context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Kiko.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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.Threading;
using MindTouch.Tasking;
using MindTouch.Threading;
namespace MindTouch.Collections {
/// <summary>
/// Provides a mechanism for dispatching work items against an <see cref="IDispatchQueue"/>.
/// </summary>
/// <typeparam name="T">Type of work item that can be dispatched.</typeparam>
public class ProcessingQueue<T> : IThreadsafeQueue<T>, IDisposable {
//--- Class Methods ---
private static Action<T, Action> MakeHandlerWithCompletion(Action<T> handler) {
return (item, completion) => {
try {
handler(item);
} finally {
completion();
}
};
}
//--- Fields ---
private readonly Action<T, Action> _handler;
private readonly IDispatchQueue _dispatchQueue;
private readonly LockFreeItemConsumerQueue<T> _inbox;
private bool _disposed;
private int _capacity;
//--- Constructors ---
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type and with completion callback.</param>
/// <param name="maxParallelism">Maximum number of items being dispatch simultaneously against the dispatch queue.</param>
/// <param name="dispatchQueue">Dispatch queue for work items.</param>
public ProcessingQueue(Action<T, Action> handler, int maxParallelism, IDispatchQueue dispatchQueue) {
if(dispatchQueue == null) {
throw new ArgumentNullException("dispatchQueue");
}
if(handler == null) {
throw new ArgumentNullException("handler");
}
if(maxParallelism <= 0) {
throw new ArgumentException("maxParallelism must be greater than 0", "maxParallelism");
}
_handler = handler;
_capacity = maxParallelism;
_dispatchQueue = dispatchQueue;
// check if we need an item holding queue
if(maxParallelism < int.MaxValue) {
_inbox = new LockFreeItemConsumerQueue<T>();
}
}
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type and with completion callback.</param>
/// <param name="dispatchQueue">Dispatch queue for work items.</param>
public ProcessingQueue(Action<T, Action> handler, IDispatchQueue dispatchQueue) : this(handler, int.MaxValue, dispatchQueue) { }
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type and with completion callback.</param>
/// <param name="maxParallelism">Maximum number of items being dispatch simultaneously against the dispatch queue.</param>
public ProcessingQueue(Action<T, Action> handler, int maxParallelism) : this(handler, maxParallelism, Async.GlobalDispatchQueue) { }
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type and with completion callback.</param>
public ProcessingQueue(Action<T, Action> handler) : this(handler, int.MaxValue, Async.GlobalDispatchQueue) { }
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type.</param>
/// <param name="maxParallelism">Maximum number of items being dispatch simultaneously against the dispatch queue.</param>
/// <param name="dispatchQueue">Dispatch queue for work items.</param>
public ProcessingQueue(Action<T> handler, int maxParallelism, IDispatchQueue dispatchQueue) : this(MakeHandlerWithCompletion(handler), maxParallelism, dispatchQueue) { }
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type.</param>
/// <param name="dispatchQueue">Dispatch queue for work items.</param>
public ProcessingQueue(Action<T> handler, IDispatchQueue dispatchQueue) : this(handler, int.MaxValue, dispatchQueue) { }
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type and with completion callback.</param>
/// <param name="maxParallelism">Maximum number of items being dispatch simultaneously against the dispatch queue.</param>
public ProcessingQueue(Action<T> handler, int maxParallelism) : this(handler, maxParallelism, Async.GlobalDispatchQueue) { }
/// <summary>
/// Create an instance of the work queue.
/// </summary>
/// <param name="handler">Dispatch action for work item Type and with completion callback.</param>
public ProcessingQueue(Action<T> handler) : this(handler, int.MaxValue, Async.GlobalDispatchQueue) { }
//--- Properties ---
/// <summary>
/// <see langword="True"/> if the queue is empty.
/// </summary>
public bool IsEmpty { get { return (_inbox != null) ? _inbox.ItemIsEmpty : true; } }
/// <summary>
/// Total number of items in queue.
/// </summary>
public int Count { get { return (_inbox != null) ? _inbox.ItemCount : 0; } }
//--- Methods ---
/// <summary>
/// Try to queue a work item for dispatch.
/// </summary>
/// <param name="item">Item to add to queue.</param>
/// <returns><see langword="True"/> if the enqueue succeeded.</returns>
public bool TryEnqueue(T item) {
if((_inbox != null) && (Interlocked.Decrement(ref _capacity) < 0)) {
return _inbox.TryEnqueue(item);
}
return TryStartWorkItem(item);
}
/// <summary>
/// This method is not supported and throws <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
/// <exception cref="NotSupportedException"/>
public bool TryDequeue(out T item) {
if(_inbox != null) {
return _inbox.TryDequeue(out item);
}
item = default(T);
return false;
}
/// <summary>
/// Release the resources reserved by the work queue from the global thread pool.
/// </summary>
public void Dispose() {
if(!_disposed) {
_disposed = true;
// check if the dispatch queue needs to be disposed
IDisposable disposable = _dispatchQueue as IDisposable;
if(disposable != null) {
disposable.Dispose();
}
}
}
private bool TryStartWorkItem(T item) {
return _dispatchQueue.TryQueueWorkItem(() => _handler(item, EndWorkItem));
}
private void StartWorkItem(T item) {
if(!TryStartWorkItem(item)) {
throw new NotSupportedException("TryStartWorkItem failed");
}
}
private void EndWorkItem() {
if((_inbox != null) && (Interlocked.Increment(ref _capacity) <= 0)) {
if(!_inbox.TryEnqueue(StartWorkItem)) {
throw new NotSupportedException("TryEnqueue failed");
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using Orleans.Hosting;
using Orleans.Transactions.TestKit.Correctnesss;
namespace Orleans.Transactions.TestKit
{
public class TransactionRecoveryTestsRunner : TransactionTestRunnerBase
{
private static readonly TimeSpan RecoveryTimeout = TimeSpan.FromSeconds(60);
// reduce to or remove once we fix timeouts abort
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(1);
private readonly Random random;
private readonly TestCluster testCluster;
private readonly ILogger logger;
protected void Log(string message)
{
this.testOutput($"[{DateTime.Now}] {message}");
this.logger.LogInformation(message);
}
private class ExpectedGrainActivity
{
public ExpectedGrainActivity(Guid grainId, ITransactionalBitArrayGrain grain)
{
this.GrainId = grainId;
this.Grain = grain;
}
public Guid GrainId { get; }
public ITransactionalBitArrayGrain Grain { get; }
public BitArrayState Expected { get; } = new BitArrayState();
public BitArrayState Unambiguous { get; } = new BitArrayState();
public List<BitArrayState> Actual { get; set; }
public async Task GetActual()
{
try
{
this.Actual = await this.Grain.Get();
} catch(Exception)
{
// allow a single retry
await Task.Delay(TimeSpan.FromSeconds(30));
this.Actual = await this.Grain.Get();
}
}
}
public TransactionRecoveryTestsRunner(TestCluster testCluster, Action<string> testOutput)
: base(testCluster.GrainFactory, testOutput)
{
this.testCluster = testCluster;
this.logger = this.testCluster.ServiceProvider.GetService<ILogger<TransactionRecoveryTestsRunner>>();
this.random = new Random();
}
public virtual Task TransactionWillRecoverAfterRandomSiloGracefulShutdown(string transactionTestGrainClassName, int concurrent)
{
return TransactionWillRecoverAfterRandomSiloFailure(transactionTestGrainClassName, concurrent, true);
}
public virtual Task TransactionWillRecoverAfterRandomSiloUnGracefulShutdown(string transactionTestGrainClassName, int concurrent)
{
return TransactionWillRecoverAfterRandomSiloFailure(transactionTestGrainClassName, concurrent, false);
}
protected virtual async Task TransactionWillRecoverAfterRandomSiloFailure(string transactionTestGrainClassName, int concurrent, bool gracefulShutdown)
{
var endOnCommand = new[] { false };
var index = new[] { 0 };
Func<int> getIndex = () => index[0]++;
List<ExpectedGrainActivity> txGrains = Enumerable.Range(0, concurrent * 2)
.Select(i => Guid.NewGuid())
.Select(grainId => new ExpectedGrainActivity(grainId, TestGrain<ITransactionalBitArrayGrain>(transactionTestGrainClassName, grainId)))
.ToList();
//ping all grains to activate them
await WakeupGrains(txGrains.Select(g=>g.Grain).ToList());
List<ExpectedGrainActivity>[] transactionGroups = txGrains
.Select((txGrain, i) => new { index = i, value = txGrain })
.GroupBy(v => v.index / 2)
.Select(g => g.Select(i => i.value).ToList())
.ToArray();
var txSucceedBeforeInterruption = await AllTxSucceed(transactionGroups, getIndex());
txSucceedBeforeInterruption.Should().BeTrue();
await ValidateResults(txGrains, transactionGroups);
// have transactions in flight when silo goes down
Task<bool> succeeding = RunWhileSucceeding(transactionGroups, getIndex, endOnCommand);
await Task.Delay(TimeSpan.FromSeconds(2));
var siloToTerminate = this.testCluster.Silos[this.random.Next(this.testCluster.Silos.Count)];
this.Log($"Warmup transaction succeeded. {(gracefulShutdown ? "Stopping" : "Killing")} silo {siloToTerminate.SiloAddress} ({siloToTerminate.Name}) and continuing");
if (gracefulShutdown)
await this.testCluster.StopSiloAsync(siloToTerminate);
else
await this.testCluster.KillSiloAsync(siloToTerminate);
this.Log("Waiting for transactions to stop completing successfully");
var complete = await Task.WhenAny(succeeding, Task.Delay(TimeSpan.FromSeconds(30)));
endOnCommand[0] = true;
bool endedOnCommand = await succeeding;
if (endedOnCommand) this.Log($"No transactions failed due to silo death. Test may not be valid");
this.Log($"Waiting for system to recover. Performed {index[0]} transactions on each group.");
var transactionGroupsRef = new[] { transactionGroups };
await TestingUtils.WaitUntilAsync(lastTry => CheckTxResult(transactionGroupsRef, getIndex, lastTry), RecoveryTimeout, RetryDelay);
this.Log($"Recovery completed. Performed {index[0]} transactions on each group. Validating results.");
await ValidateResults(txGrains, transactionGroups);
}
private Task WakeupGrains(List<ITransactionalBitArrayGrain> grains)
{
var tasks = new List<Task>();
foreach (var grain in grains)
{
tasks.Add(grain.Ping());
}
return Task.WhenAll(tasks);
}
private async Task<bool> RunWhileSucceeding(List<ExpectedGrainActivity>[] transactionGroups, Func<int> getIndex, bool[] end)
{
// Loop until failure, or getTime changes
while (await AllTxSucceed(transactionGroups, getIndex()) && !end[0])
{
}
return end[0];
}
private async Task<bool> CheckTxResult(List<ExpectedGrainActivity>[][] transactionGroupsRef, Func<int> getIndex, bool assertIsTrue)
{
// only retry failed transactions
transactionGroupsRef[0] = await RunAllTxReportFailed(transactionGroupsRef[0], getIndex());
bool succeed = transactionGroupsRef[0] == null;
this.Log($"All transactions succeed after interruption : {succeed}");
if (assertIsTrue)
{
//consider it recovered if all tx succeed
this.Log($"Final check : {succeed}");
succeed.Should().BeTrue();
return succeed;
}
else
{
return succeed;
}
}
// Runs all transactions and returns failed;
private async Task<List<ExpectedGrainActivity>[]> RunAllTxReportFailed(List<ExpectedGrainActivity>[] transactionGroups, int index)
{
List<Task> tasks = transactionGroups
.Select(p => SetBit(p, index))
.ToList();
try
{
await Task.WhenAll(tasks);
return null;
}
catch (Exception)
{
// Collect the indices of the transaction groups which failed their transactions for diagnostics.
List<ExpectedGrainActivity>[] failedGroups = tasks.Select((task, i) => new { task, i }).Where(t => t.task.IsFaulted).Select(t => transactionGroups[t.i]).ToArray();
this.Log($"Some transactions failed. Index: {index}. {failedGroups.Length} out of {tasks.Count} failed. Failed groups: {string.Join(", ", failedGroups.Select(transactionGroup => string.Join(":", transactionGroup.Select(a => a.GrainId))))}");
return failedGroups;
}
}
private async Task<bool> AllTxSucceed(List<ExpectedGrainActivity>[] transactionGroups, int index)
{
// null return indicates none failed
return (await RunAllTxReportFailed(transactionGroups, index) == null);
}
private async Task SetBit(List<ExpectedGrainActivity> grains, int index)
{
try
{
await this.grainFactory.GetGrain<ITransactionCoordinatorGrain>(Guid.NewGuid()).MultiGrainSetBit(grains.Select(v => v.Grain).ToList(), index);
grains.ForEach(g =>
{
g.Expected.Set(index, true);
g.Unambiguous.Set(index, true);
});
}
catch (OrleansTransactionAbortedException e)
{
this.Log($"Some transactions failed. Index: {index}: Exception: {e.GetType().Name}");
grains.ForEach(g =>
{
g.Expected.Set(index, false);
g.Unambiguous.Set(index, true);
});
throw;
}
catch (Exception e)
{
this.Log($"Ambiguous transaction failure. Index: {index}: Exception: {e.GetType().Name}");
grains.ForEach(g =>
{
g.Expected.Set(index, false);
g.Unambiguous.Set(index, false);
});
throw;
}
}
private async Task ValidateResults(List<ExpectedGrainActivity> txGrains, List<ExpectedGrainActivity>[] transactionGroups)
{
await Task.WhenAll(txGrains.Select(a => a.GetActual()));
this.Log($"Got all {txGrains.Count} actual values");
bool pass = true;
foreach (List<ExpectedGrainActivity> transactionGroup in transactionGroups)
{
if (transactionGroup.Count == 0) continue;
BitArrayState first = transactionGroup[0].Actual.FirstOrDefault();
foreach (ExpectedGrainActivity activity in transactionGroup.Skip(1))
{
BitArrayState actual = activity.Actual.FirstOrDefault();
BitArrayState difference = first ^ actual;
if (difference.Value.Any(v => v != 0))
{
this.Log($"Activity on grain {activity.GrainId} did not match activity on {transactionGroup[0].GrainId}:\n"
+ $"{first} ^\n"
+ $"{actual} = \n"
+ $"{difference}\n"
+ $"Activation: {activity.GrainId}");
pass = false;
}
}
}
int i = 0;
foreach (ExpectedGrainActivity activity in txGrains)
{
BitArrayState expected = activity.Expected;
BitArrayState unambiguous = activity.Unambiguous;
BitArrayState unambuguousExpected = expected & unambiguous;
List<BitArrayState> actual = activity.Actual;
BitArrayState first = actual.FirstOrDefault();
if (first == null)
{
this.Log($"No activity for {i} ({activity.GrainId})");
pass = false;
continue;
}
int j = 0;
foreach (BitArrayState result in actual)
{
// skip comparing first to first.
if (ReferenceEquals(first, result)) continue;
// Check if each state is identical to the first state.
var difference = result ^ first;
if (difference.Value.Any(v => v != 0))
{
this.Log($"Activity on grain {i}, state {j} did not match 'first':\n"
+ $" {first}\n"
+ $"^ {result}\n"
+ $"= {difference}\n"
+ $"Activation: {activity.GrainId}");
pass = false;
}
j++;
}
// Check if the unambiguous portions of the first match.
var unambiguousFirst = first & unambiguous;
var unambiguousDifference = unambuguousExpected ^ unambiguousFirst;
if (unambiguousDifference.Value.Any(v => v != 0))
{
this.Log(
$"First state on grain {i} did not match 'expected':\n"
+ $" {unambuguousExpected}\n"
+ $"^ {unambiguousFirst}\n"
+ $"= {unambiguousDifference}\n"
+ $"Activation: {activity.GrainId}");
pass = false;
}
i++;
}
this.Log($"Report complete : {pass}");
pass.Should().BeTrue();
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
using MSBuildConstruction = Microsoft.Build.Construction;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
#region constants
internal const string Debug = "Debug";
internal const string Release = "Release";
internal const string AnyCPU = "AnyCPU";
#endregion
#region fields
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private List<OutputGroup> outputGroups;
private IProjectConfigProperties configurationProperties;
private IVsProjectFlavorCfg flavoredCfg;
private BuildableProjectConfig buildableCfg;
#endregion
#region properties
public ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
public string ConfigName
{
get
{
return this.configName;
}
set
{
this.configName = value;
}
}
public virtual object ConfigurationProperties
{
get
{
if(this.configurationProperties == null)
{
this.configurationProperties = new ProjectConfigProperties(this);
}
return this.configurationProperties;
}
}
protected IList<OutputGroup> OutputGroups
{
get
{
if(null == this.outputGroups)
{
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if(groupNames != null)
{
// Populate the output array
foreach(KeyValuePair<string, string> group in groupNames)
{
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
public ProjectConfig(ProjectNode project, string configuration)
{
this.project = project;
this.configName = configuration;
// Because the project can be aggregated by a flavor, we need to make sure
// we get the outer most implementation of that interface (hence: project --> IUnknown --> Interface)
IntPtr projectUnknown = Marshal.GetIUnknownForObject(this.ProjectMgr);
try
{
IVsProjectFlavorCfgProvider flavorCfgProvider = (IVsProjectFlavorCfgProvider)Marshal.GetTypedObjectForIUnknown(projectUnknown, typeof(IVsProjectFlavorCfgProvider));
ErrorHandler.ThrowOnFailure(flavorCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
if(flavoredCfg == null)
throw new COMException();
}
finally
{
if(projectUnknown != IntPtr.Zero)
Marshal.Release(projectUnknown);
}
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if(null != persistXML)
{
this.project.LoadXmlFragment(persistXML, this.DisplayName);
}
}
#endregion
#region methods
protected virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group)
{
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean)
{
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache)
{
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
{
if(!this.project.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
// Signal the output groups that something is changed
foreach(OutputGroup group in this.OutputGroups)
{
group.InvalidateGroup();
}
this.project.SetProjectFileDirty(true);
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition)
{
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0)
{
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups)
{
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase))
{
newGroup = group;
break;
}
}
if (newGroup == null)
{
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0)
{
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType)
{
int isDirty = 0;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment)
{
fragment = null;
int hr = VSConstants.S_OK;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name)
{
name = DisplayName;
return VSConstants.S_OK;
}
private string DisplayName
{
get
{
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if(!string.IsNullOrEmpty(platform[0]))
{
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug)
{
fDebug = 0;
if(this.configName == "Debug")
{
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease)
{
CCITracing.TraceCall();
fRelease = 0;
if(this.configName == "Release")
{
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo)
{
CCITracing.TraceCall();
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb)
{
CCITracing.TraceCall();
if(buildableCfg == null)
buildableCfg = new BuildableProjectConfig(this);
pb = buildableCfg;
return VSConstants.S_OK;
}
public virtual int get_CanonicalName(out string name)
{
return ((IVsCfg)this).get_DisplayName(out name);
}
public virtual int get_IsPackaged(out int pkgd)
{
CCITracing.TraceCall();
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f)
{
CCITracing.TraceCall();
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform)
{
CCITracing.TraceCall();
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p)
{
CCITracing.TraceCall();
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if(cfgProvider != null)
{
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root)
{
CCITracing.TraceCall();
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target)
{
CCITracing.TraceCall();
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li)
{
if (li == null)
{
throw new ArgumentNullException("li");
}
CCITracing.TraceCall();
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output)
{
CCITracing.TraceCall();
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public virtual int DebugLaunch(uint grfLaunch)
{
CCITracing.TraceCall();
try
{
VsDebugTargetInfo info = new VsDebugTargetInfo();
info.cbSize = (uint)Marshal.SizeOf(info);
info.dlo = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
// On first call, reset the cache, following calls will use the cached values
string property = GetConfigurationProperty("StartProgram", true);
if(string.IsNullOrEmpty(property))
{
info.bstrExe = this.project.GetOutputAssembly(this.ConfigName);
}
else
{
info.bstrExe = property;
}
property = GetConfigurationProperty("WorkingDirectory", false);
if(string.IsNullOrEmpty(property))
{
info.bstrCurDir = Path.GetDirectoryName(info.bstrExe);
}
else
{
info.bstrCurDir = property;
}
property = GetConfigurationProperty("CmdArgs", false);
if(!string.IsNullOrEmpty(property))
{
info.bstrArg = property;
}
property = GetConfigurationProperty("RemoteDebugMachine", false);
if(property != null && property.Length > 0)
{
info.bstrRemoteMachine = property;
}
info.fSendStdoutToOutputWindow = 0;
property = GetConfigurationProperty("EnableUnmanagedDebugging", false);
if(property != null && string.Compare(property, "true", StringComparison.OrdinalIgnoreCase) == 0)
{
//Set the unmanged debugger
//TODO change to vsconstant when it is available in VsConstants (guidNativeOnlyEng was the old name, maybe it has got a new name)
info.clsidCustom = new Guid("{3B476D35-A401-11D2-AAD4-00C04F990171}");
}
else
{
//Set the managed debugger
info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
}
info.grfLaunch = grfLaunch;
VsShellUtilities.LaunchDebugger(this.project.Site, info);
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
return Marshal.GetHRForException(e);
}
return VSConstants.S_OK;
}
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch)
{
CCITracing.TraceCall();
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if(fCanLaunch == 0)
{
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup)
{
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach(OutputGroup group in OutputGroups)
{
string groupName;
group.get_CanonicalName(out groupName);
if(String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0)
{
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot)
{
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate)
{
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual)
{
// Are they only asking for the number of groups?
if(celt == 0)
{
if((null == pcActual) || (0 == pcActual.Length))
{
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if((null == rgpcfg) || (rgpcfg.Length == 0))
{
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach(OutputGroup group in OutputGroups)
{
if(rgpcfg.Length > count && celt > count && group != null)
{
rgpcfg[count] = group;
++count;
}
}
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot)
{
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg)
{
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
if(this.project == null || this.project.NodeProperties == null)
{
throw new InvalidOperationException();
}
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
/// <summary>
/// Splits the canonical configuration name into platform and configuration name.
/// </summary>
/// <param name="canonicalName">The canonicalName name.</param>
/// <param name="configName">The name of the configuration.</param>
/// <param name="platformName">The name of the platform.</param>
/// <returns>true if successfull.</returns>
internal static bool TrySplitConfigurationCanonicalName(string canonicalName, out string configName, out string platformName)
{
configName = String.Empty;
platformName = String.Empty;
if(String.IsNullOrEmpty(canonicalName))
{
return false;
}
string[] splittedCanonicalName = canonicalName.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if(splittedCanonicalName == null || (splittedCanonicalName.Length != 1 && splittedCanonicalName.Length != 2))
{
return false;
}
configName = splittedCanonicalName[0];
if(splittedCanonicalName.Length == 2)
{
platformName = splittedCanonicalName[1];
}
return true;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache)
{
if (resetCache || this.currentConfig == null)
{
// Get properties for current configuration from project file and cache it
this.project.SetConfiguration(this.ConfigName);
this.project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
this.currentConfig = this.project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
if (this.currentConfig == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return this.currentConfig.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
if(pages == null)
{
throw new ArgumentNullException("pages");
}
if(pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = HierarchyNode.GetOuterHierarchy(this.project);
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if(guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close()
{
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if(iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
else if(iidCfg == typeof(IVsBuildableProjectCfg).GUID)
{
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
// If not supported
if(ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
//=============================================================================
// NOTE: advises on out of proc build execution to maximize
// future cross-platform targeting capabilities of the VS tools.
[CLSCompliant(false)]
[ComVisible(true)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Buildable")]
public class BuildableProjectConfig : IVsBuildableProjectCfg
{
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config)
{
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie)
{
CCITracing.TraceCall();
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p)
{
CCITracing.TraceCall();
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 0; // TODO:
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done)
{
CCITracing.TraceCall();
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
public virtual int Stop(int fsync)
{
CCITracing.TraceCall();
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie)
{
CCITracing.TraceCall();
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin()
{
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0)
{
return false;
}
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget)
{
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
finally
{
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful))
{
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target)
{
if (!this.NotifyBuildBegin())
{
return;
}
try
{
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
}
finally
{
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences()
{
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
foreach(ReferenceNode referenceNode in referenceContainer.EnumReferences())
{
referenceNode.RefreshReference();
}
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CopyEngineResult.cs" company="public domain">
// Based upon MSDN public domain software by Stephen Toub
// </copyright>
// <summary>
// The copy engine result codes.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace FileOperation
{
/// <summary>
/// The copy engine result.
/// </summary>
public enum CopyEngineResult : uint
{
/// <summary>
/// The success copy
/// </summary>
OK = 0x0,
/// <summary>
/// The success yes.
/// </summary>
SuccessYes = 0x00270001,
/// <summary>
/// The success not handled.
/// </summary>
SuccessNotHandled = 0x00270003,
/// <summary>
/// The success user retry.
/// </summary>
SuccessUserRetry = 0x00270004,
/// <summary>
/// The success user ignored.
/// </summary>
SuccessUserIgnored = 0x00270005,
/// <summary>
/// The success merge.
/// </summary>
SuccessMerge = 0x00270006,
/// <summary>
/// The success dont process children.
/// </summary>
SuccessDontProcessChildren = 0x00270008,
/// <summary>
/// The success already done.
/// </summary>
SuccessAlreadyDone = 0x0027000A,
/// <summary>
/// The success pending.
/// </summary>
SuccessPending = 0x0027000B,
/// <summary>
/// The success keep both.
/// </summary>
SuccessKeepBoth = 0x0027000C,
/// <summary>
/// The success close program.
/// </summary>
SuccessCloseProgram = 0x0027000D, // Close the program using the current file
/// <summary>
/// The error User wants to canceled entire job
/// </summary>
ErrorUserCancelled = 0x80270000,
/// <summary>
/// The error Engine wants to canceled entire job, don't set the CANCELLED bit
/// </summary>
ErrorCancelled = 0x80270001,
/// <summary>
/// The error Need to elevate the process to complete the operation
/// </summary>
ErrorRequiresElevation = 0x80270002,
/// <summary>
/// The error Source and destination file are the same
/// </summary>
ErrorSameFile = 0x80270003,
/// <summary>
/// The error Trying to rename a file into a different location, use move instead.
/// </summary>
ErrorDiffDir = 0x80270004,
/// <summary>
/// The error One source specified, multiple destinations
/// </summary>
ErrorManySrc1Dest = 0x80270005,
/// <summary>
/// The error The destination is a sub-tree of the source
/// </summary>
ErrorDestSubtree = 0x80270009,
/// <summary>
/// The error The destination is the same folder as the source
/// </summary>
ErrorDestSameTree = 0x8027000A,
/// <summary>
/// The error fld is file dest.
/// </summary>
ErrorFldIsFileDest = 0x8027000B, // Existing destination file with same name as folder
/// <summary>
/// The error file is fld dest.
/// </summary>
ErrorFileIsFldDest = 0x8027000C, // Existing destination folder with same name as file
/// <summary>
/// The error file too large.
/// </summary>
ErrorFileTooLarge = 0x8027000D, // File too large for destination file system
/// <summary>
/// Destination device is full and happens to be removable
/// </summary>
ErrorRemovableFull = 0x8027000E,
/// <summary>
/// The error dest is ro cd.
/// </summary>
ErrorDestIsRoCd = 0x8027000F, // Destination is a Read-Only CDRom, possibly unformatted
/// <summary>
/// The error_ des t_ i s_ r w_ cd.
/// </summary>
ErrorDestIsRwCd = 0x80270010, // Destination is a Read/Write CDRom, possibly unformatted
/// <summary>
/// The error Destination is a Recordable (Audio, CDRom, possibly unformatted
/// </summary>
ErrorDestIsRCd = 0x80270011,
/// <summary>
/// The error Destination is a Read-Only DVD, possibly unformatted
/// </summary>
ErrorDestIsRoDvd = 0x80270012,
/// <summary>
/// The error Destination is a Read/Wrote DVD, possibly unformatted
/// </summary>
ErrorDestIsRwDvd = 0x80270013,
/// <summary>
/// The error Destination is a Recordable (Audio, DVD, possibly unformatted
/// </summary>
ErrorDestIsRDvd = 0x80270014,
/// <summary>
/// The errorSource is a Read-Only CDRom, possibly unformatted
/// </summary>
ErrorSourceIsRoCd = 0x80270015,
/// <summary>
/// The error Source is a Read/Write (Audio, CDRom, possibly unformatted
/// </summary>
ErrorSourceIsRwCd = 0x80270016,
/// <summary>
/// The error Source is a Recordable (Audio, CDRom, possibly unformatted
/// </summary>
ErrorSourceIsRCd = 0x80270017,
/// <summary>
/// The error Source is a Read-Only DVD, possibly unformatted
/// </summary>
ErrorSourceIsRoDvd = 0x80270018,
/// <summary>
/// The error Source is a Read/Wrote DVD, possibly unformatted
/// </summary>
ErrorSourceIsRwDvd = 0x80270019,
/// <summary>
/// The error Source is a Recordable (Audio, DVD, possibly unformatted.
/// </summary>
ErrorSourceIsRDvd = 0x8027001A,
/// <summary>
/// The error Invalid source path
/// </summary>
ErrorInvalidFilesSrc = 0x8027001B,
/// <summary>
/// The error Invalid destination path
/// </summary>
ErrorInvalidFilesDest = 0x8027001C,
/// <summary>
/// The error Source Files within folders where the overall path is longer than MAX_PATH
/// </summary>
ErrorPathTooDeepSrc = 0x8027001D,
/// <summary>
/// The error Destination files would be within folders where the overall path is longer than MAX_PATH
/// </summary>
ErrorPathTooDeepDest = 0x8027001E,
/// <summary>
/// The error Source is a root directory, cannot be moved or renamed
/// </summary>
ErrorRootDirSrc = 0x8027001F,
/// <summary>
/// The error Destination is a root directory, cannot be renamed
/// </summary>
ErrorRootDirDest = 0x80270020,
/// <summary>
/// The error Security problem on source
/// </summary>
ErrorAccessDeniedSrc = 0x80270021,
/// <summary>
/// The error Security problem on destination
/// </summary>
ErrorAccessDeniedDest = 0x80270022,
/// <summary>
/// The error Source file does not exist, or is unavailable.
/// </summary>
ErrorPathNotFoundSrc = 0x80270023,
/// <summary>
/// The error Destination file does not exist, or is unavailable
/// </summary>
ErrorPathNotFoundDest = 0x80270024,
/// <summary>
/// The error Source file is on a disconnected network location
/// </summary>
ErrorNetDisconnectSrc = 0x80270025,
/// <summary>
/// The error Destination file is on a disconnected network location
/// </summary>
ErrorNetDisconnectDest = 0x80270026,
/// <summary>
/// The error Sharing Violation on source
/// </summary>
ErrorSharingViolationSrc = 0x80270027,
/// <summary>
/// The error Sharing Violation on destination
/// </summary>
ErrorSharingViolationDest = 0x80270028,
/// <summary>
/// The error Destination exists, cannot replace
/// </summary>
ErrorAlreadyExistsNormal = 0x80270029,
/// <summary>
/// The error Destination with read-only attribute exists, cannot replace
/// </summary>
ErrorAlreadyExistsReadonly = 0x8027002A,
/// <summary>
/// The error Destination with system attribute exists, cannot replace
/// </summary>
ErrorAlreadyExistsSystem = 0x8027002B,
/// <summary>
/// The error Destination folder exists, cannot replace
/// </summary>
ErrorAlreadyExistsFolder = 0x8027002C,
/// <summary>
/// The error Secondary Stream information would be lost
/// </summary>
ErrorStreamLoss = 0x8027002D,
/// <summary>
/// The error Extended Attributes would be lost.
/// </summary>
ErrorEaLoss = 0x8027002E,
/// <summary>
/// The error Property would be lost
/// </summary>
ErrorPropertyLoss = 0x8027002F,
/// <summary>
/// The error Properties would be lost
/// </summary>
ErrorPropertiesLoss = 0x80270030,
/// <summary>
/// The error Encryption would be lost.
/// </summary>
ErrorEncryptionLoss = 0x80270031,
/// <summary>
/// Entire operation likely won't fit
/// </summary>
ErrorDiskFull = 0x80270032,
/// <summary>
/// The errorEntire operation likely won't fit, clean-up wizard available
/// </summary>
ErrorDiskFullClean = 0x80270033,
/// <summary>
/// The error Can't reach source folder
/// </summary>
ErrorCantReachSource = 0x80270035,
/// <summary>
/// The error_ recycl e_ unknow n_ error.
/// </summary>
ErrorRecycleUnknownError = 0x80270035,
/// <summary>
/// The error Recycling not available (usually turned off
/// </summary>
ErrorRecycleForceNuke = 0x80270036,
/// <summary>
/// The error Item is too large for the recycle-bin
/// </summary>
ErrorRecycleSizeTooBig = 0x80270037,
/// <summary>
/// The error Folder is too deep to fit in the recycle-bin
/// </summary>
ErrorRecyclePathTooLong = 0x80270038,
/// <summary>
/// The error Recycle bin could not be found or is unavailable
/// </summary>
ErrorRecycleBinNotFound = 0x8027003A,
/// <summary>
/// The error Name of the new file being created is too long
/// </summary>
ErrorNewfileNameTooLong = 0x8027003B,
/// <summary>
/// The error Name of the new folder being created is too long
/// </summary>
ErrorNewfolderNameTooLong = 0x8027003C,
/// <summary>
/// The error The directory being processed is not empty
/// </summary>
ErrorDirNotEmpty = 0x8027003D,
/// <summary>
/// The netcach the item requested is in the negative net parsing cache
/// </summary>
NetcacheNegativeCache = 0x80270100,
/// <summary>
/// The execut for returned by command delegates to indicate that they did no work
/// </summary>
ExecuteLaunchApplication = 0x80270101,
/// <summary>
/// The shell returned when trying to create a thumbnail extractor at too low a bitdepth for high fidelity
/// </summary>
ShellWrongBitdepth = 0x80270102
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Interfaces;
namespace OpenSim.Region.CoreModules.World.Terrain
{
public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
{
#region StandardTerrainEffects enum
/// <summary>
/// A standard set of terrain brushes and effects recognised by viewers
/// </summary>
public enum StandardTerrainEffects : byte
{
Flatten = 0,
Raise = 1,
Lower = 2,
Smooth = 3,
Noise = 4,
Revert = 5,
// Extended brushes
Erode = 255,
Weather = 254,
Olsen = 253
}
#endregion
public const float MinParcelResolution = 4.0f; // smallest parcel is 4m x 4m = 16sqm
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("terrain");
private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
private ITerrainChannel m_channel;
private Dictionary<string, ITerrainEffect> m_plugineffects;
private ITerrainChannel m_revert;
private Scene m_scene;
private volatile bool m_tainted;
#region ICommandableModule Members
public ICommander CommandInterface
{
get { return m_commander; }
}
#endregion
#region INonSharedRegionModule Members
/// <summary>
/// Creates and initializes a terrain module for a region
/// </summary>
/// <param name="scene">Region initializing</param>
/// <param name="config">Config for the region</param>
public void Initialize(IConfigSource config)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
// Install terrain module in the simulator
lock (m_scene)
{
if (m_scene.Heightmap == null)
{
m_channel = new TerrainChannel();
m_scene.Heightmap = m_channel;
m_revert = new TerrainChannel();
UpdateRevertMap();
}
else
{
m_channel = m_scene.Heightmap;
m_revert = new TerrainChannel();
UpdateRevertMap();
}
m_scene.RegisterModuleInterface<ITerrainModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
InstallInterfaces();
}
InstallDefaultEffects();
LoadPlugins();
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
lock (m_scene)
{
// remove the commands
m_scene.UnregisterModuleCommander(m_commander.Name);
// remove the event-handlers
m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
// remove the interface
m_scene.UnregisterModuleInterface<ITerrainModule>(this);
}
}
public void Close()
{
}
public string Name
{
get { return "TerrainModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region ITerrainModule Members
/// <summary>
/// Loads a terrain file from disk and installs it in the scene.
/// </summary>
/// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
public void LoadFromFile(string filename)
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
try
{
ITerrainChannel channel = loader.Value.LoadFile(filename);
if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize)
{
// TerrainChannel expects a RegionSize x RegionSize map, currently
throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
Constants.RegionSize, Constants.RegionSize));
}
m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
catch (NotImplementedException)
{
m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
" parser does not support file loading. (May be save only)");
throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
}
catch (FileNotFoundException)
{
m_log.Error(
"[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
throw new TerrainException(
String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
}
catch (ArgumentException e)
{
m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
throw new TerrainException(
String.Format("Unable to load heightmap: {0}", e.Message));
}
}
CheckForTerrainUpdates();
m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
return;
}
}
m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
}
/// <summary>
/// Saves the current heightmap to a specified file.
/// </summary>
/// <param name="filename">The destination filename</param>
public void SaveToFile(string filename)
{
try
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
loader.Value.SaveFile(filename, m_channel);
return;
}
}
}
catch (NotImplementedException)
{
m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
}
catch (IOException ioe)
{
m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message));
}
}
/// <summary>
/// Loads a terrain file from a stream and installs it in the scene.
/// </summary>
/// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
/// <param name="stream"></param>
public void LoadFromStream(string filename, Stream stream)
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (@filename.EndsWith(loader.Key))
{
lock (m_scene)
{
try
{
ITerrainChannel channel = loader.Value.LoadStream(stream);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
catch (NotImplementedException)
{
m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
" parser does not support file loading. (May be save only)");
throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
}
}
CheckForTerrainUpdates();
m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
return;
}
}
m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
}
/// <summary>
/// Modify Land
/// </summary>
/// <param name="pos">Land-position (X,Y,0)</param>
/// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
/// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
/// <param name="agentId">UUID of script-owner</param>
public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId)
{
float duration = 0.25f;
if (action == 0)
duration = 4.0f;
client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, -1, agentId, size);
}
/// <summary>
/// Saves the current heightmap to a specified stream.
/// </summary>
/// <param name="filename">The destination filename. Used here only to identify the image type</param>
/// <param name="stream"></param>
public void SaveToStream(string filename, Stream stream)
{
try
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
loader.Value.SaveStream(stream, m_channel);
return;
}
}
}
catch (NotImplementedException)
{
m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
}
}
public void TaintTerrain ()
{
CheckForTerrainUpdates();
}
#region Plugin Loading Methods
private void LoadPlugins()
{
m_plugineffects = new Dictionary<string, ITerrainEffect>();
// Load the files in the Terrain/ dir
string[] files = Directory.GetFiles("Terrain");
foreach (string file in files)
{
m_log.Info("Loading effects in " + file);
try
{
Assembly library = Assembly.LoadFrom(file);
foreach (Type pluginType in library.GetTypes())
{
try
{
if (pluginType.IsAbstract || pluginType.IsNotPublic)
continue;
string typeName = pluginType.Name;
if (typeof(ITerrainEffect).IsAssignableFrom(pluginType))
{
ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString()));
InstallPlugin(typeName, terEffect);
}
else if (typeof(ITerrainLoader).IsAssignableFrom(pluginType))
{
ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString()));
m_loaders[terLoader.FileExtension] = terLoader;
m_log.Info("L ... " + typeName);
}
}
catch (AmbiguousMatchException)
{
}
}
}
catch (BadImageFormatException)
{
}
}
}
public void InstallPlugin(string pluginName, ITerrainEffect effect)
{
lock (m_plugineffects)
{
if (!m_plugineffects.ContainsKey(pluginName))
{
m_plugineffects.Add(pluginName, effect);
m_log.Info("E ... " + pluginName);
}
else
{
m_plugineffects[pluginName] = effect;
m_log.Warn("E ... " + pluginName + " (Replaced)");
}
}
}
#endregion
#endregion
/// <summary>
/// Installs into terrain module the standard suite of brushes
/// </summary>
private void InstallDefaultEffects()
{
// Draggable Paint Brush Effects
m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
// Area of effect selection effects
m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
// Filesystem load/save loaders
m_loaders[".r32"] = new RAW32();
m_loaders[".f32"] = m_loaders[".r32"];
m_loaders[".ter"] = new Terragen();
m_loaders[".raw"] = new LLRAW();
m_loaders[".jpg"] = new JPEG();
m_loaders[".jpeg"] = m_loaders[".jpg"];
m_loaders[".bmp"] = new BMP();
m_loaders[".png"] = new PNG();
m_loaders[".gif"] = new GIF();
m_loaders[".tif"] = new TIFF();
m_loaders[".tiff"] = m_loaders[".tif"];
}
/// <summary>
/// Saves the current state of the region into the revert map buffer.
/// </summary>
public void UpdateRevertMap()
{
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
m_revert[x, y] = m_channel[x, y];
}
}
}
/// <summary>
/// Loads a tile from a larger terrain file and installs it into the region.
/// </summary>
/// <param name="filename">The terrain file to load</param>
/// <param name="fileWidth">The width of the file in units</param>
/// <param name="fileHeight">The height of the file in units</param>
/// <param name="fileStartX">Where to begin our slice</param>
/// <param name="fileStartY">Where to begin our slice</param>
public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
{
int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX;
int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY;
if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
{
// this region is included in the tile request
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
fileWidth, fileHeight,
(int) Constants.RegionSize,
(int) Constants.RegionSize);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
return;
}
}
}
}
/// <summary>
/// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
/// </summary>
private void EventManager_OnTerrainTick()
{
if (m_tainted)
{
m_tainted = false;
m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialized(), m_channel.IncrementRevisionNumber());
m_scene.SaveTerrain();
// Mark the worldmap as tainted so that the push to the map tile server can happen when the time comes.
m_scene.MarkMapTileTainted(WorldMapTaintReason.TerrainElevationChange);
// Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
//m_scene.CreateTerrainTexture(true);
}
}
/// <summary>
/// Processes commandline input. Do not call directly.
/// </summary>
/// <param name="args">Commandline arguments</param>
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "terrain")
{
if (args.Length == 1)
{
m_commander.ProcessConsoleCommand("help", new string[0]);
return;
}
string[] tmpArgs = new string[args.Length - 2];
int i;
for (i = 2; i < args.Length; i++)
tmpArgs[i - 2] = args[i];
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
/// <summary>
/// Installs terrain brush hook to IClientAPI
/// </summary>
/// <param name="client"></param>
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnModifyTerrain += client_OnModifyTerrain;
client.OnBakeTerrain += client_OnBakeTerrain;
}
/// <summary>
/// Checks to see if the terrain has been modified since last check
/// but won't attempt to limit those changes to the limits specified in the estate settings
/// currently invoked by the command line operations in the region server only
/// </summary>
private void CheckForTerrainUpdates()
{
CheckForTerrainUpdates(false);
}
/// <summary>
/// Checks to see if the terrain has been modified since last check.
/// If it has been modified, every all the terrain patches are sent to the client.
/// If the call is asked to respect the estate settings for terrain_raise_limit and
/// terrain_lower_limit, it will clamp terrain updates between these values
/// currently invoked by client_OnModifyTerrain only and not the Commander interfaces
/// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param>
/// </summary>
private void CheckForTerrainUpdates(bool respectEstateSettings)
{
bool shouldTaint = false;
float[] serialized = m_channel.GetFloatsSerialized();
int x;
for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize)
{
int y;
for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize)
{
if (m_channel.Tainted(x, y))
{
// if we should respect the estate settings then
// fixup and height deltas that don't respect them
if (respectEstateSettings && LimitChannelChanges(x, y))
{
// this has been vetoed, so update
// what we are going to send to the client
serialized = m_channel.GetFloatsSerialized();
}
UpdateClientsSceneView(serialized, x, y);
shouldTaint = true;
}
}
}
if (shouldTaint)
{
m_tainted = true;
}
}
/// <summary>
/// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
/// are all within the current estate limits
/// <returns>true if changes were limited, false otherwise</returns>
/// </summary>
private bool LimitChannelChanges(int xStart, int yStart)
{
bool changesLimited = false;
double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
// loop through the height map for this patch and compare it against
// the revert map
for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
{
for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
{
double requestedHeight = m_channel[x, y];
double bakedHeight = m_revert[x, y];
double requestedDelta = requestedHeight - bakedHeight;
if (requestedDelta > maxDelta)
{
m_channel[x, y] = bakedHeight + maxDelta;
changesLimited = true;
}
else if (requestedDelta < minDelta)
{
m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
changesLimited = true;
}
}
}
return changesLimited;
}
private void UpdateClientsSceneView(float[] serialized, int regionx, int regiony)
{
m_scene.ForEachScenePresence(
delegate(ScenePresence presence)
{
if (presence.SceneView != null)
presence.SceneView.TerrainPatchUpdated(serialized,
regionx / Constants.TerrainPatchSize,
regiony / Constants.TerrainPatchSize);
});
}
public bool SetTerrain(UUID userID, int x1, int y1, int x2, int y2, float height)
{
bool rc = false;
// Sanity check.
if ((height < 0.0f) || (height > 1024.0f))
return false;
int temp;
if (x1 > x2) { temp = x1; x1 = x2; x2 = temp; }
if (y1 > y2) { temp = y1; y1 = y2; y2 = temp; }
if ((x1 < 0) || (y1 < 0) || (x2 >= Constants.RegionSize) || (y2 >= Constants.RegionSize))
return false;
bool god = m_scene.Permissions.IsGod(userID);
for (int x = x1; x <= x2; x++)
{
for (int y = y1; y <= y2; y++)
{
if (god || m_scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
{
m_channel[x, y] = height;
rc = true;
}
}
}
if (rc)
CheckForTerrainUpdates(!god); //revert changes outside estate limits
return rc;
}
private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
float north, float west, float south, float east, int parcelId, UUID agentId,
float BrushSize)
{
bool god = m_scene.Permissions.IsGod(user);
bool allowed = false;
if (north == south && east == west)
{
if (m_painteffects.ContainsKey((StandardTerrainEffects) action))
{
m_painteffects[(StandardTerrainEffects)action].PaintEffect(
m_channel, user, west, south, height, size, seconds, BrushSize, m_scene);
//revert changes outside estate limits
CheckForTerrainUpdates(!god);
}
else
{
m_log.Debug("Unknown terrain brush type " + action);
}
}
else
{
if (m_floodeffects.ContainsKey((StandardTerrainEffects) action))
{
bool[,] fillArea = new bool[m_channel.Width,m_channel.Height];
fillArea.Initialize();
if (parcelId != -1)
{
// If a parcel ID is specified, the viewer sends the bottom left of each 4sqm block,
// i.e. bottom left, not top right for north and east.
// We need to add 4m to each of these to find the top and right boundaries.
north += MinParcelResolution;
east += MinParcelResolution;
// If the parcelId == -1, it means the viewer has already done this for us.
}
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
if ((x <= east) && x >= west)
{
if ((y <= north) && y >= south)
{
if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
{
fillArea[x, y] = true;
allowed = true;
}
}
}
}
}
if (allowed)
{
m_floodeffects[(StandardTerrainEffects) action].FloodEffect(
m_channel, fillArea, size);
CheckForTerrainUpdates(!god); //revert changes outside estate limits
}
}
else
{
m_log.Debug("Unknown terrain flood type " + action);
}
}
}
private void client_OnBakeTerrain(IClientAPI remoteClient)
{
// Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
// for now check a point in the centre of the region
if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
{
InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
}
}
#region Console Commands
private void InterfaceLoadFile(Object[] args)
{
LoadFromFile((string) args[0]);
CheckForTerrainUpdates();
}
private void InterfaceLoadTileFile(Object[] args)
{
LoadFromFile((string) args[0],
(int) args[1],
(int) args[2],
(int) args[3],
(int) args[4]);
CheckForTerrainUpdates();
}
private void InterfaceSaveFile(Object[] args)
{
SaveToFile((string) args[0]);
}
private void InterfaceBakeTerrain(Object[] args)
{
UpdateRevertMap();
}
private void InterfaceRevertTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] = m_revert[x, y];
CheckForTerrainUpdates();
}
private void InterfaceFlipTerrain(Object[] args)
{
String direction = (String)args[0];
if (direction.ToLower().StartsWith("y"))
{
for (int x = 0; x < Constants.RegionSize; x++)
{
for (int y = 0; y < Constants.RegionSize / 2; y++)
{
double height = m_channel[x, y];
double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y];
m_channel[x, y] = flippedHeight;
m_channel[x, (int)Constants.RegionSize - 1 - y] = height;
}
}
}
else if (direction.ToLower().StartsWith("x"))
{
for (int y = 0; y < Constants.RegionSize; y++)
{
for (int x = 0; x < Constants.RegionSize / 2; x++)
{
double height = m_channel[x, y];
double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y];
m_channel[x, y] = flippedHeight;
m_channel[(int)Constants.RegionSize - 1 - x, y] = height;
}
}
}
else
{
m_log.Error("Unrecognised direction - need x or y");
}
CheckForTerrainUpdates();
}
private void InterfaceRescaleTerrain(Object[] args)
{
double desiredMin = (double)args[0];
double desiredMax = (double)args[1];
// determine desired scaling factor
double desiredRange = desiredMax - desiredMin;
//m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
if (desiredRange == 0d)
{
// delta is zero so flatten at requested height
InterfaceFillTerrain(new Object[] { args[1] });
}
else
{
//work out current heightmap range
double currMin = double.MaxValue;
double currMax = double.MinValue;
int width = m_channel.Width;
int height = m_channel.Height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
double currHeight = m_channel[x, y];
if (currHeight < currMin)
{
currMin = currHeight;
}
else if (currHeight > currMax)
{
currMax = currHeight;
}
}
}
double currRange = currMax - currMin;
double scale = desiredRange / currRange;
//m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
//m_log.InfoFormat("Scale = {0}", scale);
// scale the heightmap accordingly
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
double currHeight = m_channel[x, y] - currMin;
m_channel[x, y] = desiredMin + (currHeight * scale);
}
}
CheckForTerrainUpdates();
}
}
private void InterfaceElevateTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] += (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceMultiplyTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] *= (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceLowerTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] -= (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceFillTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] = (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceShowDebugStats(Object[] args)
{
double max = Double.MinValue;
double min = double.MaxValue;
double sum = 0;
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
sum += m_channel[x, y];
if (max < m_channel[x, y])
max = m_channel[x, y];
if (min > m_channel[x, y])
min = m_channel[x, y];
}
}
double avg = sum / (m_channel.Height * m_channel.Width);
m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height);
m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum);
}
private void InterfaceEnableExperimentalBrushes(Object[] args)
{
if ((bool) args[0])
{
m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
}
else
{
InstallDefaultEffects();
}
}
private void InterfaceRunPluginEffect(Object[] args)
{
if ((string) args[0] == "list")
{
m_log.Info("List of loaded plugins");
foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
{
m_log.Info(kvp.Key);
}
return;
}
if ((string) args[0] == "reload")
{
LoadPlugins();
return;
}
if (m_plugineffects.ContainsKey((string) args[0]))
{
m_plugineffects[(string) args[0]].RunEffect(m_channel);
CheckForTerrainUpdates();
}
else
{
m_log.Warn("No such plugin effect loaded.");
}
}
private void InstallInterfaces()
{
// Load / Save
string supportedFileExtensions = String.Empty;
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")";
Command loadFromFileCommand =
new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
loadFromFileCommand.AddArgument("filename",
"The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
supportedFileExtensions, "String");
Command saveToFileCommand =
new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
saveToFileCommand.AddArgument("filename",
"The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
supportedFileExtensions, "String");
Command loadFromTileCommand =
new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
loadFromTileCommand.AddArgument("filename",
"The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
supportedFileExtensions, "String");
loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
"Integer");
loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
"Integer");
// Terrain adjustments
Command fillRegionCommand =
new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
"Double");
Command elevateCommand =
new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
Command lowerCommand =
new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
Command multiplyCommand =
new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
Command bakeRegionCommand =
new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
Command revertRegionCommand =
new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
Command flipCommand =
new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
Command rescaleCommand =
new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
// Debug
Command showDebugStatsCommand =
new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
"Shows some information about the regions heightmap for debugging purposes.");
Command experimentalBrushesCommand =
new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
"Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
//Plugins
Command pluginRunCommand =
new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
m_commander.RegisterCommand("load", loadFromFileCommand);
m_commander.RegisterCommand("load-tile", loadFromTileCommand);
m_commander.RegisterCommand("save", saveToFileCommand);
m_commander.RegisterCommand("fill", fillRegionCommand);
m_commander.RegisterCommand("elevate", elevateCommand);
m_commander.RegisterCommand("lower", lowerCommand);
m_commander.RegisterCommand("multiply", multiplyCommand);
m_commander.RegisterCommand("bake", bakeRegionCommand);
m_commander.RegisterCommand("revert", revertRegionCommand);
m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
m_commander.RegisterCommand("stats", showDebugStatsCommand);
m_commander.RegisterCommand("effect", pluginRunCommand);
m_commander.RegisterCommand("flip", flipCommand);
m_commander.RegisterCommand("rescale", rescaleCommand);
// Add this to our scene so scripts can call these functions
m_scene.RegisterModuleCommander(m_commander);
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="System.Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="System.Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
private readonly ConstructorInfo _parameterizedConstructor;
private ObjectConstructor<object> _parameterizedCreator;
private ObjectConstructor<object> _overrideCreator;
internal ObjectConstructor<object> ParameterizedCreator
{
get
{
if (_parameterizedCreator == null)
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get { return _overrideCreator; }
set
{
_overrideCreator = value;
// hacky
CanDeserialize = true;
}
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the collection values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the collection values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal
{
get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
else
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
if (underlyingType == typeof(IList))
CreatedType = typeof(List<object>);
if (CollectionItemType != null)
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
#if !(NET20 || NET35 || PORTABLE40)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
#endif
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>)))
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType);
IsReadOnlyOrFixedSize = true;
canDeserialize = HasParameterizedCreatorInternal;
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
#if !(NET35 || NET20)
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
_parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType);
}
#endif
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = HasParameterizedCreatorInternal;
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
#if (NET20 || NET35)
if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
{
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray))
{
ShouldCreateWrapper = true;
}
}
#endif
#if !(NET20 || NET35 || NET40)
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
CanDeserialize = true;
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
else
constructorArgument = _genericCollectionDefinitionType;
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null)
? typeof(object)
: CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}
| |
namespace Spring.Expressions.Parser.antlr.debug
{
using System;
using System.Threading;
using antlr;
using BitSet = antlr.collections.impl.BitSet;
public abstract class DebuggingCharScanner : CharScanner, DebuggingParser
{
private void InitBlock()
{
eventSupport = new ScannerEventSupport(this);
}
public virtual void setDebugMode(bool mode)
{
_notDebugMode = !mode;
}
private ScannerEventSupport eventSupport;
private bool _notDebugMode = false;
protected internal string[] ruleNames;
protected internal string[] semPredNames;
public DebuggingCharScanner(InputBuffer cb) : base(cb)
{
InitBlock();
}
public DebuggingCharScanner(LexerSharedInputState state) : base(state)
{
InitBlock();
}
public virtual void addMessageListener(MessageListener l)
{
eventSupport.addMessageListener(l);
}
public virtual void addNewLineListener(NewLineListener l)
{
eventSupport.addNewLineListener(l);
}
public virtual void addParserListener(ParserListener l)
{
eventSupport.addParserListener(l);
}
public virtual void addParserMatchListener(ParserMatchListener l)
{
eventSupport.addParserMatchListener(l);
}
public virtual void addParserTokenListener(ParserTokenListener l)
{
eventSupport.addParserTokenListener(l);
}
public virtual void addSemanticPredicateListener(SemanticPredicateListener l)
{
eventSupport.addSemanticPredicateListener(l);
}
public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l)
{
eventSupport.addSyntacticPredicateListener(l);
}
public virtual void addTraceListener(TraceListener l)
{
eventSupport.addTraceListener(l);
}
public override void consume()
{
int la_1 = - 99;
try
{
la_1 = LA(1);
}
catch (CharStreamException)
{
}
base.consume();
eventSupport.fireConsume(la_1);
}
protected internal virtual void fireEnterRule(int num, int data)
{
if (isDebugMode())
eventSupport.fireEnterRule(num, inputState.guessing, data);
}
protected internal virtual void fireExitRule(int num, int ttype)
{
if (isDebugMode())
eventSupport.fireExitRule(num, inputState.guessing, ttype);
}
protected internal virtual bool fireSemanticPredicateEvaluated(int type, int num, bool condition)
{
if (isDebugMode())
return eventSupport.fireSemanticPredicateEvaluated(type, num, condition, inputState.guessing);
else
return condition;
}
protected internal virtual void fireSyntacticPredicateFailed()
{
if (isDebugMode())
eventSupport.fireSyntacticPredicateFailed(inputState.guessing);
}
protected internal virtual void fireSyntacticPredicateStarted()
{
if (isDebugMode())
eventSupport.fireSyntacticPredicateStarted(inputState.guessing);
}
protected internal virtual void fireSyntacticPredicateSucceeded()
{
if (isDebugMode())
eventSupport.fireSyntacticPredicateSucceeded(inputState.guessing);
}
public virtual string getRuleName(int num)
{
return ruleNames[num];
}
public virtual string getSemPredName(int num)
{
return semPredNames[num];
}
public virtual void goToSleep()
{
lock(this)
{
try
{
Monitor.Wait(this);
}
catch (System.Threading.ThreadInterruptedException)
{
}
}
}
public virtual bool isDebugMode()
{
return !_notDebugMode;
}
public override char LA(int i)
{
char la = base.LA(i);
eventSupport.fireLA(i, la);
return la;
}
protected internal override IToken makeToken(int t)
{
// do something with char buffer???
// try {
// IToken tok = (Token)tokenObjectClass.newInstance();
// tok.setType(t);
// // tok.setText(getText()); done in generated lexer now
// tok.setLine(line);
// return tok;
// }
// catch (InstantiationException ie) {
// panic("can't instantiate a Token");
// }
// catch (IllegalAccessException iae) {
// panic("Token class is not accessible");
// }
return base.makeToken(t);
}
public override void match(int c)
{
char la_1 = LA(1);
try
{
base.match(c);
eventSupport.fireMatch(Convert.ToChar(c), inputState.guessing);
}
catch (MismatchedCharException e)
{
if (inputState.guessing == 0)
eventSupport.fireMismatch(la_1, Convert.ToChar(c), inputState.guessing);
throw e;
}
}
public override void match(BitSet b)
{
string text = this.text.ToString();
char la_1 = LA(1);
try
{
base.match(b);
eventSupport.fireMatch(la_1, b, text, inputState.guessing);
}
catch (MismatchedCharException e)
{
if (inputState.guessing == 0)
eventSupport.fireMismatch(la_1, b, text, inputState.guessing);
throw e;
}
}
public override void match(string s)
{
System.Text.StringBuilder la_s = new System.Text.StringBuilder("");
int len = s.Length;
// peek at the next len worth of characters
try
{
for (int i = 1; i <= len; i++)
{
la_s.Append(base.LA(i));
}
}
catch (System.Exception)
{
}
try
{
base.match(s);
eventSupport.fireMatch(s, inputState.guessing);
}
catch (MismatchedCharException e)
{
if (inputState.guessing == 0)
eventSupport.fireMismatch(la_s.ToString(), s, inputState.guessing);
throw e;
}
}
public override void matchNot(int c)
{
char la_1 = LA(1);
try
{
base.matchNot(c);
eventSupport.fireMatchNot(la_1, Convert.ToChar(c), inputState.guessing);
}
catch (MismatchedCharException e)
{
if (inputState.guessing == 0)
eventSupport.fireMismatchNot(la_1, Convert.ToChar(c), inputState.guessing);
throw e;
}
}
public override void matchRange(int c1, int c2)
{
char la_1 = LA(1);
try
{
base.matchRange(c1, c2);
eventSupport.fireMatch(la_1, "" + c1 + c2, inputState.guessing);
}
catch (MismatchedCharException e)
{
if (inputState.guessing == 0)
eventSupport.fireMismatch(la_1, "" + c1 + c2, inputState.guessing);
throw e;
}
}
public override void newline()
{
base.newline();
eventSupport.fireNewLine(getLine());
}
public virtual void removeMessageListener(MessageListener l)
{
eventSupport.removeMessageListener(l);
}
public virtual void removeNewLineListener(NewLineListener l)
{
eventSupport.removeNewLineListener(l);
}
public virtual void removeParserListener(ParserListener l)
{
eventSupport.removeParserListener(l);
}
public virtual void removeParserMatchListener(ParserMatchListener l)
{
eventSupport.removeParserMatchListener(l);
}
public virtual void removeParserTokenListener(ParserTokenListener l)
{
eventSupport.removeParserTokenListener(l);
}
public virtual void removeSemanticPredicateListener(SemanticPredicateListener l)
{
eventSupport.removeSemanticPredicateListener(l);
}
public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l)
{
eventSupport.removeSyntacticPredicateListener(l);
}
public virtual void removeTraceListener(TraceListener l)
{
eventSupport.removeTraceListener(l);
}
/// <summary>Report exception errors caught in nextToken()
/// </summary>
public virtual void reportError(MismatchedCharException e)
{
eventSupport.fireReportError(e);
base.reportError(e);
}
/// <summary>Parser error-reporting function can be overridden in subclass
/// </summary>
public override void reportError(string s)
{
eventSupport.fireReportError(s);
base.reportError(s);
}
/// <summary>Parser warning-reporting function can be overridden in subclass
/// </summary>
public override void reportWarning(string s)
{
eventSupport.fireReportWarning(s);
base.reportWarning(s);
}
public virtual void setupDebugging()
{
}
public virtual void wakeUp()
{
lock(this)
{
Monitor.Pulse(this);
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office.Word;
using System.IO;
using DocumentFormat.OpenXml.Wordprocessing;
namespace DocumentFormat.OpenXml.Bibliography
{
/// <summary>
/// Defines Sources.
/// </summary>
public partial class Sources : OpenXmlPartRootElement
{
/// <summary>
/// Sources constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the Sources.</param>
internal Sources(CustomXmlPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(CustomXmlPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(CustomXmlPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
}
}
namespace DocumentFormat.OpenXml.AdditionalCharacteristics
{
/// <summary>
/// Defines AdditionalCharacteristics.
/// </summary>
public partial class AdditionalCharacteristicsInfo : OpenXmlPartRootElement
{
/// <summary>
/// AdditionalCharacteristics constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the AdditionalCharacteristics.</param>
internal AdditionalCharacteristicsInfo(CustomXmlPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(CustomXmlPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(CustomXmlPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
}
}
namespace DocumentFormat.OpenXml.Office.CustomUI
{
/// <summary>
/// Defines CustomUI.
/// </summary>
public partial class CustomUI : OpenXmlPartRootElement
{
/// <summary>
/// CustomUI constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the CustomUI.</param>
internal CustomUI(CustomUIPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(CustomUIPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(CustomUIPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
/// <summary>
/// Gets the CustomUIPart associated with this element, it could either be a QuickAccessToolbarCustomizationsPart or a RibbonExtensibilityPart.
/// </summary>
public CustomUIPart CustomUIPart
{
get
{
return OpenXmlPart as CustomUIPart;
}
internal set
{
OpenXmlPart = value;
}
}
}
}
namespace DocumentFormat.OpenXml.InkML
{
/// <summary>
/// Defines Ink.
/// </summary>
public partial class Ink : OpenXmlPartRootElement
{
/// <summary>
/// Ink constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the Ink.</param>
internal Ink(CustomXmlPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(CustomXmlPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(CustomXmlPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
}
}
namespace DocumentFormat.OpenXml.Wordprocessing
{
/// <summary>
/// Defines Styles.
/// </summary>
public partial class Styles : OpenXmlPartRootElement
{
/// <summary>
/// Styles constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the Styles.</param>
internal Styles(StylesPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(StylesPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(StylesPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
/// <summary>
/// Gets the StylesPart associated with this element, it could either be a StyleDefinitionsPart or a StylesWithEffectsPart.
/// </summary>
public StylesPart StylesPart
{
get
{
return OpenXmlPart as StylesPart;
}
internal set
{
OpenXmlPart = value;
}
}
}
/// <summary>
/// Defines SdtElement - the base class for the sdt elements.
/// </summary>
public abstract class SdtElement : OpenXmlCompositeElement
{
/// <summary>
/// Initializes a new instance of the SdtElement class.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
protected SdtElement(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the SdtElement class.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
protected SdtElement(params OpenXmlElement[] childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the SdtElement class.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
protected SdtElement(string outerXml)
: base(outerXml)
{
}
/// <summary>
/// Gets/Sets the SdtProperties.
/// </summary>
public SdtProperties SdtProperties
{
get
{
return GetElement<SdtProperties>(0);
}
set
{
this.SetElement(0, value);
}
}
/// <summary>
/// Gets/Sets the SdtEndCharProperties.
/// </summary>
public SdtEndCharProperties SdtEndCharProperties
{
get
{
return GetElement<SdtEndCharProperties>(1);
}
set
{
this.SetElement(1, value);
}
}
}
/// <summary>
/// Defines CustomXmlElement - the base class for the customXml elements.
/// </summary>
public abstract class CustomXmlElement : OpenXmlCompositeElement
{
/// <summary>
/// Initializes a new instance of the CustomXmlElement class with the speicified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
protected CustomXmlElement(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CustomXmlElement class with the speicified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
protected CustomXmlElement(params OpenXmlElement[] childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CustomXmlBlock class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
protected CustomXmlElement(string outerXml)
: base(outerXml)
{
}
/// <summary>
/// <para>Custom XML Markup Namespace. </para>
/// <para>Represents the attribte in schema: w:uri.</para>
/// </summary>
/// <remark>
/// xmlns:w=http://schemas.openxmlformats.org/wordprocessingml/2006/main.
/// </remark>
[SchemaAttr(23, "uri")]
public StringValue Uri
{
get { return (StringValue)Attributes[0]; }
set { Attributes[0] = value; }
}
/// <summary>
/// <para>Element name. </para>
/// <para>Represents the attribte in schema: w:element.</para>
/// </summary>
/// <remark>
/// xmlns:w=http://schemas.openxmlformats.org/wordprocessingml/2006/main.
/// </remark>
[SchemaAttr(23, "element")]
public StringValue Element
{
get { return (StringValue)Attributes[1]; }
set { Attributes[1] = value; }
}
internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name)
{
if (23 == namespaceId && "uri" == name)
return new StringValue();
if (23 == namespaceId && "element" == name)
return new StringValue();
return null;
}
/// <summary>
/// <para>CustomXmlProperties.</para>
/// <para>Represents the element tag in schema: w:customXmlPr.</para>
/// </summary>
/// <remark>
/// xmlns:w = http://schemas.openxmlformats.org/wordprocessingml/2006/main.
/// </remark>
public CustomXmlProperties CustomXmlProperties
{
get
{
return GetElement<CustomXmlProperties>(0);
}
set
{
SetElement(0, value);
}
}
}
/// <summary>
/// Defines Recipients.
/// </summary>
public partial class Recipients : OpenXmlPartRootElement
{
/// <summary>
/// Recipients constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the Recipients.</param>
internal Recipients(MailMergeRecipientDataPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(MailMergeRecipientDataPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(MailMergeRecipientDataPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
}
}
namespace DocumentFormat.OpenXml.Office.Word
{
/// <summary>
/// Defines MailMergeRecipients.
/// </summary>
public partial class MailMergeRecipients : OpenXmlPartRootElement
{
/// <summary>
/// MailMergeRecipients constructor.
/// </summary>
/// <param name="ownerPart">The owner part of the MailMergeRecipients.</param>
internal MailMergeRecipients(MailMergeRecipientDataPart ownerPart)
: base(ownerPart)
{
}
/// <summary>
/// Loads the DOM from an OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be loaded.</param>
public void Load(MailMergeRecipientDataPart openXmlPart)
{
LoadFromPart(openXmlPart);
}
/// <summary>
/// Saves the DOM into the OpenXML part.
/// </summary>
/// <param name="openXmlPart">The part to be saved to.</param>
public void Save(MailMergeRecipientDataPart openXmlPart)
{
base.SaveToPart(openXmlPart);
}
}
}
namespace DocumentFormat.OpenXml.Packaging
{
/// <summary>
/// Defines MailMergeRecipientDataPart.
/// </summary>
public partial class MailMergeRecipientDataPart : OpenXmlPart
{
[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private DocumentFormat.OpenXml.OpenXmlPartRootElement _rootEle;
/// <summary>
/// Only for OpenXmlPart derived classes.
/// </summary>
internal override OpenXmlPartRootElement _rootElement
{
get
{
return _rootEle;
}
set
{
_rootEle = value as DocumentFormat.OpenXml.OpenXmlPartRootElement;
}
}
/// <summary>
/// Gets the root element of this part. The DOM tree will be loaded on demand.
/// </summary>
internal override OpenXmlPartRootElement PartRootElement
{
get
{
if (this.Recipients != null)
{
return this.Recipients;
}
else
{
return this.MailMergeRecipients;
}
}
}
/// <summary>
/// Gets/Sets the part's root element when the part's content type is MailMergeRecipientDataPartType.OpenXmlMailMergeRecipientData.
/// Setting this property will throw InvalidOperationException if the MailMergeRecipients property is not null.
/// </summary>
public DocumentFormat.OpenXml.Wordprocessing.Recipients Recipients
{
get
{
TryLoadRootElement();
return _rootEle as DocumentFormat.OpenXml.Wordprocessing.Recipients;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (this.MailMergeRecipients != null)
{
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ExceptionMessages.PropertyMutualExclusive, "Recipients", "MailMergeRecipients"));
}
SetDomTree(value);
}
}
/// <summary>
/// Gets/Sets the part's root element when the part's content type is MailMergeRecipientDataPartType.MsWordMailMergeRecipientData.
/// Setting this property will throw InvalidOperationException if the Recipients property is not null.
/// </summary>
public DocumentFormat.OpenXml.Office.Word.MailMergeRecipients MailMergeRecipients
{
get
{
TryLoadRootElement();
return _rootEle as MailMergeRecipients;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (this.Recipients != null)
{
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ExceptionMessages.PropertyMutualExclusive, "MailMergeRecipients", "Recipients"));
}
SetDomTree(value);
}
}
private void TryLoadRootElement()
{
if (_rootEle == null)
{
try
{
LoadDomTree<DocumentFormat.OpenXml.Wordprocessing.Recipients>();
}
catch (System.IO.InvalidDataException)
{
}
if (_rootEle == null)
{
LoadDomTree<DocumentFormat.OpenXml.Office.Word.MailMergeRecipients>();
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Zunix.ScreensManager
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
public class ZuneScreenManager : DrawableGameComponent
{
#region Fields
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
InputState input = new InputState();
SpriteBatch spriteBatch;
SpriteFont font;
Texture2D blankTexture;
bool isInitialized;
bool traceEnabled;
#endregion
#region Properties
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
/// <summary>
/// A default font shared by all the screens. This saves
/// each screen having to bother loading their own local copy.
/// </summary>
public SpriteFont Font
{
get { return font; }
}
/// <summary>
/// If true, the manager prints out a list of all the screens
/// each time it is updated. This can be useful for making sure
/// everything is being added and removed at the right times.
/// </summary>
public bool TraceEnabled
{
get { return traceEnabled; }
set { traceEnabled = value; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ZuneScreenManager(Game game)
: base(game)
{
}
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
base.Initialize();
isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load content belonging to the screen manager.
ContentManager content = Game.Content;
spriteBatch = new SpriteBatch(GraphicsDevice);
font = content.Load<SpriteFont>(@"Fonts\menufont");
blankTexture = content.Load<Texture2D>(@"Textures\blank");
// Tell each of the screens to load their content.
foreach (GameScreen screen in screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in screens)
{
screen.UnloadContent();
}
}
#endregion
#region Update and Draw
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad.
input.Update();
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.TransitionOn ||
screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.HandleInput(input);
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent
// screens that they are covered by it.
if (!screen.IsPopup)
coveredByOtherScreen = true;
}
}
// Print debug trace?
if (traceEnabled)
TraceScreens();
}
/// <summary>
/// Prints a list of all the screens, for debugging.
/// </summary>
void TraceScreens()
{
List<string> screenNames = new List<string>();
foreach (GameScreen screen in screens)
screenNames.Add(screen.GetType().Name);
Trace.WriteLine(string.Join(", ", screenNames.ToArray()));
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
foreach (GameScreen screen in screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
screen.Draw(gameTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen)
{
screen.ScreenManager = this;
screen.IsExiting = false;
// If we have a graphics device, tell the screen to load content.
if (isInitialized)
{
screen.LoadContent();
}
screens.Add(screen);
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (isInitialized)
{
screen.UnloadContent();
}
screens.Remove(screen);
screensToUpdate.Remove(screen);
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
/// <summary>
/// Helper draws a translucent black fullscreen sprite, used for fading
/// screens in and out, and for darkening the background behind popups.
/// </summary>
public void FadeBackBufferToBlack(int alpha)
{
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Begin();
spriteBatch.Draw(blankTexture,
new Rectangle(0, 0, viewport.Width, viewport.Height),
new Color(0, 0, 0, (byte)alpha));
spriteBatch.End();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
/*=============================================================================
**
**
**
** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
=============================================================================*/
namespace System.Threading {
using System;
using System.Security.Permissions;
using System.Runtime;
using System.Runtime.Remoting;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public static class Monitor
{
/*=========================================================================
** Obtain the monitor lock of obj. Will block if another thread holds the lock
** Will not block if the current thread holds the lock,
** however the caller must ensure that the same number of Exit
** calls are made as there were Enter calls.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Enter(Object obj);
// Use a ref bool instead of out to ensure that unverifiable code must
// initialize this value to something. If we used out, the value
// could be uninitialized if we threw an exception in our prolog.
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void Enter(Object obj, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnter(obj, ref lockTaken);
Contract.Assert(lockTaken);
}
private static void ThrowLockTakenException()
{
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnter(Object obj, ref bool lockTaken);
/*=========================================================================
** Release the monitor lock. If one or more threads are waiting to acquire the
** lock, and the current thread has executed as many Exits as
** Enters, one of the threads will be unblocked and allowed to proceed.
**
** Exceptions: ArgumentNullException if object is null.
** SynchronizationLockException if the current thread does not
** own the lock.
=========================================================================*/
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void Exit(Object obj);
/*=========================================================================
** Similar to Enter, but will never block. That is, if the current thread can
** acquire the monitor lock without blocking, it will do so and TRUE will
** be returned. Otherwise FALSE will be returned.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
public static bool TryEnter(Object obj)
{
bool lockTaken = false;
TryEnter(obj, 0, ref lockTaken);
return lockTaken;
}
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void TryEnter(Object obj, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, 0, ref lockTaken);
}
/*=========================================================================
** Version of TryEnter that will block, but only up to a timeout period
** expressed in milliseconds. If timeout == Timeout.Infinite the method
** becomes equivalent to Enter.
**
** Exceptions: ArgumentNullException if object is null.
** ArgumentException if timeout < 0.
=========================================================================*/
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static bool TryEnter(Object obj, int millisecondsTimeout)
{
bool lockTaken = false;
TryEnter(obj, millisecondsTimeout, ref lockTaken);
return lockTaken;
}
private static int MillisecondsTimeoutFromTimeSpan(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return (int)tm;
}
public static bool TryEnter(Object obj, TimeSpan timeout)
{
return TryEnter(obj, MillisecondsTimeoutFromTimeSpan(timeout));
}
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, millisecondsTimeout, ref lockTaken);
}
public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken);
[System.Security.SecuritySafeCritical]
public static bool IsEntered(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
return IsEnteredNative(obj);
}
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsEnteredNative(Object obj);
/*========================================================================
** Waits for notification from the object (via a Pulse/PulseAll).
** timeout indicates how long to wait before the method returns.
** This method acquires the monitor waithandle for the object
** If this thread holds the monitor lock for the object, it releases it.
** On exit from the method, it obtains the monitor lock back.
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
**
** Exceptions: ArgumentNullException if object is null.
========================================================================*/
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, Object obj);
[System.Security.SecuritySafeCritical] // auto-generated
public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext)
{
if (obj == null)
throw (new ArgumentNullException(nameof(obj)));
return ObjWait(exitContext, millisecondsTimeout, obj);
}
public static bool Wait(Object obj, TimeSpan timeout, bool exitContext)
{
return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), exitContext);
}
public static bool Wait(Object obj, int millisecondsTimeout)
{
return Wait(obj, millisecondsTimeout, false);
}
public static bool Wait(Object obj, TimeSpan timeout)
{
return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), false);
}
public static bool Wait(Object obj)
{
return Wait(obj, Timeout.Infinite, false);
}
/*========================================================================
** Sends a notification to a single waiting object.
* Exceptions: SynchronizationLockException if this method is not called inside
* a synchronized block of code.
========================================================================*/
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulse(Object obj);
[System.Security.SecuritySafeCritical] // auto-generated
public static void Pulse(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
ObjPulse(obj);
}
/*========================================================================
** Sends a notification to all waiting objects.
========================================================================*/
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulseAll(Object obj);
[System.Security.SecuritySafeCritical] // auto-generated
public static void PulseAll(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
ObjPulseAll(obj);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B02Level1 (editable child object).<br/>
/// This is a generated base class of <see cref="B02Level1"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="B03Level11Objects"/> of type <see cref="B03Level11Coll"/> (1:M relation to <see cref="B04Level11"/>)<br/>
/// This class is an item of <see cref="B01Level1Coll"/> collection.
/// </remarks>
[Serializable]
public partial class B02Level1 : BusinessBase<B02Level1>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_IDProperty = RegisterProperty<int>(p => p.Level_1_ID, "Level_1 ID");
/// <summary>
/// Gets the Level_1 ID.
/// </summary>
/// <value>The Level_1 ID.</value>
public int Level_1_ID
{
get { return GetProperty(Level_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_NameProperty = RegisterProperty<string>(p => p.Level_1_Name, "Level_1 Name");
/// <summary>
/// Gets or sets the Level_1 Name.
/// </summary>
/// <value>The Level_1 Name.</value>
public string Level_1_Name
{
get { return GetProperty(Level_1_NameProperty); }
set { SetProperty(Level_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B03Level11SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<B03Level11Child> B03Level11SingleObjectProperty = RegisterProperty<B03Level11Child>(p => p.B03Level11SingleObject, "B3 Level11 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the B03 Level11 Single Object ("parent load" child property).
/// </summary>
/// <value>The B03 Level11 Single Object.</value>
public B03Level11Child B03Level11SingleObject
{
get { return GetProperty(B03Level11SingleObjectProperty); }
private set { LoadProperty(B03Level11SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B03Level11ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<B03Level11ReChild> B03Level11ASingleObjectProperty = RegisterProperty<B03Level11ReChild>(p => p.B03Level11ASingleObject, "B3 Level11 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the B03 Level11 ASingle Object ("parent load" child property).
/// </summary>
/// <value>The B03 Level11 ASingle Object.</value>
public B03Level11ReChild B03Level11ASingleObject
{
get { return GetProperty(B03Level11ASingleObjectProperty); }
private set { LoadProperty(B03Level11ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B03Level11Objects"/> property.
/// </summary>
public static readonly PropertyInfo<B03Level11Coll> B03Level11ObjectsProperty = RegisterProperty<B03Level11Coll>(p => p.B03Level11Objects, "B3 Level11 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the B03 Level11 Objects ("parent load" child property).
/// </summary>
/// <value>The B03 Level11 Objects.</value>
public B03Level11Coll B03Level11Objects
{
get { return GetProperty(B03Level11ObjectsProperty); }
private set { LoadProperty(B03Level11ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B02Level1"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B02Level1"/> object.</returns>
internal static B02Level1 NewB02Level1()
{
return DataPortal.CreateChild<B02Level1>();
}
/// <summary>
/// Factory method. Loads a <see cref="B02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B02Level1"/> object.</returns>
internal static B02Level1 GetB02Level1(SafeDataReader dr)
{
B02Level1 obj = new B02Level1();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.LoadProperty(B03Level11ObjectsProperty, B03Level11Coll.NewB03Level11Coll());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B02Level1"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private B02Level1()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B02Level1"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(B03Level11SingleObjectProperty, DataPortal.CreateChild<B03Level11Child>());
LoadProperty(B03Level11ASingleObjectProperty, DataPortal.CreateChild<B03Level11ReChild>());
LoadProperty(B03Level11ObjectsProperty, DataPortal.CreateChild<B03Level11Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_IDProperty, dr.GetInt32("Level_1_ID"));
LoadProperty(Level_1_NameProperty, dr.GetString("Level_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
internal void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
while (dr.Read())
{
var child = B03Level11Child.GetB03Level11Child(dr);
var obj = ((B01Level1Coll)Parent).FindB02Level1ByParentProperties(child.cParentID1);
obj.LoadProperty(B03Level11SingleObjectProperty, child);
}
dr.NextResult();
while (dr.Read())
{
var child = B03Level11ReChild.GetB03Level11ReChild(dr);
var obj = ((B01Level1Coll)Parent).FindB02Level1ByParentProperties(child.cParentID2);
obj.LoadProperty(B03Level11ASingleObjectProperty, child);
}
dr.NextResult();
var b03Level11Coll = B03Level11Coll.GetB03Level11Coll(dr);
b03Level11Coll.LoadItems((B01Level1Coll)Parent);
dr.NextResult();
while (dr.Read())
{
var child = B05Level111ReChild.GetB05Level111ReChild(dr);
var obj = b03Level11Coll.FindB04Level11ByParentProperties(child.cMarentID2);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B05Level111Child.GetB05Level111Child(dr);
var obj = b03Level11Coll.FindB04Level11ByParentProperties(child.cMarentID1);
obj.LoadChild(child);
}
dr.NextResult();
var b05Level111Coll = B05Level111Coll.GetB05Level111Coll(dr);
b05Level111Coll.LoadItems(b03Level11Coll);
dr.NextResult();
while (dr.Read())
{
var child = B07Level1111Child.GetB07Level1111Child(dr);
var obj = b05Level111Coll.FindB06Level111ByParentProperties(child.cLarentID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B07Level1111ReChild.GetB07Level1111ReChild(dr);
var obj = b05Level111Coll.FindB06Level111ByParentProperties(child.cLarentID2);
obj.LoadChild(child);
}
dr.NextResult();
var b07Level1111Coll = B07Level1111Coll.GetB07Level1111Coll(dr);
b07Level1111Coll.LoadItems(b05Level111Coll);
dr.NextResult();
while (dr.Read())
{
var child = B09Level11111Child.GetB09Level11111Child(dr);
var obj = b07Level1111Coll.FindB08Level1111ByParentProperties(child.cNarentID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B09Level11111ReChild.GetB09Level11111ReChild(dr);
var obj = b07Level1111Coll.FindB08Level1111ByParentProperties(child.cNarentID2);
obj.LoadChild(child);
}
dr.NextResult();
var b09Level11111Coll = B09Level11111Coll.GetB09Level11111Coll(dr);
b09Level11111Coll.LoadItems(b07Level1111Coll);
dr.NextResult();
while (dr.Read())
{
var child = B11Level111111Child.GetB11Level111111Child(dr);
var obj = b09Level11111Coll.FindB10Level11111ByParentProperties(child.cQarentID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B11Level111111ReChild.GetB11Level111111ReChild(dr);
var obj = b09Level11111Coll.FindB10Level11111ByParentProperties(child.cQarentID2);
obj.LoadChild(child);
}
dr.NextResult();
var b11Level111111Coll = B11Level111111Coll.GetB11Level111111Coll(dr);
b11Level111111Coll.LoadItems(b09Level11111Coll);
}
/// <summary>
/// Inserts a new <see cref="B02Level1"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddB02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_IDProperty, (int) cmd.Parameters["@Level_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B02Level1"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateB02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="B02Level1"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteB02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(B03Level11SingleObjectProperty, DataPortal.CreateChild<B03Level11Child>());
LoadProperty(B03Level11ASingleObjectProperty, DataPortal.CreateChild<B03Level11ReChild>());
LoadProperty(B03Level11ObjectsProperty, DataPortal.CreateChild<B03Level11Coll>());
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Funq;
using NServiceKit.CacheAccess;
using NServiceKit.CacheAccess.Providers;
using NServiceKit.Common;
using NServiceKit.Common.Web;
using NServiceKit.Html;
using NServiceKit.IO;
using NServiceKit.Messaging;
using NServiceKit.MiniProfiler;
using NServiceKit.ServiceHost;
using NServiceKit.VirtualPath;
using NServiceKit.ServiceModel.Serialization;
using NServiceKit.WebHost.Endpoints.Extensions;
using NServiceKit.WebHost.Endpoints.Formats;
using NServiceKit.WebHost.Endpoints.Support;
using NServiceKit.WebHost.Endpoints.Utils;
namespace NServiceKit.WebHost.Endpoints
{
/// <summary>An endpoint host.</summary>
public class EndpointHost
{
/// <summary>Gets the application host.</summary>
///
/// <value>The application host.</value>
public static IAppHost AppHost { get; internal set; }
/// <summary>Gets or sets the content type filter.</summary>
///
/// <value>The content type filter.</value>
public static IContentTypeFilter ContentTypeFilter { get; set; }
/// <summary>Gets the raw request filters.</summary>
///
/// <value>The raw request filters.</value>
public static List<Action<IHttpRequest, IHttpResponse>> RawRequestFilters { get; private set; }
/// <summary>Gets the request filters.</summary>
///
/// <value>The request filters.</value>
public static List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters { get; private set; }
/// <summary>Gets the response filters.</summary>
///
/// <value>The response filters.</value>
public static List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters { get; private set; }
/// <summary>Gets or sets the view engines.</summary>
///
/// <value>The view engines.</value>
public static List<IViewEngine> ViewEngines { get; set; }
/// <summary>TODO: rename to UncaughtExceptionsHandler.</summary>
///
/// <value>The exception handler.</value>
public static HandleUncaughtExceptionDelegate ExceptionHandler { get; set; }
/// <summary>TODO: rename to ServiceExceptionsHandler.</summary>
///
/// <value>The service exception handler.</value>
public static HandleServiceExceptionDelegate ServiceExceptionHandler { get; set; }
/// <summary>Gets or sets the catch all handlers.</summary>
///
/// <value>The catch all handlers.</value>
public static List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; }
private static bool pluginsLoaded = false;
/// <summary>Gets or sets the plugins.</summary>
///
/// <value>The plugins.</value>
public static List<IPlugin> Plugins { get; set; }
/// <summary>Gets or sets the virtual path provider.</summary>
///
/// <value>The virtual path provider.</value>
public static IVirtualPathProvider VirtualPathProvider { get; set; }
/// <summary>Gets or sets the Date/Time of the started at.</summary>
///
/// <value>The started at.</value>
public static DateTime StartedAt { get; set; }
/// <summary>Gets or sets the Date/Time of the ready at.</summary>
///
/// <value>The ready at.</value>
public static DateTime ReadyAt { get; set; }
private static void Reset()
{
ContentTypeFilter = HttpResponseFilter.Instance;
RawRequestFilters = new List<Action<IHttpRequest, IHttpResponse>>();
RequestFilters = new List<Action<IHttpRequest, IHttpResponse, object>>();
ResponseFilters = new List<Action<IHttpRequest, IHttpResponse, object>>();
ViewEngines = new List<IViewEngine>();
CatchAllHandlers = new List<HttpHandlerResolverDelegate>();
Plugins = new List<IPlugin> {
new HtmlFormat(),
new CsvFormat(),
new MarkdownFormat(),
new PredefinedRoutesFeature(),
new MetadataFeature(),
};
//Default Config for projects that want to use components but not WebFramework (e.g. MVC)
Config = new EndpointHostConfig(
"Empty Config",
new ServiceManager(new Container(), new ServiceController(null)));
}
/// <summary>Pre user config.</summary>
///
/// <param name="appHost"> The application host.</param>
/// <param name="serviceName"> Name of the service.</param>
/// <param name="serviceManager">The service manager.</param>
public static void ConfigureHost(IAppHost appHost, string serviceName, ServiceManager serviceManager)
{
Reset();
AppHost = appHost;
EndpointHostConfig.Instance.ServiceName = serviceName;
EndpointHostConfig.Instance.ServiceManager = serviceManager;
var config = EndpointHostConfig.Instance;
Config = config; // avoid cross-dependency on Config setter
VirtualPathProvider = new FileSystemVirtualPathProvider(AppHost, Config.WebHostPhysicalPath);
Config.DebugMode = appHost.GetType().Assembly.IsDebugBuild();
if (Config.DebugMode)
{
Plugins.Add(new RequestInfoFeature());
}
}
// Config has changed
private static void ApplyConfigChanges()
{
config.ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.Create(config.NServiceKitHandlerFactoryPath);
JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers;
JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers;
}
/// <summary>After configure called.</summary>
public static void AfterInit()
{
StartedAt = DateTime.UtcNow;
if (config.EnableFeatures != Feature.All)
{
if ((Feature.Xml & config.EnableFeatures) != Feature.Xml)
config.IgnoreFormatsInMetadata.Add("xml");
if ((Feature.Json & config.EnableFeatures) != Feature.Json)
config.IgnoreFormatsInMetadata.Add("json");
if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv)
config.IgnoreFormatsInMetadata.Add("jsv");
if ((Feature.Csv & config.EnableFeatures) != Feature.Csv)
config.IgnoreFormatsInMetadata.Add("csv");
if ((Feature.Html & config.EnableFeatures) != Feature.Html)
config.IgnoreFormatsInMetadata.Add("html");
if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11)
config.IgnoreFormatsInMetadata.Add("soap11");
if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12)
config.IgnoreFormatsInMetadata.Add("soap12");
}
if ((Feature.Html & config.EnableFeatures) != Feature.Html)
Plugins.RemoveAll(x => x is HtmlFormat);
if ((Feature.Csv & config.EnableFeatures) != Feature.Csv)
Plugins.RemoveAll(x => x is CsvFormat);
if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown)
Plugins.RemoveAll(x => x is MarkdownFormat);
if ((Feature.PredefinedRoutes & config.EnableFeatures) != Feature.PredefinedRoutes)
Plugins.RemoveAll(x => x is PredefinedRoutesFeature);
if ((Feature.Metadata & config.EnableFeatures) != Feature.Metadata)
Plugins.RemoveAll(x => x is MetadataFeature);
if ((Feature.RequestInfo & config.EnableFeatures) != Feature.RequestInfo)
Plugins.RemoveAll(x => x is RequestInfoFeature);
if ((Feature.Razor & config.EnableFeatures) != Feature.Razor)
Plugins.RemoveAll(x => x is IRazorPlugin); //external
if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf)
Plugins.RemoveAll(x => x is IProtoBufPlugin); //external
if ((Feature.MsgPack & config.EnableFeatures) != Feature.MsgPack)
Plugins.RemoveAll(x => x is IMsgPackPlugin); //external
if (ExceptionHandler == null)
{
ExceptionHandler = (httpReq, httpRes, operationName, ex) =>
{
var errorMessage = String.Format("Error occured while Processing Request: {0}", ex.Message);
var statusCode = ex.ToStatusCode();
//httpRes.WriteToResponse always calls .Close in it's finally statement so
//if there is a problem writing to response, by now it will be closed
if (!httpRes.IsClosed)
{
httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode);
}
};
}
if (config.NServiceKitHandlerFactoryPath != null)
config.NServiceKitHandlerFactoryPath = config.NServiceKitHandlerFactoryPath.TrimStart('/');
var specifiedContentType = config.DefaultContentType; //Before plugins loaded
ConfigurePlugins();
AppHost.LoadPlugin(Plugins.ToArray());
pluginsLoaded = true;
AfterPluginsLoaded(specifiedContentType);
var registeredCacheClient = AppHost.TryResolve<ICacheClient>();
using (registeredCacheClient)
{
if (registeredCacheClient == null)
{
Container.Register<ICacheClient>(new MemoryCacheClient());
}
}
var registeredMqService = AppHost.TryResolve<IMessageService>();
var registeredMqFactory = AppHost.TryResolve<IMessageFactory>();
if (registeredMqService != null && registeredMqFactory == null)
{
Container.Register(c => registeredMqService.MessageFactory);
}
ReadyAt = DateTime.UtcNow;
}
/// <summary>Try resolve.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
///
/// <returns>A T.</returns>
public static T TryResolve<T>()
{
return AppHost != null ? AppHost.TryResolve<T>() : default(T);
}
/// <summary>
/// The AppHost.Container. Note: it is not thread safe to register dependencies after AppStart.
/// </summary>
public static Container Container
{
get
{
var aspHost = AppHost as AppHostBase;
if (aspHost != null)
return aspHost.Container;
var listenerHost = AppHost as HttpListenerBase;
return listenerHost != null ? listenerHost.Container : new Container(); //testing may use alt AppHost
}
}
private static void ConfigurePlugins()
{
//Some plugins need to initialize before other plugins are registered.
foreach (var plugin in Plugins)
{
var preInitPlugin = plugin as IPreInitPlugin;
if (preInitPlugin != null)
{
preInitPlugin.Configure(AppHost);
}
}
}
private static void AfterPluginsLoaded(string specifiedContentType)
{
if (!String.IsNullOrEmpty(specifiedContentType))
config.DefaultContentType = specifiedContentType;
else if (String.IsNullOrEmpty(config.DefaultContentType))
config.DefaultContentType = ContentType.Json;
config.ServiceManager.AfterInit();
ServiceManager = config.ServiceManager; //reset operations
}
/// <summary>Gets the plugin.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
///
/// <returns>The plugin.</returns>
public static T GetPlugin<T>() where T : class, IPlugin
{
return Plugins.FirstOrDefault(x => x is T) as T;
}
/// <summary>Adds a plugin.</summary>
///
/// <param name="plugins">A variable-length parameters list containing plugins.</param>
public static void AddPlugin(params IPlugin[] plugins)
{
if (pluginsLoaded)
{
AppHost.LoadPlugin(plugins);
}
else
{
foreach (var plugin in plugins)
{
Plugins.Add(plugin);
}
}
}
/// <summary>Gets or sets the manager for service.</summary>
///
/// <value>The service manager.</value>
public static ServiceManager ServiceManager
{
get { return config.ServiceManager; }
set { config.ServiceManager = value; }
}
private static EndpointHostConfig config;
/// <summary>Gets or sets the configuration.</summary>
///
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
///
/// <value>The configuration.</value>
public static EndpointHostConfig Config
{
get
{
return config;
}
set
{
if (value.ServiceName == null)
throw new ArgumentNullException("ServiceName");
if (value.ServiceController == null)
throw new ArgumentNullException("ServiceController");
config = value;
ApplyConfigChanges();
}
}
/// <summary>Assert test configuration.</summary>
///
/// <param name="assemblies">A variable-length parameters list containing assemblies.</param>
public static void AssertTestConfig(params Assembly[] assemblies)
{
if (Config != null)
return;
var config = EndpointHostConfig.Instance;
config.ServiceName = "Test Services";
config.ServiceManager = new ServiceManager(assemblies.Length == 0 ? new[] { Assembly.GetCallingAssembly() } : assemblies);
Config = config;
}
/// <summary>Gets a value indicating whether the debug mode.</summary>
///
/// <value>true if debug mode, false if not.</value>
public static bool DebugMode
{
get { return Config != null && Config.DebugMode; }
}
/// <summary>Gets the metadata.</summary>
///
/// <value>The metadata.</value>
public static ServiceMetadata Metadata { get { return Config.Metadata; } }
/// <summary>
/// Applies the raw request filters. Returns whether or not the request has been handled
/// and no more processing should be done.
/// </summary>
/// <returns></returns>
public static bool ApplyPreRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes)
{
foreach (var requestFilter in RawRequestFilters)
{
requestFilter(httpReq, httpRes);
if (httpRes.IsClosed) break;
}
return httpRes.IsClosed;
}
/// <summary>
/// Applies the request filters. Returns whether or not the request has been handled
/// and no more processing should be done.
/// </summary>
/// <returns></returns>
public static bool ApplyRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes, object requestDto)
{
httpReq.ThrowIfNull("httpReq");
httpRes.ThrowIfNull("httpRes");
using (Profiler.Current.Step("Executing Request Filters"))
{
//Exec all RequestFilter attributes with Priority < 0
var attributes = FilterAttributeCache.GetRequestFilterAttributes(requestDto.GetType());
var i = 0;
for (; i < attributes.Length && attributes[i].Priority < 0; i++)
{
var attribute = attributes[i];
ServiceManager.Container.AutoWire(attribute);
attribute.RequestFilter(httpReq, httpRes, requestDto);
if (AppHost != null) //tests
AppHost.Release(attribute);
if (httpRes.IsClosed) return httpRes.IsClosed;
}
//Exec global filters
foreach (var requestFilter in RequestFilters)
{
requestFilter(httpReq, httpRes, requestDto);
if (httpRes.IsClosed) return httpRes.IsClosed;
}
//Exec remaining RequestFilter attributes with Priority >= 0
for (; i < attributes.Length; i++)
{
var attribute = attributes[i];
ServiceManager.Container.AutoWire(attribute);
attribute.RequestFilter(httpReq, httpRes, requestDto);
if (AppHost != null) //tests
AppHost.Release(attribute);
if (httpRes.IsClosed) return httpRes.IsClosed;
}
return httpRes.IsClosed;
}
}
/// <summary>
/// Applies the response filters. Returns whether or not the request has been handled
/// and no more processing should be done.
/// </summary>
/// <returns></returns>
public static bool ApplyResponseFilters(IHttpRequest httpReq, IHttpResponse httpRes, object response)
{
httpReq.ThrowIfNull("httpReq");
httpRes.ThrowIfNull("httpRes");
using (Profiler.Current.Step("Executing Response Filters"))
{
var responseDto = response.ToResponseDto();
var attributes = responseDto != null
? FilterAttributeCache.GetResponseFilterAttributes(responseDto.GetType())
: null;
//Exec all ResponseFilter attributes with Priority < 0
var i = 0;
if (attributes != null)
{
for (; i < attributes.Length && attributes[i].Priority < 0; i++)
{
var attribute = attributes[i];
ServiceManager.Container.AutoWire(attribute);
attribute.ResponseFilter(httpReq, httpRes, response);
if (AppHost != null) //tests
AppHost.Release(attribute);
if (httpRes.IsClosed) return httpRes.IsClosed;
}
}
//Exec global filters
foreach (var responseFilter in ResponseFilters)
{
responseFilter(httpReq, httpRes, response);
if (httpRes.IsClosed) return httpRes.IsClosed;
}
//Exec remaining RequestFilter attributes with Priority >= 0
if (attributes != null)
{
for (; i < attributes.Length; i++)
{
var attribute = attributes[i];
ServiceManager.Container.AutoWire(attribute);
attribute.ResponseFilter(httpReq, httpRes, response);
if (AppHost != null) //tests
AppHost.Release(attribute);
if (httpRes.IsClosed) return httpRes.IsClosed;
}
}
return httpRes.IsClosed;
}
}
internal static object ExecuteService(object request, EndpointAttributes endpointAttributes, IHttpRequest httpReq, IHttpResponse httpRes)
{
using (Profiler.Current.Step("Execute Service"))
{
return config.ServiceController.Execute(request,
new HttpRequestContext(httpReq, httpRes, request, endpointAttributes));
}
}
/// <summary>Creates service runner.</summary>
///
/// <typeparam name="TRequest">Type of the request.</typeparam>
/// <param name="actionContext">Context for the action.</param>
///
/// <returns>The new service runner.</returns>
public static IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
return AppHost != null
? AppHost.CreateServiceRunner<TRequest>(actionContext)
: new ServiceRunner<TRequest>(null, actionContext);
}
/// <summary>
/// Call to signal the completion of a NServiceKit-handled Request
/// </summary>
internal static void CompleteRequest()
{
try
{
if (AppHost != null)
{
AppHost.OnEndRequest();
}
}
catch { }
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public static void Dispose()
{
AppHost = null;
}
}
}
| |
/*
* 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.Collections.Generic;
using System.Xml;
/// <summary>
/// Represents the CompanyInsightValue.
/// </summary>
public sealed class CompanyInsightValue : InsightValue
{
private string name;
private string satoriId;
private string description;
private string descriptionAttribution;
private string imageUrl;
private string imageUrlAttribution;
private string yearFound;
private string financeSymbol;
private string websiteUrl;
/// <summary>
/// Gets the Name
/// </summary>
public string Name
{
get
{
return this.name;
}
set
{
this.SetFieldValue<string>(ref this.name, value);
}
}
/// <summary>
/// Gets the SatoriId
/// </summary>
public string SatoriId
{
get
{
return this.satoriId;
}
set
{
this.SetFieldValue<string>(ref this.satoriId, value);
}
}
/// <summary>
/// Gets the Description
/// </summary>
public string Description
{
get
{
return this.description;
}
set
{
this.SetFieldValue<string>(ref this.description, value);
}
}
/// <summary>
/// Gets the DescriptionAttribution
/// </summary>
public string DescriptionAttribution
{
get
{
return this.descriptionAttribution;
}
set
{
this.SetFieldValue<string>(ref this.descriptionAttribution, value);
}
}
/// <summary>
/// Gets the ImageUrl
/// </summary>
public string ImageUrl
{
get
{
return this.imageUrl;
}
set
{
this.SetFieldValue<string>(ref this.imageUrl, value);
}
}
/// <summary>
/// Gets the ImageUrlAttribution
/// </summary>
public string ImageUrlAttribution
{
get
{
return this.imageUrlAttribution;
}
set
{
this.SetFieldValue<string>(ref this.imageUrlAttribution, value);
}
}
/// <summary>
/// Gets the YearFound
/// </summary>
public string YearFound
{
get
{
return this.yearFound;
}
set
{
this.SetFieldValue<string>(ref this.yearFound, value);
}
}
/// <summary>
/// Gets the FinanceSymbol
/// </summary>
public string FinanceSymbol
{
get
{
return this.financeSymbol;
}
set
{
this.SetFieldValue<string>(ref this.financeSymbol, value);
}
}
/// <summary>
/// Gets the WebsiteUrl
/// </summary>
public string WebsiteUrl
{
get
{
return this.websiteUrl;
}
set
{
this.SetFieldValue<string>(ref this.websiteUrl, value);
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">XML reader</param>
/// <returns>Whether the element was read</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.InsightSource:
this.InsightSource = reader.ReadElementValue<string>();
break;
case XmlElementNames.UpdatedUtcTicks:
this.UpdatedUtcTicks = reader.ReadElementValue<long>();
break;
case XmlElementNames.Name:
this.Name = reader.ReadElementValue();
break;
case XmlElementNames.SatoriId:
this.SatoriId = reader.ReadElementValue();
break;
case XmlElementNames.Description:
this.Description = reader.ReadElementValue();
break;
case XmlElementNames.DescriptionAttribution:
this.DescriptionAttribution = reader.ReadElementValue();
break;
case XmlElementNames.ImageUrl:
this.ImageUrl = reader.ReadElementValue();
break;
case XmlElementNames.ImageUrlAttribution:
this.ImageUrlAttribution = reader.ReadElementValue();
break;
case XmlElementNames.YearFound:
this.YearFound = reader.ReadElementValue();
break;
case XmlElementNames.FinanceSymbol:
this.FinanceSymbol = reader.ReadElementValue();
break;
case XmlElementNames.WebsiteUrl:
this.WebsiteUrl = reader.ReadElementValue();
break;
default:
return false;
}
return true;
}
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
// Signature, CallingConventionConverter_SpecifyCommonStubData, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_SpecifyCommonStubData")]
public static void CallingConventionConverter_SpecifyCommonStubData(global::System.IntPtr commonStubData)
{
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_SpecifyCommonStubData(commonStubData);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-handle-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll
{
// Signature, CloseHandle, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseHandle")]
public static bool CloseHandle(global::System.IntPtr handle)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_handle_l1_1_0_dll_PInvokes.CloseHandle(handle);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore_PInvokes", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_SpecifyCommonStubData(global::System.IntPtr commonStubData);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-handle-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CloseHandle(global::System.IntPtr handle);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Autofac;
using NUnit.Framework;
using Orchard.Caching;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Folders;
using Orchard.Environment.Extensions.Loaders;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.Dependencies;
using Orchard.Tests.Extensions.ExtensionTypes;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Environment.Extensions {
[TestFixture]
public class ExtensionLoaderCoordinatorTests {
private IContainer _container;
private IExtensionManager _manager;
private StubFolders _folders;
[SetUp]
public void Init() {
var builder = new ContainerBuilder();
_folders = new StubFolders(DefaultExtensionTypes.Module);
builder.RegisterInstance(_folders).As<IExtensionFolders>();
builder.RegisterType<ExtensionManager>().As<IExtensionManager>();
builder.RegisterType<StubCacheManager>().As<ICacheManager>();
builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();
builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
_container = builder.Build();
_manager = _container.Resolve<IExtensionManager>();
}
public class StubFolders : IExtensionFolders {
private readonly string _extensionType;
public StubFolders(string extensionType) {
_extensionType = extensionType;
Manifests = new Dictionary<string, string>();
}
public IDictionary<string, string> Manifests { get; set; }
public IEnumerable<ExtensionDescriptor> AvailableExtensions() {
foreach (var e in Manifests) {
string name = e.Key;
yield return ExtensionHarvester.GetDescriptorForExtension("~/", name, _extensionType, Manifests[name]);
}
}
}
public class StubLoaders : IExtensionLoader {
#region Implementation of IExtensionLoader
public int Order {
get { return 1; }
}
public string Name {
get { return this.GetType().Name; }
}
public Assembly LoadReference(DependencyReferenceDescriptor reference) {
throw new NotImplementedException();
}
public void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) {
throw new NotImplementedException();
}
public void ReferenceDeactivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) {
throw new NotImplementedException();
}
public bool IsCompatibleWithModuleReferences(ExtensionDescriptor extension, IEnumerable<ExtensionProbeEntry> references) {
throw new NotImplementedException();
}
public ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) {
return new ExtensionProbeEntry { Descriptor = descriptor, Loader = this };
}
public IEnumerable<ExtensionReferenceProbeEntry> ProbeReferences(ExtensionDescriptor extensionDescriptor) {
throw new NotImplementedException();
}
public ExtensionEntry Load(ExtensionDescriptor descriptor) {
return new ExtensionEntry { Descriptor = descriptor, ExportedTypes = new[] { typeof(Alpha), typeof(Beta), typeof(Phi) } };
}
public void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
throw new NotImplementedException();
}
public void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
throw new NotImplementedException();
}
public void ExtensionRemoved(ExtensionLoadingContext ctx, DependencyDescriptor dependency) {
throw new NotImplementedException();
}
public void Monitor(ExtensionDescriptor extension, Action<IVolatileToken> monitor) {
}
public IEnumerable<ExtensionCompilationReference> GetCompilationReferences(DependencyDescriptor dependency) {
throw new NotImplementedException();
}
public IEnumerable<string> GetVirtualPathDependencies(DependencyDescriptor dependency) {
throw new NotImplementedException();
}
public bool LoaderIsSuitable(ExtensionDescriptor descriptor) {
throw new NotImplementedException();
}
#endregion
}
private ExtensionManager CreateExtensionManager(StubFolders extensionFolder, StubLoaders extensionLoader) {
return new ExtensionManager(new[] { extensionFolder }, new[] { extensionLoader }, new StubCacheManager(), new StubParallelCacheContext(), new StubAsyncTokenProvider());
}
[Test]
public void AvailableExtensionsShouldFollowCatalogLocations() {
_folders.Manifests.Add("foo", "Name: Foo");
_folders.Manifests.Add("bar", "Name: Bar");
_folders.Manifests.Add("frap", "Name: Frap");
_folders.Manifests.Add("quad", "Name: Quad");
var available = _manager.AvailableExtensions();
Assert.That(available.Count(), Is.EqualTo(4));
Assert.That(available, Has.Some.Property("Id").EqualTo("foo"));
}
[Test]
public void ExtensionDescriptorsShouldHaveNameAndVersion() {
_folders.Manifests.Add("Sample", @"
Name: Sample Extension
Version: 2.x
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("Sample"));
Assert.That(descriptor.Name, Is.EqualTo("Sample Extension"));
Assert.That(descriptor.Version, Is.EqualTo("2.x"));
}
[Test]
public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxt() {
_folders.Manifests.Add("SuperWiki", @"
Name: SuperWiki
Version: 1.0.3
OrchardVersion: 1
Features:
SuperWiki:
Description: My super wiki module for Orchard.
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Version, Is.EqualTo("1.0.3"));
Assert.That(descriptor.OrchardVersion, Is.EqualTo("1"));
Assert.That(descriptor.Features.Count(), Is.EqualTo(1));
Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard."));
}
[Test]
public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxtWithSimpleFormat() {
_folders.Manifests.Add("SuperWiki", @"
Name: SuperWiki
Version: 1.0.3
OrchardVersion: 1
Description: My super wiki module for Orchard.
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Version, Is.EqualTo("1.0.3"));
Assert.That(descriptor.OrchardVersion, Is.EqualTo("1"));
Assert.That(descriptor.Features.Count(), Is.EqualTo(1));
Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard."));
}
[Test]
public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxt() {
_folders.Manifests.Add("MyCompany.AnotherWiki", @"
Name: AnotherWiki
Author: Coder Notaprogrammer
Website: http://anotherwiki.codeplex.com
Version: 1.2.3
OrchardVersion: 1
Features:
AnotherWiki:
Description: My super wiki module for Orchard.
Dependencies: Versioning, Search
Category: Content types
AnotherWiki Editor:
Description: A rich editor for wiki contents.
Dependencies: TinyMce, AnotherWiki
Category: Input methods
AnotherWiki DistributionList:
Description: Sends e-mail alerts when wiki contents gets published.
Dependencies: AnotherWiki, Email Subscriptions
Category: Email
AnotherWiki Captcha:
Description: Kills spam. Or makes it zombie-like.
Dependencies: AnotherWiki, reCaptcha
Category: Spam
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("MyCompany.AnotherWiki"));
Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki"));
Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer"));
Assert.That(descriptor.WebSite, Is.EqualTo("http://anotherwiki.codeplex.com"));
Assert.That(descriptor.Version, Is.EqualTo("1.2.3"));
Assert.That(descriptor.OrchardVersion, Is.EqualTo("1"));
Assert.That(descriptor.Features.Count(), Is.EqualTo(5));
foreach (var featureDescriptor in descriptor.Features) {
switch (featureDescriptor.Id) {
case "AnotherWiki":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Content types"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("Versioning"));
Assert.That(featureDescriptor.Dependencies.Contains("Search"));
break;
case "AnotherWiki Editor":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("TinyMce"));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
break;
case "AnotherWiki DistributionList":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Email"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions"));
break;
case "AnotherWiki Captcha":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Spam"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha"));
break;
// default feature.
case "MyCompany.AnotherWiki":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
break;
default:
Assert.Fail("Features not parsed correctly");
break;
}
}
}
[Test]
public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxtWithSimpleFormat() {
_folders.Manifests.Add("AnotherWiki", @"
Name: AnotherWiki
Author: Coder Notaprogrammer
Website: http://anotherwiki.codeplex.com
Version: 1.2.3
OrchardVersion: 1
Description: Module Description
FeatureDescription: My super wiki module for Orchard.
Dependencies: Versioning, Search
Category: Content types
Features:
AnotherWiki Editor:
Description: A rich editor for wiki contents.
Dependencies: TinyMce, AnotherWiki
Category: Input methods
AnotherWiki DistributionList:
Description: Sends e-mail alerts when wiki contents gets published.
Dependencies: AnotherWiki, Email Subscriptions
Category: Email
AnotherWiki Captcha:
Description: Kills spam. Or makes it zombie-like.
Dependencies: AnotherWiki, reCaptcha
Category: Spam
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("AnotherWiki"));
Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki"));
Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer"));
Assert.That(descriptor.WebSite, Is.EqualTo("http://anotherwiki.codeplex.com"));
Assert.That(descriptor.Version, Is.EqualTo("1.2.3"));
Assert.That(descriptor.OrchardVersion, Is.EqualTo("1"));
Assert.That(descriptor.Description, Is.EqualTo("Module Description"));
Assert.That(descriptor.Features.Count(), Is.EqualTo(4));
foreach (var featureDescriptor in descriptor.Features) {
switch (featureDescriptor.Id) {
case "AnotherWiki":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Content types"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("Versioning"));
Assert.That(featureDescriptor.Dependencies.Contains("Search"));
break;
case "AnotherWiki Editor":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("TinyMce"));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
break;
case "AnotherWiki DistributionList":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Email"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions"));
break;
case "AnotherWiki Captcha":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Spam"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha"));
break;
default:
Assert.Fail("Features not parsed correctly");
break;
}
}
}
[Test]
public void ExtensionManagerShouldLoadFeatures() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Module);
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features);
var features = extensionManager.LoadFeatures(testFeature);
var types = features.SelectMany(x => x.ExportedTypes);
Assert.That(types.Count(), Is.Not.EqualTo(0));
}
[Test]
public void ExtensionManagerFeaturesContainNonAbstractClasses() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Module);
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features);
var features = extensionManager.LoadFeatures(testFeature);
var types = features.SelectMany(x => x.ExportedTypes);
foreach (var type in types) {
Assert.That(type.IsClass);
Assert.That(!type.IsAbstract);
}
}
[Test]
public void ExtensionManagerTestFeatureAttribute() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Module);
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features)
.Single(x => x.Id == "TestFeature");
foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) {
foreach (var type in feature.ExportedTypes) {
foreach (OrchardFeatureAttribute featureAttribute in type.GetCustomAttributes(typeof(OrchardFeatureAttribute), false)) {
Assert.That(featureAttribute.FeatureName, Is.EqualTo("TestFeature"));
}
}
}
}
[Test]
public void ExtensionManagerLoadFeatureReturnsTypesFromSpecificFeaturesWithFeatureAttribute() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Module);
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features)
.Single(x => x.Id == "TestFeature");
foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) {
foreach (var type in feature.ExportedTypes) {
Assert.That(type == typeof(Phi));
}
}
}
[Test]
public void ExtensionManagerLoadFeatureDoesNotReturnTypesFromNonMatchingFeatures() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Module);
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testModule = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features)
.Single(x => x.Id == "TestModule");
foreach (var feature in extensionManager.LoadFeatures(new[] { testModule })) {
foreach (var type in feature.ExportedTypes) {
Assert.That(type != typeof(Phi));
Assert.That((type == typeof(Alpha) || (type == typeof(Beta))));
}
}
}
[Test]
public void ModuleNameIsIntroducedAsFeatureImplicitly() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Module);
extensionFolder.Manifests.Add("Minimalistic", @"
Name: Minimalistic
Version: 1.0.3
OrchardVersion: 1
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic");
Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1));
Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic"));
}
[Test]
public void ThemeNameIsIntroducedAsFeatureImplicitly() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders(DefaultExtensionTypes.Theme);
extensionFolder.Manifests.Add("Minimalistic", @"
Name: Minimalistic
Version: 1.0.3
OrchardVersion: 1
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic");
Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1));
Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic"));
}
}
}
| |
//
// DatabaseTrackListModel.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Data.Sqlite;
using Hyena.Query;
using Banshee.Base;
using Banshee.Query;
using Banshee.Database;
using Banshee.PlaybackController;
namespace Banshee.Collection.Database
{
public class DatabaseTrackListModel : TrackListModel, IExportableModel,
ICacheableDatabaseModel, IFilterable, ISortable, ICareAboutView
{
private readonly BansheeDbConnection connection;
private IDatabaseTrackModelProvider provider;
protected IDatabaseTrackModelCache cache;
private Banshee.Sources.DatabaseSource source;
private long count;
private long filtered_count;
private TimeSpan filtered_duration;
private long filtered_filesize, filesize;
private ISortableColumn sort_column;
private string sort_query;
private bool forced_sort_query;
private string reload_fragment;
private string join_table, join_fragment, join_primary_key, join_column, condition, condition_from;
private string query_fragment;
private string user_query;
private int rows_in_view;
public DatabaseTrackListModel (BansheeDbConnection connection, IDatabaseTrackModelProvider provider, Banshee.Sources.DatabaseSource source)
{
this.connection = connection;
this.provider = provider;
this.source = source;
}
protected HyenaSqliteConnection Connection {
get { return connection; }
}
private bool initialized = false;
public void Initialize (IDatabaseTrackModelCache cache)
{
if (initialized)
return;
initialized = true;
this.cache = cache;
cache.AggregatesUpdated += HandleCacheAggregatesUpdated;
GenerateSortQueryPart ();
}
private bool have_new_user_query = true;
private void GenerateUserQueryFragment ()
{
if (!have_new_user_query)
return;
if (String.IsNullOrEmpty (UserQuery)) {
query_fragment = null;
query_tree = null;
} else {
query_tree = UserQueryParser.Parse (UserQuery, BansheeQuery.FieldSet);
query_fragment = (query_tree == null) ? null : query_tree.ToSql (BansheeQuery.FieldSet);
if (query_fragment != null && query_fragment.Length == 0) {
query_fragment = null;
query_tree = null;
}
}
have_new_user_query = false;
}
private QueryNode query_tree;
public QueryNode Query {
get { return query_tree; }
}
protected string SortQuery {
get { return sort_query; }
set { sort_query = value; }
}
protected virtual void GenerateSortQueryPart ()
{
SortQuery = (SortColumn == null || SortColumn.SortType == SortType.None)
? (SortColumn != null && source is Banshee.Playlist.PlaylistSource)
? "CorePlaylistEntries.ViewOrder ASC, CorePlaylistEntries.EntryID ASC"
: BansheeQuery.GetSort ("Artist", true)
: BansheeQuery.GetSort (SortColumn.SortKey, SortColumn.SortType == SortType.Ascending);
}
private SortType last_sort_type = SortType.None;
public bool Sort (ISortableColumn column)
{
lock (this) {
if (forced_sort_query) {
return false;
}
// Don't sort by the same column and the same sort-type more than once
if (sort_column != null && sort_column == column && column.SortType == last_sort_type) {
return false;
}
last_sort_type = column.SortType;
sort_column = column;
GenerateSortQueryPart ();
cache.Clear ();
}
return true;
}
private void HandleCacheAggregatesUpdated (IDataReader reader)
{
filtered_duration = TimeSpan.FromMilliseconds (reader.IsDBNull (1) ? 0 : Convert.ToInt64 (reader[1]));
filtered_filesize = reader.IsDBNull (2) ? 0 : Convert.ToInt64 (reader[2]);
}
public override void Clear ()
{
cache.Clear ();
count = 0;
filesize = 0;
filtered_count = 0;
OnCleared ();
}
public void InvalidateCache (bool notify)
{
if (cache == null) {
Log.ErrorFormat ("Called invalidate cache for {0}'s track model, but cache is null", source);
} else {
cache.Clear ();
if (notify) {
OnReloaded ();
}
}
}
private string unfiltered_query;
public virtual string UnfilteredQuery {
get {
return unfiltered_query ?? (unfiltered_query = String.Format (
"FROM {0} WHERE {1} {2}",
FromFragment,
String.IsNullOrEmpty (provider.Where) ? "1=1" : provider.Where,
ConditionFragment
));
}
}
private string from;
protected string From {
get { return from ?? provider.From; }
set { from = value; }
}
private string from_fragment;
public string FromFragment {
get { return from_fragment ?? (from_fragment = String.Format ("{0}{1}", From, JoinFragment)); }
}
public virtual void UpdateUnfilteredAggregates ()
{
HyenaSqliteCommand count_command = new HyenaSqliteCommand (String.Format (
"SELECT COUNT(*), SUM(CoreTracks.FileSize) {0}", UnfilteredQuery
));
using (HyenaDataReader reader = new HyenaDataReader (connection.Query (count_command))) {
count = reader.Get<long> (0);
filesize = reader.Get<long> (1);
}
}
public override void Reload ()
{
Reload (null);
}
public void Reload (IListModel reloadTrigger)
{
if (cache == null) {
Log.WarningFormat ("Called Reload on {0} for source {1} but cache is null; Did you forget to call AfterInitialized () in your DatabaseSource ctor?",
this, source == null ? "null source!" : source.Name);
return;
}
lock (this) {
GenerateUserQueryFragment ();
UpdateUnfilteredAggregates ();
cache.SaveSelection ();
List<IFilterListModel> reload_models = new List<IFilterListModel> ();
bool found = (reloadTrigger == null);
foreach (IFilterListModel filter in source.CurrentFilters) {
if (found) {
reload_models.Add (filter);
} else if (filter == reloadTrigger) {
found = true;
}
}
if (reload_models.Count == 0) {
ReloadWithFilters (true);
} else {
ReloadWithoutFilters ();
foreach (IFilterListModel model in reload_models) {
model.Reload (false);
}
bool have_filters = false;
foreach (IFilterListModel filter in source.CurrentFilters) {
have_filters |= !filter.Selection.AllSelected;
}
// Unless both artist/album selections are "all" (eg unfiltered), reload
// the track model again with the artist/album filters now in place.
if (have_filters) {
ReloadWithFilters (true);
}
}
cache.UpdateAggregates ();
cache.RestoreSelection ();
filtered_count = cache.Count;
OnReloaded ();
// Trigger these after the track list, b/c visually it's more important for it to update first
foreach (IFilterListModel model in reload_models) {
model.RaiseReloaded ();
}
}
}
private void ReloadWithoutFilters ()
{
ReloadWithFilters (false);
}
private void ReloadWithFilters (bool with_filters)
{
StringBuilder qb = new StringBuilder ();
qb.Append (UnfilteredQuery);
if (with_filters) {
foreach (IFilterListModel filter in source.CurrentFilters) {
string filter_sql = filter.GetSqlFilter ();
if (filter_sql != null) {
qb.Append (" AND ");
qb.Append (filter_sql);
}
}
}
if (query_fragment != null) {
qb.Append (" AND ");
qb.Append (query_fragment);
}
if (sort_query != null) {
qb.Append (" ORDER BY ");
qb.Append (sort_query);
}
reload_fragment = qb.ToString ();
cache.Reload ();
}
public override int IndexOf (TrackInfo track)
{
lock (this) {
if (track is DatabaseTrackInfo) {
return (int) cache.IndexOf (track as DatabaseTrackInfo);
} else if (track is Banshee.Streaming.RadioTrackInfo) {
return (int) cache.IndexOf ((track as Banshee.Streaming.RadioTrackInfo).ParentTrack as DatabaseTrackInfo);
}
return -1;
}
}
public int IndexOfFirst (TrackInfo track)
{
lock (this) {
return IndexOf (cache.GetSingle ("AND MetadataHash = ? ORDER BY OrderID", track.MetadataHash));
}
}
public override TrackInfo GetRandom (DateTime notPlayedSince)
{
return GetRandom (notPlayedSince, PlaybackShuffleMode.Song, true, false, Shuffler.Playback);
}
public TrackInfo GetRandom (DateTime notPlayedSince, PlaybackShuffleMode mode, bool repeat, bool resetSinceTime, Shuffler shuffler)
{
lock (this) {
shuffler.SetModelAndCache (this, cache);
return shuffler.GetRandom (notPlayedSince, mode, repeat, resetSinceTime);
}
}
public override TrackInfo this[int index] {
get {
lock (this) {
return cache.GetValue (index);
}
}
}
public override int Count {
get { return (int) filtered_count; }
}
public TimeSpan Duration {
get { return filtered_duration; }
}
public long FileSize {
get { return filtered_filesize; }
}
public long UnfilteredFileSize {
get { return filesize; }
}
public int UnfilteredCount {
get { return (int) count; }
set { count = value; }
}
public string UserQuery {
get { return user_query; }
set {
lock (this) {
user_query = value;
have_new_user_query = true;
}
}
}
public string ForcedSortQuery {
get { return forced_sort_query ? sort_query : null; }
set {
forced_sort_query = value != null;
sort_query = value;
if (cache != null) {
cache.Clear ();
}
}
}
public string JoinTable {
get { return join_table; }
set {
join_table = value;
join_fragment = String.Format (", {0}", join_table);
}
}
public string JoinFragment {
get { return join_fragment; }
}
public string JoinPrimaryKey {
get { return join_primary_key; }
set { join_primary_key = value; }
}
public string JoinColumn {
get { return join_column; }
set { join_column = value; }
}
public void AddCondition (string part)
{
AddCondition (null, part);
}
public void AddCondition (string tables, string part)
{
if (!String.IsNullOrEmpty (part)) {
condition = condition == null ? part : String.Format ("{0} AND {1}", condition, part);
if (!String.IsNullOrEmpty (tables)) {
condition_from = condition_from == null ? tables : String.Format ("{0}, {1}", condition_from, tables);
}
}
}
public string Condition {
get { return condition; }
}
private string condition_from_fragment;
public string ConditionFromFragment {
get {
if (condition_from_fragment == null) {
if (JoinFragment == null) {
condition_from_fragment = condition_from;
} else {
if (condition_from == null) {
condition_from = "CoreTracks";
}
condition_from_fragment = String.Format ("{0}{1}", condition_from, JoinFragment);
}
}
return condition_from_fragment;
}
}
public string ConditionFragment {
get { return PrefixCondition ("AND"); }
}
private string PrefixCondition (string prefix)
{
string condition = Condition;
return String.IsNullOrEmpty (condition)
? String.Empty
: String.Format (" {0} {1} ", prefix, condition);
}
public int CacheId {
get { return (int) cache.CacheId; }
}
public ISortableColumn SortColumn {
get { return sort_column; }
}
public virtual int RowsInView {
protected get { return rows_in_view; }
set { rows_in_view = value; }
}
int IExportableModel.GetLength ()
{
return Count;
}
IDictionary<string, object> IExportableModel.GetMetadata (int index)
{
return this[index].GenerateExportable ();
}
private string track_ids_sql;
public string TrackIdsSql {
get {
if (track_ids_sql == null) {
if (!CachesJoinTableEntries) {
track_ids_sql = "ItemID FROM CoreCache WHERE ModelID = ? LIMIT ?, ?";
} else {
track_ids_sql = String.Format (
"{0} FROM {1} WHERE {2} IN (SELECT ItemID FROM CoreCache WHERE ModelID = ? LIMIT ?, ?)",
JoinColumn, JoinTable, JoinPrimaryKey
);
}
}
return track_ids_sql;
}
}
private bool caches_join_table_entries = false;
public bool CachesJoinTableEntries {
get { return caches_join_table_entries; }
set { caches_join_table_entries = value; }
}
// Implement ICacheableModel
public int FetchCount {
get { return RowsInView > 0 ? RowsInView * 5 : 100; }
}
public string SelectAggregates {
get { return "SUM(CoreTracks.Duration), SUM(CoreTracks.FileSize)"; }
}
// Implement IDatabaseModel
public string ReloadFragment {
get { return reload_fragment; }
}
public bool CachesValues { get { return false; } }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AspNetEventSource.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Web.Hosting;
using System.Web.Util;
// Name and Guid are part of the public contract (for identification by ETW listeners) so cannot
// be changed. We're statically specifying a GUID using the same logic as EventSource.GetGuid,
// as otherwise EventSource invokes crypto to generate the GUID and this results in an
// unacceptable performance degradation (DevDiv #652801).
[EventSource(Name = "Microsoft-Windows-ASPNET", Guid = "ee799f41-cfa5-550b-bf2c-344747c1c668")]
internal sealed class AspNetEventSource : EventSource {
// singleton
public static readonly AspNetEventSource Instance = new AspNetEventSource();
private unsafe delegate void WriteEventWithRelatedActivityIdCoreDelegate(int eventId, Guid* childActivityID, int eventDataCount, EventData* data);
private readonly WriteEventWithRelatedActivityIdCoreDelegate _writeEventWithRelatedActivityIdCoreDel;
private AspNetEventSource() {
// We need to light up when running on .NET 4.5.1 since we can't compile directly
// against the protected methods we might need to consume. Only ever try creating
// this delegate if we're in full trust, otherwise exceptions could happen at
// inopportune times (such as during invocation).
if (AppDomain.CurrentDomain.IsHomogenous && AppDomain.CurrentDomain.IsFullyTrusted) {
MethodInfo writeEventWithRelatedActivityIdCoreMethod = typeof(EventSource).GetMethod(
"WriteEventWithRelatedActivityIdCore", BindingFlags.Instance | BindingFlags.NonPublic, null,
new Type[] { typeof(int), typeof(Guid*), typeof(int), typeof(EventData*) }, null);
if (writeEventWithRelatedActivityIdCoreMethod != null) {
_writeEventWithRelatedActivityIdCoreDel = (WriteEventWithRelatedActivityIdCoreDelegate)Delegate.CreateDelegate(
typeof(WriteEventWithRelatedActivityIdCoreDelegate), this, writeEventWithRelatedActivityIdCoreMethod, throwOnBindFailure: false);
}
}
}
[NonEvent] // use the private member signature for deducing ETW parameters
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RequestEnteredAspNetPipeline(IIS7WorkerRequest wr, Guid childActivityId) {
if (!IsEnabled()) {
return;
}
Guid parentActivityId = wr.RequestTraceIdentifier;
RequestEnteredAspNetPipelineImpl(parentActivityId, childActivityId);
}
[NonEvent] // use the private member signature for deducing ETW parameters
private unsafe void RequestEnteredAspNetPipelineImpl(Guid iisActivityId, Guid aspNetActivityId) {
if (ActivityIdHelper.Instance == null || _writeEventWithRelatedActivityIdCoreDel == null || iisActivityId == Guid.Empty) {
return;
}
// IIS doesn't always set the current thread's activity ID before invoking user code. Instead,
// its tracing APIs (IHttpTraceContext::RaiseTraceEvent) set the ID, write to ETW, then reset
// the ID. If we want to write a transfer event but the current thread's activity ID is
// incorrect, then we need to mimic this behavior. We don't use a try / finally since
// exceptions here are fatal to the process.
Guid originalThreadActivityId = ActivityIdHelper.Instance.CurrentThreadActivityId;
bool needToSetThreadActivityId = (originalThreadActivityId != iisActivityId);
// Step 1: Set the ID (if necessary)
if (needToSetThreadActivityId) {
ActivityIdHelper.Instance.SetCurrentThreadActivityId(iisActivityId, out originalThreadActivityId);
}
// Step 2: Write to ETW, providing the recipient activity ID.
_writeEventWithRelatedActivityIdCoreDel((int)Events.RequestEnteredAspNetPipeline, &aspNetActivityId, 0, null);
// Step 3: Reset the ID (if necessary)
if (needToSetThreadActivityId) {
Guid unused;
ActivityIdHelper.Instance.SetCurrentThreadActivityId(originalThreadActivityId, out unused);
}
}
// Transfer event signals that control has transitioned from IIS -> ASP.NET.
// Overload used only for deducing ETW parameters; use the public entry point instead.
//
// !! WARNING !!
// The logic in RequestEnteredAspNetPipelineImpl must be kept in [....] with these parameters, otherwise
// type safety violations could occur.
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "ETW looks at this method using reflection.")]
[Event((int)Events.RequestEnteredAspNetPipeline, Level = EventLevel.Informational, Task = (EventTask)Tasks.Request, Opcode = EventOpcode.Send, Version = 1)]
private void RequestEnteredAspNetPipeline() {
throw new NotImplementedException();
}
[NonEvent] // use the private member signature for deducing ETW parameters
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void RequestStarted(IIS7WorkerRequest wr) {
if (!IsEnabled()) {
return;
}
RequestStartedImpl(wr);
}
[NonEvent] // use the private member signature for deducing ETW parameters
private unsafe void RequestStartedImpl(IIS7WorkerRequest wr) {
string httpVerb = wr.GetHttpVerbName();
HTTP_COOKED_URL* pCookedUrl = wr.GetCookedUrl();
Guid iisEtwActivityId = wr.RequestTraceIdentifier;
Guid requestCorrelationId = wr.GetRequestCorrelationId();
fixed (char* pHttpVerb = httpVerb) {
// !! WARNING !!
// This logic must be kept in [....] with the ETW-deduced parameters in RequestStarted,
// otherwise type safety violations could occur.
const int EVENTDATA_COUNT = 3;
EventData* pEventData = stackalloc EventData[EVENTDATA_COUNT];
FillInEventData(&pEventData[0], httpVerb, pHttpVerb);
// We have knowledge that pFullUrl is null-terminated so we can optimize away
// the copy we'd otherwise have to perform. Still need to adjust the length
// to account for the null terminator, though.
Debug.Assert(pCookedUrl->pFullUrl != null);
pEventData[1].DataPointer = (IntPtr)pCookedUrl->pFullUrl;
pEventData[1].Size = checked(pCookedUrl->FullUrlLength + sizeof(char));
FillInEventData(&pEventData[2], &requestCorrelationId);
WriteEventCore((int)Events.RequestStarted, EVENTDATA_COUNT, pEventData);
}
}
// Event signals that ASP.NET has started processing a request.
// Overload used only for deducing ETW parameters; use the public entry point instead.
//
// !! WARNING !!
// The logic in RequestStartedImpl must be kept in [....] with these parameters, otherwise
// type safety violations could occur.
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "ETW looks at this method using reflection.")]
[Event((int)Events.RequestStarted, Level = EventLevel.Informational, Task = (EventTask)Tasks.Request, Opcode = EventOpcode.Start, Version = 1)]
private unsafe void RequestStarted(string HttpVerb, string FullUrl, Guid RequestCorrelationId) {
throw new NotImplementedException();
}
// Event signals that ASP.NET has completed processing a request.
[Event((int)Events.RequestCompleted, Level = EventLevel.Informational, Task = (EventTask)Tasks.Request, Opcode = EventOpcode.Stop, Version = 1)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RequestCompleted() {
if (!IsEnabled()) {
return;
}
WriteEvent((int)Events.RequestCompleted);
}
/*
* Helpers to populate the EventData structure
*/
// prerequisite: str must be pinned and provided as pStr; may be null.
// we'll convert null strings to empty strings if necessary.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe static void FillInEventData(EventData* pEventData, string str, char* pStr) {
#if DBG
fixed (char* pStr2 = str) { Debug.Assert(pStr == pStr2); }
#endif
if (pStr != null) {
pEventData->DataPointer = (IntPtr)pStr;
pEventData->Size = checked((str.Length + 1) * sizeof(char)); // size is specified in bytes, including null wide char
}
else {
pEventData->DataPointer = NullHelper.Instance.PtrToNullChar; // empty string
pEventData->Size = sizeof(char);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe static void FillInEventData(EventData* pEventData, Guid* pGuid) {
Debug.Assert(pGuid != null);
pEventData->DataPointer = (IntPtr)pGuid;
pEventData->Size = sizeof(Guid);
}
// Each ETW event should have its own entry here.
private enum Events {
RequestEnteredAspNetPipeline = 1,
RequestStarted,
RequestCompleted
}
// Tasks are used for correlating events; we're free to define our own.
// For example, Tasks.Request with Opcode = Start matches Tasks.Request with Opcode = Stop,
// and Tasks.Application with Opcode = Start matches Tasks.Application with Opcode = Stop.
//
// EventSource requires that this be a public static class with public const fields,
// otherwise manifest generation could fail at runtime.
public static class Tasks {
public const EventTask Request = (EventTask)1;
}
private sealed class NullHelper : CriticalFinalizerObject {
public static readonly NullHelper Instance = new NullHelper();
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Justification = @"Containing type is a CriticalFinalizerObject.")]
public readonly IntPtr PtrToNullChar;
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private unsafe NullHelper() {
// allocate a single null character
PtrToNullChar = Marshal.AllocHGlobal(sizeof(char));
*((char*)PtrToNullChar) = '\0';
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~NullHelper() {
if (PtrToNullChar != IntPtr.Zero) {
Marshal.FreeHGlobal(PtrToNullChar);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using EdjCase.JsonRpc.Router.Abstractions;
using EdjCase.JsonRpc.Router.Swagger.Extensions;
using EdjCase.JsonRpc.Router.Swagger.Models;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace EdjCase.JsonRpc.Router.Swagger
{
using Microsoft.Extensions.DependencyInjection;
public class JsonRpcSwaggerProvider : ISwaggerProvider
{
private readonly ISchemaGenerator schemaGenerator;
private readonly SwaggerConfiguration swagerOptions;
private readonly IServiceScopeFactory scopeFactory;
private readonly IXmlDocumentationService xmlDocumentationService;
private OpenApiDocument? cacheDocument;
private JsonNamingPolicy namePolicy;
public JsonRpcSwaggerProvider(
ISchemaGenerator schemaGenerator,
IXmlDocumentationService xmlDocumentationService,
IOptions<SwaggerConfiguration> swaggerOptions,
IServiceScopeFactory scopeFactory
)
{
this.schemaGenerator = schemaGenerator;
this.swagerOptions = swaggerOptions.Value;
this.namePolicy = swaggerOptions.Value.NamingPolicy;
this.scopeFactory = scopeFactory;
this.xmlDocumentationService = xmlDocumentationService;
}
private List<UniqueMethod> GetUniqueKeyMethodPairs(RpcRouteMetaData metaData)
{
List<UniqueMethod> methodList = this.Convert(metaData.BaseRoute, path: null).ToList();
foreach ((RpcPath path, IReadOnlyList<IRpcMethodInfo> pathRoutes) in metaData.PathRoutes)
{
methodList.AddRange(this.Convert(pathRoutes, path));
}
return methodList;
}
private IEnumerable<UniqueMethod> Convert(IEnumerable<IRpcMethodInfo> routeInfo, RpcPath? path)
{
//group by name for generate unique url similar method names
foreach (IGrouping<string, IRpcMethodInfo> methodsGroup in routeInfo.GroupBy(x => x.Name))
{
int? methodCounter = methodsGroup.Count() > 1 ? 1 : (int?)null;
foreach (IRpcMethodInfo methodInfo in methodsGroup)
{
string methodName = this.namePolicy.ConvertName(methodInfo.Name);
string uniqueUrl = $"/{path}#{methodName}";
if (methodCounter != null)
{
uniqueUrl += $"#{methodCounter++}";
}
yield return new UniqueMethod(uniqueUrl, methodInfo);
}
}
}
public OpenApiDocument GetSwagger(string documentName, string? host = null, string? basePath = null)
{
if (this.cacheDocument != null)
{
return this.cacheDocument;
}
var schemaRepository = new SchemaRepository();
var methodProvider =
this.scopeFactory.CreateScope().ServiceProvider.GetRequiredService<IRpcMethodProvider>();
RpcRouteMetaData metaData = methodProvider.Get();
OpenApiPaths paths = this.GetOpenApiPaths(metaData, schemaRepository);
this.cacheDocument = new OpenApiDocument()
{
Info = new OpenApiInfo()
{
Title = Assembly.GetEntryAssembly().GetName().Name,
Version = "v1"
},
Servers = this.swagerOptions.Endpoints.Select(x => new OpenApiServer()
{
Url = x
}).ToList(),
Components = new OpenApiComponents()
{
Schemas = schemaRepository.Schemas
},
Paths = paths
};
return this.cacheDocument;
}
private OpenApiPaths GetOpenApiPaths(RpcRouteMetaData metaData, SchemaRepository schemaRepository)
{
OpenApiPaths paths = new OpenApiPaths();
List<UniqueMethod> uniqueMethods = this.GetUniqueKeyMethodPairs(metaData);
foreach (UniqueMethod method in uniqueMethods)
{
string operationKey = method.UniqueUrl.Replace("/", "_").Replace("#", "|");
OpenApiOperation operation = this.GetOpenApiOperation(operationKey, method.Info, schemaRepository);
var pathItem = new OpenApiPathItem()
{
Operations = new Dictionary<OperationType, OpenApiOperation>()
{
[OperationType.Post] = operation
}
};
paths.Add(method.UniqueUrl, pathItem);
}
return paths;
}
private OpenApiOperation GetOpenApiOperation(string key, IRpcMethodInfo methodInfo, SchemaRepository schemaRepository)
{
string methodAnnotation = this.xmlDocumentationService.GetSummaryForMethod(methodInfo);
Type trueReturnType = this.GetReturnType(methodInfo.RawReturnType);
return new OpenApiOperation()
{
Tags = new List<OpenApiTag>(),
Summary = methodAnnotation,
RequestBody = this.GetOpenApiRequestBody(key, methodInfo, schemaRepository),
Responses = this.GetOpenApiResponses(key, trueReturnType, schemaRepository)
};
}
private Type GetReturnType(Type returnType)
{
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
{
//Return the `Task` return type
return returnType.GenericTypeArguments.First();
}
if (returnType == typeof(Task))
{
//Task with no return type
return typeof(void);
}
return returnType;
}
private OpenApiResponses GetOpenApiResponses(string key, Type returnMethodType, SchemaRepository schemaRepository)
{
return new OpenApiResponses()
{
["200"] = new OpenApiResponse()
{
Content = new Dictionary<string, OpenApiMediaType>()
{
["application/json"] = new OpenApiMediaType
{
Schema = this.GeResposeSchema(key, returnMethodType, schemaRepository)
}
}
}
};
}
private OpenApiRequestBody GetOpenApiRequestBody(string key, IRpcMethodInfo methodInfo,
SchemaRepository schemaRepository)
{
return new OpenApiRequestBody()
{
Content = new Dictionary<string, OpenApiMediaType>()
{
["application/json"] = new OpenApiMediaType()
{
Schema = this.GetBodyParamsSchema(key, schemaRepository, methodInfo)
}
}
};
}
private OpenApiSchema GetBodyParamsSchema(string key, SchemaRepository schemaRepository, IRpcMethodInfo methodInfo)
{
OpenApiSchema paramsObjectSchema = this.GetOpenApiEmptyObject();
foreach (IRpcParameterInfo parameterInfo in methodInfo.Parameters)
{
string name = this.namePolicy.ConvertName(parameterInfo.Name);
OpenApiSchema schema = this.schemaGenerator.GenerateSchema(parameterInfo.RawType, schemaRepository);
paramsObjectSchema.Properties.Add(name, schema);
}
paramsObjectSchema = schemaRepository.AddDefinition($"{key}", paramsObjectSchema);
var requestSchema = this.GetOpenApiEmptyObject();
requestSchema.Properties.Add("id", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
requestSchema.Properties.Add("jsonrpc", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
requestSchema.Properties.Add("method", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
requestSchema.Properties.Add("params", paramsObjectSchema);
requestSchema = schemaRepository.AddDefinition($"request_{key}", requestSchema);
this.RewriteJrpcAttributesExamples(requestSchema, schemaRepository, this.namePolicy.ConvertName(methodInfo.Name));
return requestSchema;
}
private OpenApiSchema GeResposeSchema(string key, Type returnMethodType, SchemaRepository schemaRepository)
{
var resultSchema = this.schemaGenerator.GenerateSchema(returnMethodType, schemaRepository);
var responseSchema = this.GetOpenApiEmptyObject();
responseSchema.Properties.Add("id", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
responseSchema.Properties.Add("jsonrpc", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
responseSchema.Properties.Add("result", resultSchema);
responseSchema = schemaRepository.AddDefinition($"response_{key}", responseSchema);
this.RewriteJrpcAttributesExamples(responseSchema, schemaRepository);
return responseSchema;
}
private OpenApiSchema GetOpenApiEmptyObject()
{
return new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>(),
Required = new SortedSet<string>(),
AdditionalPropertiesAllowed = false
};
}
private void RewriteJrpcAttributesExamples(OpenApiSchema schema, SchemaRepository schemaRepository, string method = "method_name")
{
var jrpcAttributesExample =
new OpenApiObject()
{
{"id", new OpenApiString(Guid.NewGuid().ToString())},
{"jsonrpc", new OpenApiString("2.0")},
{"method", new OpenApiString(method)},
};
foreach (var prop in schemaRepository.Schemas[schema.Reference.Id].Properties)
{
if (jrpcAttributesExample.ContainsKey(prop.Key))
{
prop.Value.Example = jrpcAttributesExample[prop.Key];
}
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using OpenHome.Net.Core;
using OpenHome.Net.ControlPoint;
namespace OpenHome.Net.ControlPoint.Proxies
{
public interface ICpProxyOpenhomeOrgTestLights1 : ICpProxy, IDisposable
{
void SyncGetCount(out uint aCount);
void BeginGetCount(CpProxy.CallbackAsyncComplete aCallback);
void EndGetCount(IntPtr aAsyncHandle, out uint aCount);
void SyncGetRoom(uint aIndex, out String aRoomName);
void BeginGetRoom(uint aIndex, CpProxy.CallbackAsyncComplete aCallback);
void EndGetRoom(IntPtr aAsyncHandle, out String aRoomName);
void SyncGetName(uint aIndex, out String aFriendlyName);
void BeginGetName(uint aIndex, CpProxy.CallbackAsyncComplete aCallback);
void EndGetName(IntPtr aAsyncHandle, out String aFriendlyName);
void SyncGetPosition(uint aIndex, out uint aX, out uint aY, out uint aZ);
void BeginGetPosition(uint aIndex, CpProxy.CallbackAsyncComplete aCallback);
void EndGetPosition(IntPtr aAsyncHandle, out uint aX, out uint aY, out uint aZ);
void SyncSetColor(uint aIndex, uint aColor);
void BeginSetColor(uint aIndex, uint aColor, CpProxy.CallbackAsyncComplete aCallback);
void EndSetColor(IntPtr aAsyncHandle);
void SyncGetColor(uint aIndex, out uint aColor);
void BeginGetColor(uint aIndex, CpProxy.CallbackAsyncComplete aCallback);
void EndGetColor(IntPtr aAsyncHandle, out uint aColor);
void SyncGetColorComponents(uint aColor, out uint aBrightness, out uint aRed, out uint aGreen, out uint aBlue);
void BeginGetColorComponents(uint aColor, CpProxy.CallbackAsyncComplete aCallback);
void EndGetColorComponents(IntPtr aAsyncHandle, out uint aBrightness, out uint aRed, out uint aGreen, out uint aBlue);
}
internal class SyncGetCountOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
private uint iCount;
public SyncGetCountOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
public uint Count()
{
return iCount;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndGetCount(aAsyncHandle, out iCount);
}
};
internal class SyncGetRoomOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
private String iRoomName;
public SyncGetRoomOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
public String RoomName()
{
return iRoomName;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndGetRoom(aAsyncHandle, out iRoomName);
}
};
internal class SyncGetNameOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
private String iFriendlyName;
public SyncGetNameOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
public String FriendlyName()
{
return iFriendlyName;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndGetName(aAsyncHandle, out iFriendlyName);
}
};
internal class SyncGetPositionOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
private uint iX;
private uint iY;
private uint iZ;
public SyncGetPositionOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
public uint X()
{
return iX;
}
public uint Y()
{
return iY;
}
public uint Z()
{
return iZ;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndGetPosition(aAsyncHandle, out iX, out iY, out iZ);
}
};
internal class SyncSetColorOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
public SyncSetColorOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndSetColor(aAsyncHandle);
}
};
internal class SyncGetColorOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
private uint iColor;
public SyncGetColorOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
public uint Color()
{
return iColor;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndGetColor(aAsyncHandle, out iColor);
}
};
internal class SyncGetColorComponentsOpenhomeOrgTestLights1 : SyncProxyAction
{
private CpProxyOpenhomeOrgTestLights1 iService;
private uint iBrightness;
private uint iRed;
private uint iGreen;
private uint iBlue;
public SyncGetColorComponentsOpenhomeOrgTestLights1(CpProxyOpenhomeOrgTestLights1 aProxy)
{
iService = aProxy;
}
public uint Brightness()
{
return iBrightness;
}
public uint Red()
{
return iRed;
}
public uint Green()
{
return iGreen;
}
public uint Blue()
{
return iBlue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndGetColorComponents(aAsyncHandle, out iBrightness, out iRed, out iGreen, out iBlue);
}
};
/// <summary>
/// Proxy for the openhome.org:TestLights:1 UPnP service
/// </summary>
public class CpProxyOpenhomeOrgTestLights1 : CpProxy, IDisposable, ICpProxyOpenhomeOrgTestLights1
{
private OpenHome.Net.Core.Action iActionGetCount;
private OpenHome.Net.Core.Action iActionGetRoom;
private OpenHome.Net.Core.Action iActionGetName;
private OpenHome.Net.Core.Action iActionGetPosition;
private OpenHome.Net.Core.Action iActionSetColor;
private OpenHome.Net.Core.Action iActionGetColor;
private OpenHome.Net.Core.Action iActionGetColorComponents;
/// <summary>
/// Constructor
/// </summary>
/// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks>
/// <param name="aDevice">The device to use</param>
public CpProxyOpenhomeOrgTestLights1(ICpDevice aDevice)
: base("openhome-org", "TestLights", 1, aDevice)
{
OpenHome.Net.Core.Parameter param;
List<String> allowedValues = new List<String>();
iActionGetCount = new OpenHome.Net.Core.Action("GetCount");
param = new ParameterUint("Count");
iActionGetCount.AddOutputParameter(param);
iActionGetRoom = new OpenHome.Net.Core.Action("GetRoom");
param = new ParameterUint("Index");
iActionGetRoom.AddInputParameter(param);
param = new ParameterString("RoomName", allowedValues);
iActionGetRoom.AddOutputParameter(param);
iActionGetName = new OpenHome.Net.Core.Action("GetName");
param = new ParameterUint("Index");
iActionGetName.AddInputParameter(param);
param = new ParameterString("FriendlyName", allowedValues);
iActionGetName.AddOutputParameter(param);
iActionGetPosition = new OpenHome.Net.Core.Action("GetPosition");
param = new ParameterUint("Index");
iActionGetPosition.AddInputParameter(param);
param = new ParameterUint("X");
iActionGetPosition.AddOutputParameter(param);
param = new ParameterUint("Y");
iActionGetPosition.AddOutputParameter(param);
param = new ParameterUint("Z");
iActionGetPosition.AddOutputParameter(param);
iActionSetColor = new OpenHome.Net.Core.Action("SetColor");
param = new ParameterUint("Index");
iActionSetColor.AddInputParameter(param);
param = new ParameterUint("Color");
iActionSetColor.AddInputParameter(param);
iActionGetColor = new OpenHome.Net.Core.Action("GetColor");
param = new ParameterUint("Index");
iActionGetColor.AddInputParameter(param);
param = new ParameterUint("Color");
iActionGetColor.AddOutputParameter(param);
iActionGetColorComponents = new OpenHome.Net.Core.Action("GetColorComponents");
param = new ParameterUint("Color");
iActionGetColorComponents.AddInputParameter(param);
param = new ParameterUint("Brightness");
iActionGetColorComponents.AddOutputParameter(param);
param = new ParameterUint("Red");
iActionGetColorComponents.AddOutputParameter(param);
param = new ParameterUint("Green");
iActionGetColorComponents.AddOutputParameter(param);
param = new ParameterUint("Blue");
iActionGetColorComponents.AddOutputParameter(param);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aCount"></param>
public void SyncGetCount(out uint aCount)
{
SyncGetCountOpenhomeOrgTestLights1 sync = new SyncGetCountOpenhomeOrgTestLights1(this);
BeginGetCount(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aCount = sync.Count();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndGetCount().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginGetCount(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionGetCount, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetCount.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aCount"></param>
public void EndGetCount(IntPtr aAsyncHandle, out uint aCount)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aCount = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aIndex"></param>
/// <param name="aRoomName"></param>
public void SyncGetRoom(uint aIndex, out String aRoomName)
{
SyncGetRoomOpenhomeOrgTestLights1 sync = new SyncGetRoomOpenhomeOrgTestLights1(this);
BeginGetRoom(aIndex, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aRoomName = sync.RoomName();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndGetRoom().</remarks>
/// <param name="aIndex"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginGetRoom(uint aIndex, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionGetRoom, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionGetRoom.InputParameter(inIndex++), aIndex));
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionGetRoom.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aRoomName"></param>
public void EndGetRoom(IntPtr aAsyncHandle, out String aRoomName)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aRoomName = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aIndex"></param>
/// <param name="aFriendlyName"></param>
public void SyncGetName(uint aIndex, out String aFriendlyName)
{
SyncGetNameOpenhomeOrgTestLights1 sync = new SyncGetNameOpenhomeOrgTestLights1(this);
BeginGetName(aIndex, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aFriendlyName = sync.FriendlyName();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndGetName().</remarks>
/// <param name="aIndex"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginGetName(uint aIndex, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionGetName, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionGetName.InputParameter(inIndex++), aIndex));
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionGetName.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aFriendlyName"></param>
public void EndGetName(IntPtr aAsyncHandle, out String aFriendlyName)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aFriendlyName = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aIndex"></param>
/// <param name="aX"></param>
/// <param name="aY"></param>
/// <param name="aZ"></param>
public void SyncGetPosition(uint aIndex, out uint aX, out uint aY, out uint aZ)
{
SyncGetPositionOpenhomeOrgTestLights1 sync = new SyncGetPositionOpenhomeOrgTestLights1(this);
BeginGetPosition(aIndex, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aX = sync.X();
aY = sync.Y();
aZ = sync.Z();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndGetPosition().</remarks>
/// <param name="aIndex"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginGetPosition(uint aIndex, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionGetPosition, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionGetPosition.InputParameter(inIndex++), aIndex));
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetPosition.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetPosition.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetPosition.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aX"></param>
/// <param name="aY"></param>
/// <param name="aZ"></param>
public void EndGetPosition(IntPtr aAsyncHandle, out uint aX, out uint aY, out uint aZ)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aX = Invocation.OutputUint(aAsyncHandle, index++);
aY = Invocation.OutputUint(aAsyncHandle, index++);
aZ = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
public void SyncSetColor(uint aIndex, uint aColor)
{
SyncSetColorOpenhomeOrgTestLights1 sync = new SyncSetColorOpenhomeOrgTestLights1(this);
BeginSetColor(aIndex, aColor, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndSetColor().</remarks>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginSetColor(uint aIndex, uint aColor, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionSetColor, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionSetColor.InputParameter(inIndex++), aIndex));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionSetColor.InputParameter(inIndex++), aColor));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
public void EndSetColor(IntPtr aAsyncHandle)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
public void SyncGetColor(uint aIndex, out uint aColor)
{
SyncGetColorOpenhomeOrgTestLights1 sync = new SyncGetColorOpenhomeOrgTestLights1(this);
BeginGetColor(aIndex, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aColor = sync.Color();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndGetColor().</remarks>
/// <param name="aIndex"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginGetColor(uint aIndex, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionGetColor, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionGetColor.InputParameter(inIndex++), aIndex));
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetColor.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aColor"></param>
public void EndGetColor(IntPtr aAsyncHandle, out uint aColor)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aColor = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aColor"></param>
/// <param name="aBrightness"></param>
/// <param name="aRed"></param>
/// <param name="aGreen"></param>
/// <param name="aBlue"></param>
public void SyncGetColorComponents(uint aColor, out uint aBrightness, out uint aRed, out uint aGreen, out uint aBlue)
{
SyncGetColorComponentsOpenhomeOrgTestLights1 sync = new SyncGetColorComponentsOpenhomeOrgTestLights1(this);
BeginGetColorComponents(aColor, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aBrightness = sync.Brightness();
aRed = sync.Red();
aGreen = sync.Green();
aBlue = sync.Blue();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndGetColorComponents().</remarks>
/// <param name="aColor"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginGetColorComponents(uint aColor, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionGetColorComponents, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionGetColorComponents.InputParameter(inIndex++), aColor));
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetColorComponents.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetColorComponents.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetColorComponents.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionGetColorComponents.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aBrightness"></param>
/// <param name="aRed"></param>
/// <param name="aGreen"></param>
/// <param name="aBlue"></param>
public void EndGetColorComponents(IntPtr aAsyncHandle, out uint aBrightness, out uint aRed, out uint aGreen, out uint aBlue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aBrightness = Invocation.OutputUint(aAsyncHandle, index++);
aRed = Invocation.OutputUint(aAsyncHandle, index++);
aGreen = Invocation.OutputUint(aAsyncHandle, index++);
aBlue = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public void Dispose()
{
lock (this)
{
if (iHandle == IntPtr.Zero)
return;
DisposeProxy();
iHandle = IntPtr.Zero;
}
iActionGetCount.Dispose();
iActionGetRoom.Dispose();
iActionGetName.Dispose();
iActionGetPosition.Dispose();
iActionSetColor.Dispose();
iActionGetColor.Dispose();
iActionGetColorComponents.Dispose();
}
}
}
| |
// DocumentInstance.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
using System.Html.Editing;
namespace System.Html {
[ScriptIgnoreNamespace]
[ScriptImport]
public sealed class DocumentInstance {
private DocumentInstance() {
}
[ScriptField]
public Element ActiveElement {
get {
return null;
}
}
[ScriptField]
public Element Body {
get {
return null;
}
}
[ScriptField]
public string Cookie {
get {
return null;
}
set {
}
}
[ScriptField]
public string DesignMode {
get {
return null;
}
set {
}
}
[ScriptField]
public string Doctype {
get {
return null;
}
}
[ScriptField]
public Element DocumentElement {
get {
return null;
}
}
[ScriptField]
public string Domain {
get {
return null;
}
set {
}
}
[ScriptField]
public DocumentImplementation Implementation {
get {
return null;
}
}
[ScriptField]
public WindowInstance ParentWindow {
get {
return null;
}
}
[ScriptField]
public string ReadyState {
get {
return null;
}
}
[ScriptField]
public string Referrer {
get {
return null;
}
}
[ScriptField]
public Selection Selection {
get {
return null;
}
}
[ScriptField]
public string Title {
get {
return null;
}
set {
}
}
[ScriptField]
public string URL {
get {
return null;
}
}
/// <summary>
/// Adds a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
public void AddEventListener(string eventName, ElementEventListener listener) {
}
/// <summary>
/// Adds a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
/// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param>
public void AddEventListener(string eventName, ElementEventListener listener, bool useCapture) {
}
public void AttachEvent(string eventName, ElementEventHandler handler) {
}
public void Close() {
}
public ElementAttribute CreateAttribute(string name) {
return null;
}
public DocumentFragment CreateDocumentFragment() {
return null;
}
public Element CreateElement(string tagName) {
return null;
}
public MutableEvent CreateEvent(string eventType) {
return null;
}
public Element CreateTextNode(string tagName) {
return null;
}
public void DetachEvent(string eventName, ElementEventHandler handler) {
}
public bool DispatchEvent(MutableEvent eventObject) {
return false;
}
public Element ElementFromPoint(int x, int y) {
return null;
}
public bool ExecCommand(string command, bool displayUserInterface, object value) {
return false;
}
public void Focus() {
}
public Element GetElementById(string id) {
return null;
}
public TElement GetElementById<TElement>(string id) where TElement : Element {
return null;
}
public ElementCollection GetElementsByClassName(string className) {
return null;
}
public ElementCollection GetElementsByName(string name) {
return null;
}
public ElementCollection GetElementsByTagName(string tagName) {
return null;
}
public bool HasFocus() {
return false;
}
public void Open() {
}
public bool QueryCommandEnabled(string command) {
return false;
}
public bool QueryCommandIndeterm(string command) {
return false;
}
public bool QueryCommandState(string command) {
return false;
}
public bool QueryCommandSupported(string command) {
return false;
}
public object QueryCommandValue(string command) {
return null;
}
public Element QuerySelector(string selector) {
return null;
}
public ElementCollection QuerySelectorAll(string selector) {
return null;
}
/// <summary>
/// Removes a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
public void RemoveEventListener(string eventName, ElementEventListener listener) {
}
/// <summary>
/// Removes a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
/// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param>
public void RemoveEventListener(string eventName, ElementEventListener listener, bool useCapture) {
}
public void Write(string text) {
}
public void Writeln(string text) {
}
}
}
| |
// 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.Specialized;
using System.Text;
using System.Net.Mail;
namespace System.Net.Mime
{
internal class MimeBasePart
{
internal const string DefaultCharSet = "utf-8";
private static readonly char[] s_decodeEncodingSplitChars = new char[] { '?', '\r', '\n' };
protected ContentType _contentType;
protected ContentDisposition _contentDisposition;
private HeaderCollection _headers;
internal MimeBasePart() { }
internal static bool ShouldUseBase64Encoding(Encoding encoding) =>
encoding == Encoding.Unicode || encoding == Encoding.UTF8 || encoding == Encoding.UTF32 || encoding == Encoding.BigEndianUnicode;
//use when the length of the header is not known or if there is no header
internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding) =>
EncodeHeaderValue(value, encoding, base64Encoding, 0);
//used when the length of the header name itself is known (i.e. Subject : )
internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding, int headerLength)
{
//no need to encode if it's pure ascii
if (IsAscii(value, false))
{
return value;
}
if (encoding == null)
{
encoding = Encoding.GetEncoding(DefaultCharSet);
}
EncodedStreamFactory factory = new EncodedStreamFactory();
IEncodableStream stream = factory.GetEncoderForHeader(encoding, base64Encoding, headerLength);
byte[] buffer = encoding.GetBytes(value);
stream.EncodeBytes(buffer, 0, buffer.Length);
return stream.GetEncodedString();
}
private static readonly char[] s_headerValueSplitChars = new char[] { '\r', '\n', ' ' };
private static readonly char[] s_questionMarkSplitChars = new char[] { '?' };
internal static string DecodeHeaderValue(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
string newValue = string.Empty;
//split strings, they may be folded. If they are, decode one at a time and append the results
string[] substringsToDecode = value.Split(s_headerValueSplitChars, StringSplitOptions.RemoveEmptyEntries);
foreach (string foldedSubString in substringsToDecode)
{
//an encoded string has as specific format in that it must start and end with an
//'=' char and contains five parts, separated by '?' chars.
//the first and last part are therefore '=', the second part is the byte encoding (B or Q)
//the third is the unicode encoding type, and the fourth is encoded message itself. '?' is not valid inside of
//an encoded string other than as a separator for these five parts.
//If this check fails, the string is either not encoded or cannot be decoded by this method
string[] subStrings = foldedSubString.Split(s_questionMarkSplitChars);
if ((subStrings.Length != 5 || subStrings[0] != "=" || subStrings[4] != "="))
{
return value;
}
string charSet = subStrings[1];
bool base64Encoding = (subStrings[2] == "B");
byte[] buffer = Encoding.ASCII.GetBytes(subStrings[3]);
int newLength;
EncodedStreamFactory encoderFactory = new EncodedStreamFactory();
IEncodableStream s = encoderFactory.GetEncoderForHeader(Encoding.GetEncoding(charSet), base64Encoding, 0);
newLength = s.DecodeBytes(buffer, 0, buffer.Length);
Encoding encoding = Encoding.GetEncoding(charSet);
newValue += encoding.GetString(buffer, 0, newLength);
}
return newValue;
}
// Detect the encoding: "=?encoding?BorQ?content?="
// "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?="; // 3.5
// With the addition of folding in 4.0, there may be multiple lines with encoding, only detect the first:
// "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?=\r\n =?utf-8?B??=";
internal static Encoding DecodeEncoding(string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
string[] subStrings = value.Split(s_decodeEncodingSplitChars);
if ((subStrings.Length < 5 || subStrings[0] != "=" || subStrings[4] != "="))
{
return null;
}
string charSet = subStrings[1];
return Encoding.GetEncoding(charSet);
}
internal static bool IsAscii(string value, bool permitCROrLF)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
foreach (char c in value)
{
if (c > 0x7f)
{
return false;
}
if (!permitCROrLF && (c == '\r' || c == '\n'))
{
return false;
}
}
return true;
}
internal static bool IsAnsi(string value, bool permitCROrLF)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
foreach (char c in value)
{
if (c > 0xff)
{
return false;
}
if (!permitCROrLF && (c == '\r' || c == '\n'))
{
return false;
}
}
return true;
}
internal string ContentID
{
get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)]; }
set
{
if (string.IsNullOrEmpty(value))
{
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentID));
}
else
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)] = value;
}
}
}
internal string ContentLocation
{
get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)]; }
set
{
if (string.IsNullOrEmpty(value))
{
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentLocation));
}
else
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)] = value;
}
}
}
internal NameValueCollection Headers
{
get
{
//persist existing info before returning
if (_headers == null)
{
_headers = new HeaderCollection();
}
if (_contentType == null)
{
_contentType = new ContentType();
}
_contentType.PersistIfNeeded(_headers, false);
if (_contentDisposition != null)
{
_contentDisposition.PersistIfNeeded(_headers, false);
}
return _headers;
}
}
internal ContentType ContentType
{
get { return _contentType ?? (_contentType = new ContentType()); }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_contentType = value;
_contentType.PersistIfNeeded((HeaderCollection)Headers, true);
}
}
internal void PrepareHeaders(bool allowUnicode)
{
_contentType.PersistIfNeeded((HeaderCollection)Headers, false);
_headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), _contentType.Encode(allowUnicode));
if (_contentDisposition != null)
{
_contentDisposition.PersistIfNeeded((HeaderCollection)Headers, false);
_headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), _contentDisposition.Encode(allowUnicode));
}
}
internal virtual void Send(BaseWriter writer, bool allowUnicode)
{
throw new NotImplementedException();
}
internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback,
bool allowUnicode, object state)
{
throw new NotImplementedException();
}
internal void EndSend(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult castedAsyncResult = asyncResult as MimePartAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndSend)));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
if (castedAsyncResult.Result is Exception)
{
throw (Exception)castedAsyncResult.Result;
}
}
internal class MimePartAsyncResult : LazyAsyncResult
{
internal MimePartAsyncResult(MimeBasePart part, object state, AsyncCallback callback) : base(part, state, callback)
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Text;
using System.Reflection;
using System.Linq;
using System.Security.Permissions;
using System.Security;
namespace System.Data.Linq {
using System.Data.Linq.Mapping;
using System.Data.Linq.Provider;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Controls how inserts, updates and deletes are performed.
/// </summary>
internal abstract class ChangeDirector {
internal abstract int Insert(TrackedObject item);
internal abstract int DynamicInsert(TrackedObject item);
internal abstract void AppendInsertText(TrackedObject item, StringBuilder appendTo);
internal abstract int Update(TrackedObject item);
internal abstract int DynamicUpdate(TrackedObject item);
internal abstract void AppendUpdateText(TrackedObject item, StringBuilder appendTo);
internal abstract int Delete(TrackedObject item);
internal abstract int DynamicDelete(TrackedObject item);
internal abstract void AppendDeleteText(TrackedObject item, StringBuilder appendTo);
internal abstract void RollbackAutoSync();
internal abstract void ClearAutoSyncRollback();
internal static ChangeDirector CreateChangeDirector(DataContext context) {
return new StandardChangeDirector(context);
}
/// <summary>
/// Implementation of ChangeDirector which calls user code if possible
/// and othewise falls back to creating SQL for 'INSERT', 'UPDATE' and 'DELETE'.
/// </summary>
internal class StandardChangeDirector : ChangeDirector {
private enum UpdateType { Insert, Update, Delete };
private enum AutoSyncBehavior { ApplyNewAutoSync, RollbackSavedValues }
DataContext context;
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification="[....]: FxCop bug Dev10:423110 -- List<KeyValuePair<object, object>> is not supposed to be flagged as a violation.")]
List<KeyValuePair<TrackedObject, object[]>> syncRollbackItems;
internal StandardChangeDirector(DataContext context) {
this.context = context;
}
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification="[....]: FxCop bug Dev10:423110 -- List<KeyValuePair<object, object>> is not supposed to be flagged as a violation.")]
private List<KeyValuePair<TrackedObject, object[]>> SyncRollbackItems {
get {
if (syncRollbackItems == null) {
syncRollbackItems = new List<KeyValuePair<TrackedObject, object[]>>();
}
return syncRollbackItems;
}
}
internal override int Insert(TrackedObject item) {
if (item.Type.Table.InsertMethod != null) {
try {
item.Type.Table.InsertMethod.Invoke(this.context, new object[] { item.Current });
}
catch (TargetInvocationException tie) {
if (tie.InnerException != null) {
throw tie.InnerException;
}
throw;
}
return 1;
}
else {
return DynamicInsert(item);
}
}
internal override int DynamicInsert(TrackedObject item) {
Expression cmd = this.GetInsertCommand(item);
if (cmd.Type == typeof(int)) {
return (int)this.context.Provider.Execute(cmd).ReturnValue;
}
else {
IEnumerable<object> facts = (IEnumerable<object>)this.context.Provider.Execute(cmd).ReturnValue;
object[] syncResults = (object[])facts.FirstOrDefault();
if (syncResults != null) {
// [....] any auto gen or computed members
AutoSyncMembers(syncResults, item, UpdateType.Insert, AutoSyncBehavior.ApplyNewAutoSync);
return 1;
}
else {
throw Error.InsertAutoSyncFailure();
}
}
}
internal override void AppendInsertText(TrackedObject item, StringBuilder appendTo) {
if (item.Type.Table.InsertMethod != null) {
appendTo.Append(Strings.InsertCallbackComment);
}
else {
Expression cmd = this.GetInsertCommand(item);
appendTo.Append(this.context.Provider.GetQueryText(cmd));
appendTo.AppendLine();
}
}
/// <summary>
/// Update the item, returning 0 if the update fails, 1 if it succeeds.
/// </summary>
internal override int Update(TrackedObject item) {
if (item.Type.Table.UpdateMethod != null) {
// create a copy - don't allow the override to modify our
// internal original values
try {
item.Type.Table.UpdateMethod.Invoke(this.context, new object[] { item.Current });
}
catch (TargetInvocationException tie) {
if (tie.InnerException != null) {
throw tie.InnerException;
}
throw;
}
return 1;
}
else {
return DynamicUpdate(item);
}
}
internal override int DynamicUpdate(TrackedObject item) {
Expression cmd = this.GetUpdateCommand(item);
if (cmd.Type == typeof(int)) {
return (int)this.context.Provider.Execute(cmd).ReturnValue;
}
else {
IEnumerable<object> facts = (IEnumerable<object>)this.context.Provider.Execute(cmd).ReturnValue;
object[] syncResults = (object[])facts.FirstOrDefault();
if (syncResults != null) {
// [....] any auto gen or computed members
AutoSyncMembers(syncResults, item, UpdateType.Update, AutoSyncBehavior.ApplyNewAutoSync);
return 1;
}
else {
return 0;
}
}
}
internal override void AppendUpdateText(TrackedObject item, StringBuilder appendTo) {
if (item.Type.Table.UpdateMethod != null) {
appendTo.Append(Strings.UpdateCallbackComment);
}
else {
Expression cmd = this.GetUpdateCommand(item);
appendTo.Append(this.context.Provider.GetQueryText(cmd));
appendTo.AppendLine();
}
}
internal override int Delete(TrackedObject item) {
if (item.Type.Table.DeleteMethod != null) {
try {
item.Type.Table.DeleteMethod.Invoke(this.context, new object[] { item.Current });
}
catch (TargetInvocationException tie) {
if (tie.InnerException != null) {
throw tie.InnerException;
}
throw;
}
return 1;
}
else {
return DynamicDelete(item);
}
}
internal override int DynamicDelete(TrackedObject item) {
Expression cmd = this.GetDeleteCommand(item);
int ret = (int)this.context.Provider.Execute(cmd).ReturnValue;
if (ret == 0) {
// we don't yet know if the delete failed because the check constaint did not match
// or item was already deleted. Verify the item exists
cmd = this.GetDeleteVerificationCommand(item);
ret = ((int?)this.context.Provider.Execute(cmd).ReturnValue) ?? -1;
}
return ret;
}
internal override void AppendDeleteText(TrackedObject item, StringBuilder appendTo) {
if (item.Type.Table.DeleteMethod != null) {
appendTo.Append(Strings.DeleteCallbackComment);
}
else {
Expression cmd = this.GetDeleteCommand(item);
appendTo.Append(this.context.Provider.GetQueryText(cmd));
appendTo.AppendLine();
}
}
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification="[....]: FxCop bug Dev10:423110 -- List<KeyValuePair<object, object>> is not supposed to be flagged as a violation.")]
internal override void RollbackAutoSync() {
// Rolls back any AutoSync values that may have been set already
// Those values are no longer valid since the transaction will be rolled back on the server
if (this.syncRollbackItems != null) {
foreach (KeyValuePair<TrackedObject, object[]> rollbackItemPair in this.SyncRollbackItems) {
TrackedObject rollbackItem = rollbackItemPair.Key;
object[] rollbackValues = rollbackItemPair.Value;
AutoSyncMembers(
rollbackValues,
rollbackItem,
rollbackItem.IsNew ? UpdateType.Insert : UpdateType.Update,
AutoSyncBehavior.RollbackSavedValues);
}
}
}
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification="[....]: FxCop bug Dev10:423110 -- List<KeyValuePair<object, object>> is not supposed to be flagged as a violation.")]
internal override void ClearAutoSyncRollback() {
this.syncRollbackItems = null;
}
private Expression GetInsertCommand(TrackedObject item) {
MetaType mt = item.Type;
// bind to InsertFacts if there are any members to syncronize
List<MetaDataMember> membersToSync = GetAutoSyncMembers(mt, UpdateType.Insert);
ParameterExpression p = Expression.Parameter(item.Type.Table.RowType.Type, "p");
if (membersToSync.Count > 0) {
Expression autoSync = this.CreateAutoSync(membersToSync, p);
LambdaExpression resultSelector = Expression.Lambda(autoSync, p);
return Expression.Call(typeof(DataManipulation), "Insert", new Type[] { item.Type.InheritanceRoot.Type, resultSelector.Body.Type }, Expression.Constant(item.Current), resultSelector);
}
else {
return Expression.Call(typeof(DataManipulation), "Insert", new Type[] { item.Type.InheritanceRoot.Type }, Expression.Constant(item.Current));
}
}
/// <summary>
/// For the meta members specified, create an array initializer for each and bind to
/// an output array.
/// </summary>
private Expression CreateAutoSync(List<MetaDataMember> membersToSync, Expression source) {
System.Diagnostics.Debug.Assert(membersToSync.Count > 0);
int i = 0;
Expression[] initializers = new Expression[membersToSync.Count];
foreach (MetaDataMember mm in membersToSync) {
initializers[i++] = Expression.Convert(this.GetMemberExpression(source, mm.Member), typeof(object));
}
return Expression.NewArrayInit(typeof(object), initializers);
}
private static List<MetaDataMember> GetAutoSyncMembers(MetaType metaType, UpdateType updateType) {
List<MetaDataMember> membersToSync = new List<MetaDataMember>();
foreach (MetaDataMember metaMember in metaType.PersistentDataMembers.OrderBy(m => m.Ordinal)) {
// add all auto generated members for the specified update type to the auto-[....] list
if ((updateType == UpdateType.Insert && metaMember.AutoSync == AutoSync.OnInsert) ||
(updateType == UpdateType.Update && metaMember.AutoSync == AutoSync.OnUpdate) ||
metaMember.AutoSync == AutoSync.Always) {
membersToSync.Add(metaMember);
}
}
return membersToSync;
}
/// <summary>
/// Synchronize the specified item by copying in data from the specified results.
/// Used to [....] members after successful insert or update, but also used to rollback to previous values if a failure
/// occurs on other entities in the same SubmitChanges batch.
/// </summary>
/// <param name="autoSyncBehavior">
/// If AutoSyncBehavior.ApplyNewAutoSync, the current value of the property is saved before the [....] occurs. This is used for normal synchronization after a successful update/insert.
/// Otherwise, the current value is not saved. This is used for rollback operations when something in the SubmitChanges batch failed, rendering the previously-[....]'d values invalid.
/// </param>
[SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification="[....]: FxCop bug Dev10:423110 -- List<KeyValuePair<object, object>> is not supposed to be flagged as a violation.")]
private void AutoSyncMembers(object[] syncResults, TrackedObject item, UpdateType updateType, AutoSyncBehavior autoSyncBehavior) {
System.Diagnostics.Debug.Assert(item != null);
System.Diagnostics.Debug.Assert(item.IsNew || item.IsPossiblyModified, "AutoSyncMembers should only be called for new and modified objects.");
object[] syncRollbackValues = null;
if (syncResults != null) {
int idx = 0;
List<MetaDataMember> membersToSync = GetAutoSyncMembers(item.Type, updateType);
System.Diagnostics.Debug.Assert(syncResults.Length == membersToSync.Count);
if (autoSyncBehavior == AutoSyncBehavior.ApplyNewAutoSync) {
syncRollbackValues = new object[syncResults.Length];
}
foreach (MetaDataMember mm in membersToSync) {
object value = syncResults[idx];
object current = item.Current;
MetaAccessor accessor =
(mm.Member is PropertyInfo && ((PropertyInfo)mm.Member).CanWrite)
? mm.MemberAccessor
: mm.StorageAccessor;
if (syncRollbackValues != null) {
syncRollbackValues[idx] = accessor.GetBoxedValue(current);
}
accessor.SetBoxedValue(ref current, DBConvert.ChangeType(value, mm.Type));
idx++;
}
}
if (syncRollbackValues != null) {
this.SyncRollbackItems.Add(new KeyValuePair<TrackedObject, object[]>(item, syncRollbackValues));
}
}
private Expression GetUpdateCommand(TrackedObject tracked) {
object database = tracked.Original;
MetaType rowType = tracked.Type.GetInheritanceType(database.GetType());
MetaType rowTypeRoot = rowType.InheritanceRoot;
ParameterExpression p = Expression.Parameter(rowTypeRoot.Type, "p");
Expression pv = p;
if (rowType != rowTypeRoot) {
pv = Expression.Convert(p, rowType.Type);
}
Expression check = this.GetUpdateCheck(pv, tracked);
if (check != null) {
check = Expression.Lambda(check, p);
}
// bind to out array if there are any members to synchronize
List<MetaDataMember> membersToSync = GetAutoSyncMembers(rowType, UpdateType.Update);
if (membersToSync.Count > 0) {
Expression autoSync = this.CreateAutoSync(membersToSync, pv);
LambdaExpression resultSelector = Expression.Lambda(autoSync, p);
if (check != null) {
return Expression.Call(typeof(DataManipulation), "Update", new Type[] { rowTypeRoot.Type, resultSelector.Body.Type }, Expression.Constant(tracked.Current), check, resultSelector);
}
else {
return Expression.Call(typeof(DataManipulation), "Update", new Type[] { rowTypeRoot.Type, resultSelector.Body.Type }, Expression.Constant(tracked.Current), resultSelector);
}
}
else if (check != null) {
return Expression.Call(typeof(DataManipulation), "Update", new Type[] { rowTypeRoot.Type }, Expression.Constant(tracked.Current), check);
}
else {
return Expression.Call(typeof(DataManipulation), "Update", new Type[] { rowTypeRoot.Type }, Expression.Constant(tracked.Current));
}
}
private Expression GetUpdateCheck(Expression serverItem, TrackedObject tracked) {
MetaType mt = tracked.Type;
if (mt.VersionMember != null) {
return Expression.Equal(
this.GetMemberExpression(serverItem, mt.VersionMember.Member),
this.GetMemberExpression(Expression.Constant(tracked.Current), mt.VersionMember.Member)
);
}
else {
Expression expr = null;
foreach (MetaDataMember mm in mt.PersistentDataMembers) {
if (!mm.IsPrimaryKey) {
UpdateCheck check = mm.UpdateCheck;
if (check == UpdateCheck.Always ||
(check == UpdateCheck.WhenChanged && tracked.HasChangedValue(mm))) {
object memberValue = mm.MemberAccessor.GetBoxedValue(tracked.Original);
Expression eq =
Expression.Equal(
this.GetMemberExpression(serverItem, mm.Member),
Expression.Constant(memberValue, mm.Type)
);
expr = (expr != null) ? Expression.And(expr, eq) : eq;
}
}
}
return expr;
}
}
private Expression GetDeleteCommand(TrackedObject tracked) {
MetaType rowType = tracked.Type;
MetaType rowTypeRoot = rowType.InheritanceRoot;
ParameterExpression p = Expression.Parameter(rowTypeRoot.Type, "p");
Expression pv = p;
if (rowType != rowTypeRoot) {
pv = Expression.Convert(p, rowType.Type);
}
object original = tracked.CreateDataCopy(tracked.Original);
Expression check = this.GetUpdateCheck(pv, tracked);
if (check != null) {
check = Expression.Lambda(check, p);
return Expression.Call(typeof(DataManipulation), "Delete", new Type[] { rowTypeRoot.Type }, Expression.Constant(original), check);
}
else {
return Expression.Call(typeof(DataManipulation), "Delete", new Type[] { rowTypeRoot.Type }, Expression.Constant(original));
}
}
private Expression GetDeleteVerificationCommand(TrackedObject tracked) {
ITable table = this.context.GetTable(tracked.Type.InheritanceRoot.Type);
System.Diagnostics.Debug.Assert(table != null);
ParameterExpression p = Expression.Parameter(table.ElementType, "p");
Expression pred = Expression.Lambda(Expression.Equal(p, Expression.Constant(tracked.Current)), p);
Expression where = Expression.Call(typeof(Queryable), "Where", new Type[] { table.ElementType }, table.Expression, pred);
Expression selector = Expression.Lambda(Expression.Constant(0, typeof(int?)), p);
Expression select = Expression.Call(typeof(Queryable), "Select", new Type[] { table.ElementType, typeof(int?) }, where, selector);
Expression singleOrDefault = Expression.Call(typeof(Queryable), "SingleOrDefault", new Type[] { typeof(int?) }, select);
return singleOrDefault;
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
private Expression GetMemberExpression(Expression exp, MemberInfo mi) {
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return Expression.Field(exp, fi);
PropertyInfo pi = (PropertyInfo)mi;
return Expression.Property(exp, pi);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel.Channels;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.Runtime;
using System.Runtime.Serialization;
[DataContract]
public class MessageFilterTable<TFilterData> : IMessageFilterTable<TFilterData>
{
Dictionary<Type, Type> filterTypeMappings;
Dictionary<MessageFilter, TFilterData> filters;
SortedBuffer<FilterTableEntry, TableEntryComparer> tables;
int defaultPriority;
static readonly TableEntryComparer staticComparerInstance = new TableEntryComparer();
public MessageFilterTable()
: this(0)
{
}
public MessageFilterTable(int defaultPriority)
{
Init(defaultPriority);
}
[OnDeserializing]
private void OnDeserializing(StreamingContext context)
{
Init(0);
}
void Init(int defaultPriority)
{
CreateEmptyTables();
this.defaultPriority = defaultPriority;
}
public TFilterData this[MessageFilter filter]
{
get
{
return this.filters[filter];
}
set
{
if (this.ContainsKey(filter))
{
int p = this.GetPriority(filter);
this.Remove(filter);
this.Add(filter, value, p);
}
else
{
this.Add(filter, value, this.defaultPriority);
}
}
}
public int Count
{
get
{
return this.filters.Count;
}
}
[DataMember]
public int DefaultPriority
{
get
{
return this.defaultPriority;
}
set
{
this.defaultPriority = value;
}
}
[DataMember]
Entry[] Entries
{
get
{
Entry[] entries = new Entry[Count];
int i = 0;
foreach (KeyValuePair<MessageFilter, TFilterData> item in this.filters)
{
entries[i++] = new Entry(item.Key, item.Value, GetPriority(item.Key));
}
return entries;
}
set
{
for (int i = 0; i < value.Length; ++i)
{
Entry e = value[i];
Add(e.filter, e.data, e.priority);
}
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public ICollection<MessageFilter> Keys
{
get
{
return this.filters.Keys;
}
}
public ICollection<TFilterData> Values
{
get
{
return this.filters.Values;
}
}
public void Add(MessageFilter filter, TFilterData data)
{
this.Add(filter, data, this.defaultPriority);
}
[SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "filterTypeMappings", Justification = "No need to support type equivalence here.")]
public void Add(MessageFilter filter, TFilterData data, int priority)
{
if (filter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("filter");
}
if (this.filters.ContainsKey(filter))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("filter", SR.GetString(SR.FilterExists));
}
#pragma warning suppress 56506 // [....], PreSharp generates a false warning here
Type filterType = filter.GetType();
Type tableType = null;
IMessageFilterTable<TFilterData> table = null;
if (this.filterTypeMappings.TryGetValue(filterType, out tableType))
{
for (int i = 0; i < this.tables.Count; ++i)
{
if (this.tables[i].priority == priority && this.tables[i].table.GetType().Equals(tableType))
{
table = this.tables[i].table;
break;
}
}
if (table == null)
{
table = CreateFilterTable(filter);
ValidateTable(table);
if (!table.GetType().Equals(tableType))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.FilterTableTypeMismatch)));
}
table.Add(filter, data);
this.tables.Add(new FilterTableEntry(priority, table));
}
else
{
table.Add(filter, data);
}
}
else
{
table = CreateFilterTable(filter);
ValidateTable(table);
this.filterTypeMappings.Add(filterType, table.GetType());
FilterTableEntry entry = new FilterTableEntry(priority, table);
int idx = this.tables.IndexOf(entry);
if (idx >= 0)
{
table = this.tables[idx].table;
}
else
{
this.tables.Add(entry);
}
table.Add(filter, data);
}
this.filters.Add(filter, data);
}
public void Add(KeyValuePair<MessageFilter, TFilterData> item)
{
this.Add(item.Key, item.Value);
}
public void Clear()
{
this.filters.Clear();
this.tables.Clear();
}
public bool Contains(KeyValuePair<MessageFilter, TFilterData> item)
{
return ((ICollection<KeyValuePair<MessageFilter, TFilterData>>)this.filters).Contains(item);
}
public bool ContainsKey(MessageFilter filter)
{
return this.filters.ContainsKey(filter);
}
public void CopyTo(KeyValuePair<MessageFilter, TFilterData>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<MessageFilter, TFilterData>>)this.filters).CopyTo(array, arrayIndex);
}
void CreateEmptyTables()
{
this.filterTypeMappings = new Dictionary<Type, Type>();
this.filters = new Dictionary<MessageFilter, TFilterData>();
this.tables = new SortedBuffer<FilterTableEntry, TableEntryComparer>(staticComparerInstance);
}
protected virtual IMessageFilterTable<TFilterData> CreateFilterTable(MessageFilter filter)
{
IMessageFilterTable<TFilterData> ft = filter.CreateFilterTable<TFilterData>();
if (ft == null)
return new SequentialMessageFilterTable<TFilterData>();
return ft;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<KeyValuePair<MessageFilter, TFilterData>> GetEnumerator()
{
return ((ICollection<KeyValuePair<MessageFilter, TFilterData>>)this.filters).GetEnumerator();
}
public int GetPriority(MessageFilter filter)
{
TFilterData d = this.filters[filter];
for (int i = 0; i < this.tables.Count; ++i)
{
if (this.tables[i].table.ContainsKey(filter))
{
return this.tables[i].priority;
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new InvalidOperationException(SR.GetString(SR.FilterTableInvalidForLookup)));
}
public bool GetMatchingValue(Message message, out TFilterData data)
{
bool dataSet = false;
int pri = int.MinValue;
data = default(TFilterData);
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && dataSet)
{
break;
}
pri = this.tables[i].priority;
TFilterData currentData;
if (this.tables[i].table.GetMatchingValue(message, out currentData))
{
if (dataSet)
{
throw TraceUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, null), message);
}
data = currentData;
dataSet = true;
}
}
return dataSet;
}
internal bool GetMatchingValue(Message message, out TFilterData data, out bool addressMatched)
{
bool dataSet = false;
int pri = int.MinValue;
data = default(TFilterData);
addressMatched = false;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && dataSet)
{
break;
}
pri = this.tables[i].priority;
bool matchResult;
TFilterData currentData;
IMessageFilterTable<TFilterData> table = this.tables[i].table;
AndMessageFilterTable<TFilterData> andTable = table as AndMessageFilterTable<TFilterData>;
if (andTable != null)
{
bool addressResult;
matchResult = andTable.GetMatchingValue(message, out currentData, out addressResult);
addressMatched |= addressResult;
}
else
{
matchResult = table.GetMatchingValue(message, out currentData);
}
if (matchResult)
{
if (dataSet)
{
throw TraceUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, null), message);
}
addressMatched = true;
data = currentData;
dataSet = true;
}
}
return dataSet;
}
public bool GetMatchingValue(MessageBuffer buffer, out TFilterData data)
{
return this.GetMatchingValue(buffer, null, out data);
}
// this optimization is only for CorrelationActionMessageFilter and ActionMessageFilter if they override CreateFilterTable to return ActionMessageFilterTable
internal bool GetMatchingValue(MessageBuffer buffer, Message messageToReadHeaders, out TFilterData data)
{
bool dataSet = false;
int pri = int.MinValue;
data = default(TFilterData);
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && dataSet)
{
break;
}
pri = this.tables[i].priority;
TFilterData currentData;
bool result = false;
if (messageToReadHeaders != null && this.tables[i].table is ActionMessageFilterTable<TFilterData>)
{
// this is an action message, in this case we can pass in the message itself since the filter will only read from the header
result = this.tables[i].table.GetMatchingValue(messageToReadHeaders, out currentData);
}
else
{
// this is a custom filter that might read from the message body, pass in the message buffer itself in this case
result = this.tables[i].table.GetMatchingValue(buffer, out currentData);
}
if (result)
{
if (dataSet)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, null));
}
data = currentData;
dataSet = true;
}
}
return dataSet;
}
public bool GetMatchingValues(Message message, ICollection<TFilterData> results)
{
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
int pri = int.MinValue;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && count != results.Count)
{
break;
}
pri = this.tables[i].priority;
this.tables[i].table.GetMatchingValues(message, results);
}
return count != results.Count;
}
public bool GetMatchingValues(MessageBuffer buffer, ICollection<TFilterData> results)
{
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
int pri = int.MinValue;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && count != results.Count)
{
break;
}
pri = this.tables[i].priority;
this.tables[i].table.GetMatchingValues(buffer, results);
}
return count != results.Count;
}
public bool GetMatchingFilter(Message message, out MessageFilter filter)
{
MessageFilter f;
int pri = int.MinValue;
filter = null;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && filter != null)
{
break;
}
pri = this.tables[i].priority;
if (this.tables[i].table.GetMatchingFilter(message, out f))
{
if (filter == null)
{
filter = f;
}
else
{
Collection<MessageFilter> c = new Collection<MessageFilter>();
c.Add(filter);
c.Add(f);
throw TraceUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, c), message);
}
}
}
return filter != null;
}
public bool GetMatchingFilter(MessageBuffer buffer, out MessageFilter filter)
{
MessageFilter f;
int pri = int.MinValue;
filter = null;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && filter != null)
{
break;
}
pri = this.tables[i].priority;
if (this.tables[i].table.GetMatchingFilter(buffer, out f))
{
if (filter == null)
{
filter = f;
}
else
{
Collection<MessageFilter> c = new Collection<MessageFilter>();
c.Add(filter);
c.Add(f);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, c));
}
}
}
return filter != null;
}
public bool GetMatchingFilters(Message message, ICollection<MessageFilter> results)
{
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
int pri = int.MinValue;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && count != results.Count)
{
break;
}
pri = this.tables[i].priority;
this.tables[i].table.GetMatchingFilters(message, results);
}
return count != results.Count;
}
public bool GetMatchingFilters(MessageBuffer buffer, ICollection<MessageFilter> results)
{
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
int pri = int.MinValue;
for (int i = 0; i < this.tables.Count; ++i)
{
// Watch for the end of a bucket
if (pri > this.tables[i].priority && count != results.Count)
{
break;
}
pri = this.tables[i].priority;
this.tables[i].table.GetMatchingFilters(buffer, results);
}
return count != results.Count;
}
public bool Remove(MessageFilter filter)
{
for (int i = 0; i < this.tables.Count; ++i)
{
if (this.tables[i].table.Remove(filter))
{
if (this.tables[i].table.Count == 0)
{
this.tables.RemoveAt(i);
}
return this.filters.Remove(filter);
}
}
return false;
}
public bool Remove(KeyValuePair<MessageFilter, TFilterData> item)
{
if (((ICollection<KeyValuePair<MessageFilter, TFilterData>>)this.filters).Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
public bool TryGetValue(MessageFilter filter, out TFilterData data)
{
return this.filters.TryGetValue(filter, out data);
}
void ValidateTable(IMessageFilterTable<TFilterData> table)
{
Type t = this.GetType();
if (t.IsInstanceOfType(table))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.FilterBadTableType)));
}
}
///////////////////////////////////////////////////
struct FilterTableEntry
{
internal IMessageFilterTable<TFilterData> table;
internal int priority;
internal FilterTableEntry(int pri, IMessageFilterTable<TFilterData> t)
{
this.priority = pri;
this.table = t;
}
}
class TableEntryComparer : IComparer<FilterTableEntry>
{
public TableEntryComparer() { }
public int Compare(FilterTableEntry x, FilterTableEntry y)
{
// Highest priority first
int p = y.priority.CompareTo(x.priority);
if (p != 0)
{
return p;
}
return x.table.GetType().FullName.CompareTo(y.table.GetType().FullName);
}
public bool Equals(FilterTableEntry x, FilterTableEntry y)
{
// Highest priority first
int p = y.priority.CompareTo(x.priority);
if (p != 0)
{
return false;
}
return x.table.GetType().FullName.Equals(y.table.GetType().FullName);
}
public int GetHashCode(FilterTableEntry table)
{
return table.GetHashCode();
}
}
[DataContract]
class Entry
{
[DataMember(IsRequired = true)]
internal MessageFilter filter;
[DataMember(IsRequired = true)]
internal TFilterData data;
[DataMember(IsRequired = true)]
internal int priority;
internal Entry(MessageFilter f, TFilterData d, int p)
{
filter = f;
data = d;
priority = p;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace iskkonekb.kuvera.app.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Razor.Language.Legacy;
namespace Microsoft.AspNetCore.Razor.Language.Syntax
{
internal class SyntaxNodeWriter : SyntaxRewriter
{
private readonly TextWriter _writer;
private bool _visitedRoot;
public SyntaxNodeWriter(TextWriter writer)
{
_writer = writer;
}
public int Depth { get; set; }
public override SyntaxNode Visit(SyntaxNode node)
{
if (node is SyntaxToken token)
{
return VisitToken(token);
}
WriteNode(node);
return node;
}
public override SyntaxNode VisitToken(SyntaxToken token)
{
WriteToken(token);
return base.VisitToken(token);
}
public override SyntaxNode VisitTrivia(SyntaxTrivia trivia)
{
WriteTrivia(trivia);
return base.VisitTrivia(trivia);
}
private void WriteNode(SyntaxNode node)
{
WriteIndent();
Write(node.Kind);
WriteSeparator();
Write($"[{node.Position}..{node.EndPosition})::{node.FullWidth}");
if (node is RazorDirectiveSyntax razorDirective)
{
WriteRazorDirective(razorDirective);
}
else if (node is MarkupTagHelperElementSyntax tagHelperElement)
{
WriteTagHelperElement(tagHelperElement);
}
else if (node is MarkupTagHelperAttributeSyntax tagHelperAttribute)
{
WriteTagHelperAttributeInfo(tagHelperAttribute.TagHelperAttributeInfo);
}
else if (node is MarkupMinimizedTagHelperAttributeSyntax minimizedTagHelperAttribute)
{
WriteTagHelperAttributeInfo(minimizedTagHelperAttribute.TagHelperAttributeInfo);
}
else if (node is MarkupStartTagSyntax startTag)
{
if (startTag.IsMarkupTransition)
{
WriteSeparator();
Write("MarkupTransition");
}
}
else if (node is MarkupEndTagSyntax endTag)
{
if (endTag.IsMarkupTransition)
{
WriteSeparator();
Write("MarkupTransition");
}
}
if (ShouldDisplayNodeContent(node))
{
WriteSeparator();
Write($"[{node.GetContent()}]");
}
var annotation = node.GetAnnotations().FirstOrDefault(a => a.Kind == SyntaxConstants.SpanContextKind);
if (annotation != null && annotation.Data is SpanContext context)
{
WriteSpanContext(context);
}
if (!_visitedRoot)
{
WriteSeparator();
Write($"[{node.ToFullString()}]");
_visitedRoot = true;
}
}
private void WriteRazorDirective(RazorDirectiveSyntax node)
{
if (node.DirectiveDescriptor == null)
{
return;
}
var builder = new StringBuilder("Directive:{");
builder.Append(node.DirectiveDescriptor.Directive);
builder.Append(";");
builder.Append(node.DirectiveDescriptor.Kind);
builder.Append(";");
builder.Append(node.DirectiveDescriptor.Usage);
builder.Append("}");
var diagnostics = node.GetDiagnostics();
if (diagnostics.Length > 0)
{
builder.Append(" [");
var ids = string.Join(", ", diagnostics.Select(diagnostic => $"{diagnostic.Id}{diagnostic.Span}"));
builder.Append(ids);
builder.Append("]");
}
WriteSeparator();
Write(builder.ToString());
}
private void WriteTagHelperElement(MarkupTagHelperElementSyntax node)
{
// Write tag name
WriteSeparator();
Write($"{node.TagHelperInfo.TagName}[{node.TagHelperInfo.TagMode}]");
// Write descriptors
foreach (var descriptor in node.TagHelperInfo.BindingResult.Descriptors)
{
WriteSeparator();
// Get the type name without the namespace.
var typeName = descriptor.Name.Substring(descriptor.Name.LastIndexOf('.') + 1);
Write(typeName);
}
}
private void WriteTagHelperAttributeInfo(TagHelperAttributeInfo info)
{
// Write attributes
WriteSeparator();
Write(info.Name);
WriteSeparator();
Write(info.AttributeStructure);
WriteSeparator();
Write(info.Bound ? "Bound" : "Unbound");
}
private void WriteToken(SyntaxToken token)
{
WriteIndent();
var content = token.IsMissing ? "<Missing>" : token.Content;
var diagnostics = token.GetDiagnostics();
var tokenString = $"{token.Kind};[{content}];{string.Join(", ", diagnostics.Select(diagnostic => diagnostic.Id + diagnostic.Span))}";
Write(tokenString);
}
private void WriteTrivia(SyntaxTrivia trivia)
{
throw new NotImplementedException();
}
private void WriteSpanContext(SpanContext context)
{
WriteSeparator();
Write($"Gen<{context.ChunkGenerator}>");
WriteSeparator();
Write(context.EditHandler);
}
protected void WriteIndent()
{
for (var i = 0; i < Depth; i++)
{
for (var j = 0; j < 4; j++)
{
Write(' ');
}
}
}
protected void WriteSeparator()
{
Write(" - ");
}
protected void WriteNewLine()
{
_writer.WriteLine();
}
protected void Write(object value)
{
if (value is string stringValue)
{
stringValue = stringValue.Replace("\r\n", "LF");
_writer.Write(stringValue);
return;
}
_writer.Write(value);
}
private static bool ShouldDisplayNodeContent(SyntaxNode node)
{
return node.Kind == SyntaxKind.MarkupTextLiteral ||
node.Kind == SyntaxKind.MarkupEphemeralTextLiteral ||
node.Kind == SyntaxKind.MarkupStartTag ||
node.Kind == SyntaxKind.MarkupEndTag ||
node.Kind == SyntaxKind.MarkupTagHelperStartTag ||
node.Kind == SyntaxKind.MarkupTagHelperEndTag ||
node.Kind == SyntaxKind.MarkupAttributeBlock ||
node.Kind == SyntaxKind.MarkupMinimizedAttributeBlock ||
node.Kind == SyntaxKind.MarkupTagHelperAttribute ||
node.Kind == SyntaxKind.MarkupMinimizedTagHelperAttribute ||
node.Kind == SyntaxKind.MarkupLiteralAttributeValue ||
node.Kind == SyntaxKind.MarkupDynamicAttributeValue ||
node.Kind == SyntaxKind.CSharpStatementLiteral ||
node.Kind == SyntaxKind.CSharpExpressionLiteral ||
node.Kind == SyntaxKind.CSharpEphemeralTextLiteral ||
node.Kind == SyntaxKind.UnclassifiedTextLiteral;
}
}
}
| |
using System;
using System.Collections;
using Gtk;
using Gdk;
using Mono.Unix;
namespace Stetic
{
public class PropertyTree: Gtk.ScrolledWindow
{
Gtk.TreeStore store;
InternalTree tree;
TreeViewColumn editorColumn;
Hashtable propertyRows;
Hashtable sensitives, invisibles;
ArrayList expandStatus = new ArrayList ();
public PropertyTree ()
{
propertyRows = new Hashtable ();
sensitives = new Hashtable ();
invisibles = new Hashtable ();
store = new TreeStore (typeof (string), typeof(object), typeof(bool), typeof(object));
tree = new InternalTree (this, store);
CellRendererText crt;
TreeViewColumn col;
col = new TreeViewColumn ();
col.Title = Catalog.GetString ("Property");
crt = new CellRendererPropertyGroup (tree);
col.PackStart (crt, true);
col.SetCellDataFunc (crt, new TreeCellDataFunc (GroupData));
col.Resizable = true;
col.Expand = false;
col.Sizing = TreeViewColumnSizing.Fixed;
col.FixedWidth = 150;
tree.AppendColumn (col);
editorColumn = new TreeViewColumn ();
editorColumn.Title = Catalog.GetString ("Value");
CellRendererProperty crp = new CellRendererProperty (tree);
editorColumn.PackStart (crp, true);
editorColumn.SetCellDataFunc (crp, new TreeCellDataFunc (PropertyData));
editorColumn.Sizing = TreeViewColumnSizing.Fixed;
editorColumn.Resizable = false;
editorColumn.Expand = true;
tree.AppendColumn (editorColumn);
tree.HeadersVisible = false;
this.ShadowType = Gtk.ShadowType.In;
this.HscrollbarPolicy = Gtk.PolicyType.Never;
Add (tree);
ShowAll ();
tree.Selection.Changed += OnSelectionChanged;
}
public void AddProperties (ItemGroupCollection itemGroups, object instance, string targetGtkVersion)
{
foreach (ItemGroup igroup in itemGroups)
AddGroup (igroup, instance, targetGtkVersion);
}
public void SaveStatus ()
{
expandStatus.Clear ();
TreeIter iter;
if (!tree.Model.GetIterFirst (out iter))
return;
do {
if (tree.GetRowExpanded (tree.Model.GetPath (iter))) {
expandStatus.Add (tree.Model.GetValue (iter, 0));
}
} while (tree.Model.IterNext (ref iter));
}
public void RestoreStatus ()
{
TreeIter iter;
if (!tree.Model.GetIterFirst (out iter))
return;
// If the tree only has one group, show it always expanded
TreeIter iter2 = iter;
if (!tree.Model.IterNext (ref iter2)) {
tree.ExpandRow (tree.Model.GetPath (iter), true);
return;
}
do {
object grp = tree.Model.GetValue (iter, 0);
if (expandStatus.Contains (grp))
tree.ExpandRow (tree.Model.GetPath (iter), true);
} while (tree.Model.IterNext (ref iter));
}
public virtual void Clear ()
{
store.Clear ();
propertyRows.Clear ();
sensitives.Clear ();
invisibles.Clear ();
}
public virtual void Update ()
{
// Just repaint the cells
QueueDraw ();
}
public void AddGroup (ItemGroup igroup, object instance, string targetGtkVersion)
{
ArrayList props = new ArrayList ();
foreach (ItemDescriptor item in igroup) {
if (item.IsInternal)
continue;
if (item is PropertyDescriptor && item.SupportsGtkVersion (targetGtkVersion))
props.Add (item);
}
if (props.Count == 0)
return;
InstanceData idata = new InstanceData (instance);
TreeIter iter = store.AppendValues (igroup.Label, null, true, idata);
foreach (PropertyDescriptor item in props)
AppendProperty (iter, (PropertyDescriptor)item, idata);
}
protected void AppendProperty (PropertyDescriptor prop, object instance)
{
AppendProperty (TreeIter.Zero, prop, new InstanceData (instance));
}
protected void AppendProperty (TreeIter piter, PropertyDescriptor prop, object instance)
{
AppendProperty (piter, prop, new InstanceData (instance));
}
void AppendProperty (TreeIter piter, PropertyDescriptor prop, InstanceData idata)
{
TreeIter iter;
if (piter.Equals (TreeIter.Zero))
iter = store.AppendValues (prop.Label, prop, false, idata);
else
iter = store.AppendValues (piter, prop.Label, prop, false, idata);
if (prop.HasDependencies)
sensitives[prop] = prop;
if (prop.HasVisibility)
invisibles[prop] = prop;
propertyRows [prop] = store.GetStringFromIter (iter);
}
protected virtual void OnObjectChanged ()
{
}
void OnSelectionChanged (object s, EventArgs a)
{
TreePath[] rows = tree.Selection.GetSelectedRows ();
if (!tree.dragging && rows != null && rows.Length > 0) {
tree.SetCursor (rows[0], editorColumn, true);
}
}
internal void NotifyChanged ()
{
OnObjectChanged ();
}
void PropertyData (Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
{
CellRendererProperty rc = (CellRendererProperty) cell;
bool group = (bool) model.GetValue (iter, 2);
if (group) {
rc.SetData (null, null, null);
} else {
PropertyDescriptor prop = (PropertyDescriptor) model.GetValue (iter, 1);
PropertyEditorCell propCell = PropertyEditorCell.GetPropertyCell (prop);
InstanceData idata = (InstanceData) model.GetValue (iter, 3);
propCell.Initialize (tree, prop, idata.Instance);
rc.SetData (idata.Instance, prop, propCell);
}
}
void GroupData (Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
{
CellRendererPropertyGroup rc = (CellRendererPropertyGroup) cell;
rc.IsGroup = (bool) model.GetValue (iter, 2);
rc.Text = (string) model.GetValue (iter, 0);
PropertyDescriptor prop = (PropertyDescriptor) model.GetValue (iter, 1);
if (prop != null) {
InstanceData idata = (InstanceData) model.GetValue (iter, 3);
rc.SensitiveProperty = prop.EnabledFor (idata.Instance) && prop.VisibleFor (idata.Instance);
} else
rc.SensitiveProperty = true;
}
}
class InternalTree: TreeView
{
internal ArrayList Groups = new ArrayList ();
Pango.Layout layout;
bool editing;
PropertyTree tree;
internal bool dragging;
int dragPos;
Gdk.Cursor resizeCursor = new Gdk.Cursor (CursorType.SbHDoubleArrow);
public InternalTree (PropertyTree tree, TreeModel model): base (model)
{
this.tree = tree;
layout = new Pango.Layout (this.PangoContext);
layout.Wrap = Pango.WrapMode.Char;
Pango.FontDescription des = this.Style.FontDescription.Copy();
layout.FontDescription = des;
}
public bool Editing {
get { return editing; }
set { editing = value; Update (); tree.NotifyChanged (); }
}
protected override bool OnExposeEvent (Gdk.EventExpose e)
{
Groups.Clear ();
bool res = base.OnExposeEvent (e);
foreach (TreeGroup grp in Groups) {
layout.SetMarkup ("<b>" + GLib.Markup.EscapeText (grp.Group) + "</b>");
e.Window.DrawLayout (this.Style.TextGC (grp.State), grp.X, grp.Y, layout);
}
return res;
}
protected override bool OnMotionNotifyEvent (EventMotion evnt)
{
if (dragging) {
int nw = (int)(evnt.X) + dragPos;
if (nw <= 40) nw = 40;
GLib.Idle.Add (delegate {
Columns[0].FixedWidth = nw;
return false;
});
} else {
int w = Columns[0].Width;
if (Math.Abs (w - evnt.X) < 5)
this.GdkWindow.Cursor = resizeCursor;
else
this.GdkWindow.Cursor = null;
}
return base.OnMotionNotifyEvent (evnt);
}
protected override bool OnButtonPressEvent (EventButton evnt)
{
int w = Columns[0].Width;
if (Math.Abs (w - evnt.X) < 5) {
TreePath[] rows = Selection.GetSelectedRows ();
if (rows != null && rows.Length > 0)
SetCursor (rows[0], Columns[0], false);
dragging = true;
dragPos = w - (int) evnt.X;
this.GdkWindow.Cursor = resizeCursor;
}
return base.OnButtonPressEvent (evnt);
}
protected override bool OnButtonReleaseEvent (EventButton evnt)
{
if (dragging) {
this.GdkWindow.Cursor = null;
dragging = false;
}
return base.OnButtonReleaseEvent (evnt);
}
public virtual void Update ()
{
}
}
class TreeGroup
{
public string Group;
public int X;
public int Y;
public StateType State;
}
class CellRendererProperty: CellRenderer
{
PropertyDescriptor property;
object instance;
int rowHeight;
PropertyEditorCell editorCell;
bool sensitive;
bool visible;
TreeView tree;
public CellRendererProperty (TreeView tree)
{
this.tree = tree;
Xalign = 0;
Xpad = 3;
Mode |= Gtk.CellRendererMode.Editable;
Entry dummyEntry = new Gtk.Entry ();
dummyEntry.HasFrame = false;
rowHeight = dummyEntry.SizeRequest ().Height;
}
public void SetData (object instance, PropertyDescriptor property, PropertyEditorCell editor)
{
this.instance = instance;
this.property = property;
if (property == null)
this.CellBackgroundGdk = tree.Style.MidColors [(int)Gtk.StateType.Normal];
else
this.CellBackground = null;
visible = property != null ? property.VisibleFor (instance): true;
sensitive = property != null ? property.EnabledFor (instance) && property.VisibleFor (instance): true;
editorCell = editor;
}
public override void GetSize (Widget widget, ref Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height)
{
if (editorCell != null)
editorCell.GetSize ((int)(cell_area.Width - this.Xpad * 2), out width, out height);
else {
width = height = 0;
}
width += (int) this.Xpad * 2;
height += (int) this.Ypad * 2;
x_offset = 0;
y_offset = 0;
if (height < rowHeight)
height = rowHeight;
}
protected override void Render (Drawable window, Widget widget, Rectangle background_area, Rectangle cell_area, Rectangle expose_area, CellRendererState flags)
{
if (instance == null || !visible)
return;
int width = 0, height = 0;
int iwidth = cell_area.Width - (int) this.Xpad * 2;
if (editorCell != null)
editorCell.GetSize ((int)(cell_area.Width - this.Xpad * 2), out width, out height);
Rectangle bounds = new Rectangle ();
bounds.Width = width > iwidth ? iwidth : width;
bounds.Height = height;
bounds.X = (int) (cell_area.X + this.Xpad);
bounds.Y = cell_area.Y + (cell_area.Height - height) / 2;
StateType state = GetState (flags);
if (editorCell != null)
editorCell.Render (window, bounds, state);
}
public override CellEditable StartEditing (Gdk.Event ev, Widget widget, string path, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags)
{
if (property == null || editorCell == null || !sensitive)
return null;
StateType state = GetState (flags);
EditSession session = editorCell.StartEditing (cell_area, state);
if (session == null)
return null;
Gtk.Widget propEditor = (Gtk.Widget) session.Editor;
propEditor.Show ();
HackEntry e = new HackEntry (propEditor, session);
e.Show ();
return e;
}
StateType GetState (CellRendererState flags)
{
if (!sensitive)
return StateType.Insensitive;
else if ((flags & CellRendererState.Selected) != 0)
return StateType.Selected;
else
return StateType.Normal;
}
}
class CellRendererPropertyGroup: CellRendererText
{
TreeView tree;
Pango.Layout layout;
bool isGroup;
bool sensitive;
public bool IsGroup {
get { return isGroup; }
set {
isGroup = value;
if (value)
this.CellBackgroundGdk = tree.Style.MidColors [(int)Gtk.StateType.Normal];
else
this.CellBackground = null;
}
}
public bool SensitiveProperty {
get { return sensitive; }
set { sensitive = value; }
}
public CellRendererPropertyGroup (TreeView tree)
{
this.tree = tree;
layout = new Pango.Layout (tree.PangoContext);
layout.Wrap = Pango.WrapMode.Char;
Pango.FontDescription des = tree.Style.FontDescription.Copy();
layout.FontDescription = des;
}
protected void GetCellSize (Widget widget, int availableWidth, out int width, out int height)
{
layout.SetMarkup (Text);
layout.Width = -1;
layout.GetPixelSize (out width, out height);
}
public override void GetSize (Widget widget, ref Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height)
{
GetCellSize (widget, (int)(cell_area.Width - this.Xpad * 2), out width, out height);
width += (int) this.Xpad * 2;
height += (int) this.Ypad * 2;
x_offset = y_offset = 0;
if (IsGroup)
width = 0;
}
protected override void Render (Drawable window, Widget widget, Rectangle background_area, Rectangle cell_area, Rectangle expose_area, CellRendererState flags)
{
int width, height;
GetCellSize (widget, (int)(cell_area.Width - this.Xpad * 2), out width, out height);
int x = (int) (cell_area.X + this.Xpad);
int y = cell_area.Y + (cell_area.Height - height) / 2;
StateType state;
if (!sensitive)
state = StateType.Insensitive;
else if ((flags & CellRendererState.Selected) != 0)
state = StateType.Selected;
else
state = StateType.Normal;
if (IsGroup) {
TreeGroup grp = new TreeGroup ();
grp.X = x;
grp.Y = y;
grp.Group = Text;
grp.State = state;
InternalTree tree = (InternalTree) widget;
tree.Groups.Add (grp);
} else {
window.DrawLayout (widget.Style.TextGC (state), x, y, layout);
int bx = background_area.X + background_area.Width - 1;
Gdk.GC gc = new Gdk.GC (window);
gc.RgbFgColor = tree.Style.MidColors [(int)Gtk.StateType.Normal];
window.DrawLine (gc, bx, background_area.Y, bx, background_area.Y + background_area.Height);
}
}
}
class HackEntry: Entry
{
EventBox box;
EditSession session;
public HackEntry (Gtk.Widget child, EditSession session)
{
this.session = session;
box = new EventBox ();
box.ButtonPressEvent += new ButtonPressEventHandler (OnClickBox);
box.ModifyBg (StateType.Normal, Style.White);
box.Add (child);
}
[GLib.ConnectBefore]
void OnClickBox (object s, ButtonPressEventArgs args)
{
// Avoid forwarding the button press event to the
// tree, since it would hide the cell editor.
args.RetVal = true;
}
protected override void OnParentSet (Gtk.Widget parent)
{
base.OnParentSet (parent);
if (Parent != null) {
if (this.ParentWindow != null)
box.ParentWindow = this.ParentWindow;
box.Parent = Parent;
box.Show ();
((InternalTree)Parent).Editing = true;
}
else {
session.Dispose ();
((InternalTree)parent).Editing = false;
box.Unparent ();
}
}
protected override void OnShown ()
{
// Do nothing.
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
box.SizeRequest ();
box.Allocation = allocation;
}
}
class InstanceData
{
public InstanceData (object instance)
{
Instance = instance;
}
public object Instance;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System.Collections;
using System.Text;
using System.Diagnostics;
internal class NamespaceList
{
public enum ListType
{
Any,
Other,
Set
};
private ListType _type = ListType.Any;
private Hashtable _set = null;
private string _targetNamespace;
public NamespaceList()
{
}
public NamespaceList(string namespaces, string targetNamespace)
{
Debug.Assert(targetNamespace != null);
_targetNamespace = targetNamespace;
namespaces = namespaces.Trim();
if (namespaces == "##any" || namespaces.Length == 0)
{
_type = ListType.Any;
}
else if (namespaces == "##other")
{
_type = ListType.Other;
}
else
{
_type = ListType.Set;
_set = new Hashtable();
string[] splitString = XmlConvert.SplitString(namespaces);
for (int i = 0; i < splitString.Length; ++i)
{
if (splitString[i] == "##local")
{
_set[string.Empty] = string.Empty;
}
else if (splitString[i] == "##targetNamespace")
{
_set[targetNamespace] = targetNamespace;
}
else
{
XmlConvert.ToUri(splitString[i]); // can throw
_set[splitString[i]] = splitString[i];
}
}
}
}
public NamespaceList Clone()
{
NamespaceList nsl = (NamespaceList)MemberwiseClone();
if (_type == ListType.Set)
{
Debug.Assert(_set != null);
nsl._set = (Hashtable)(_set.Clone());
}
return nsl;
}
public ListType Type
{
get { return _type; }
}
public string Excluded
{
get { return _targetNamespace; }
}
public ICollection Enumerate
{
get
{
switch (_type)
{
case ListType.Set:
return _set.Keys;
case ListType.Other:
case ListType.Any:
default:
throw new InvalidOperationException();
}
}
}
public virtual bool Allows(string ns)
{
switch (_type)
{
case ListType.Any:
return true;
case ListType.Other:
return ns != _targetNamespace && ns.Length != 0;
case ListType.Set:
return _set[ns] != null;
}
Debug.Assert(false);
return false;
}
public bool Allows(XmlQualifiedName qname)
{
return Allows(qname.Namespace);
}
public override string ToString()
{
switch (_type)
{
case ListType.Any:
return "##any";
case ListType.Other:
return "##other";
case ListType.Set:
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (string s in _set.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(" ");
}
if (s == _targetNamespace)
{
sb.Append("##targetNamespace");
}
else if (s.Length == 0)
{
sb.Append("##local");
}
else
{
sb.Append(s);
}
}
return sb.ToString();
}
Debug.Assert(false);
return string.Empty;
}
public static bool IsSubset(NamespaceList sub, NamespaceList super)
{
if (super._type == ListType.Any)
{
return true;
}
else if (sub._type == ListType.Other && super._type == ListType.Other)
{
return super._targetNamespace == sub._targetNamespace;
}
else if (sub._type == ListType.Set)
{
if (super._type == ListType.Other)
{
return !sub._set.Contains(super._targetNamespace);
}
else
{
Debug.Assert(super._type == ListType.Set);
foreach (string ns in sub._set.Keys)
{
if (!super._set.Contains(ns))
{
return false;
}
}
return true;
}
}
return false;
}
public static NamespaceList Union(NamespaceList o1, NamespaceList o2, bool v1Compat)
{
NamespaceList nslist = null;
Debug.Assert(o1 != o2);
if (o1._type == ListType.Any)
{ //clause 2 - o1 is Any
nslist = new NamespaceList();
}
else if (o2._type == ListType.Any)
{ //clause 2 - o2 is Any
nslist = new NamespaceList();
}
else if (o1._type == ListType.Set && o2._type == ListType.Set)
{ //clause 3 , both are sets
nslist = o1.Clone();
foreach (string ns in o2._set.Keys)
{
nslist._set[ns] = ns;
}
}
else if (o1._type == ListType.Other && o2._type == ListType.Other)
{ //clause 4, both are negations
if (o1._targetNamespace == o2._targetNamespace)
{ //negation of same value
nslist = o1.Clone();
}
else
{ //Not a breaking change, going from not expressible to not(absent)
nslist = new NamespaceList("##other", string.Empty); //clause 4, negations of different values, result is not(absent)
}
}
else if (o1._type == ListType.Set && o2._type == ListType.Other)
{
if (v1Compat)
{
if (o1._set.Contains(o2._targetNamespace))
{
nslist = new NamespaceList();
}
else
{ //This was not there originally in V1, added for consistency since its not breaking
nslist = o2.Clone();
}
}
else
{
if (o2._targetNamespace != string.Empty)
{ //clause 5, o1 is set S, o2 is not(tns)
nslist = o1.CompareSetToOther(o2);
}
else if (o1._set.Contains(string.Empty))
{ //clause 6.1 - set S includes absent, o2 is not(absent)
nslist = new NamespaceList();
}
else
{ //clause 6.2 - set S does not include absent, result is not(absent)
nslist = new NamespaceList("##other", string.Empty);
}
}
}
else if (o2._type == ListType.Set && o1._type == ListType.Other)
{
if (v1Compat)
{
if (o2._set.Contains(o2._targetNamespace))
{
nslist = new NamespaceList();
}
else
{
nslist = o1.Clone();
}
}
else
{ //New rules
if (o1._targetNamespace != string.Empty)
{ //clause 5, o1 is set S, o2 is not(tns)
nslist = o2.CompareSetToOther(o1);
}
else if (o2._set.Contains(string.Empty))
{ //clause 6.1 - set S includes absent, o2 is not(absent)
nslist = new NamespaceList();
}
else
{ //clause 6.2 - set S does not include absent, result is not(absent)
nslist = new NamespaceList("##other", string.Empty);
}
}
}
return nslist;
}
private NamespaceList CompareSetToOther(NamespaceList other)
{
//clause 5.1
NamespaceList nslist = null;
if (_set.Contains(other._targetNamespace))
{ //S contains negated ns
if (_set.Contains(string.Empty))
{ // AND S contains absent
nslist = new NamespaceList(); //any is the result
}
else
{ //clause 5.2
nslist = new NamespaceList("##other", string.Empty);
}
}
else if (_set.Contains(string.Empty))
{ //clause 5.3 - Not expressible
nslist = null;
}
else
{ //clause 5.4 - Set S does not contain negated ns or absent
nslist = other.Clone();
}
return nslist;
}
public static NamespaceList Intersection(NamespaceList o1, NamespaceList o2, bool v1Compat)
{
NamespaceList nslist = null;
Debug.Assert(o1 != o2); //clause 1
if (o1._type == ListType.Any)
{ //clause 2 - o1 is any
nslist = o2.Clone();
}
else if (o2._type == ListType.Any)
{ //clause 2 - o2 is any
nslist = o1.Clone();
}
else if (o1._type == ListType.Set && o2._type == ListType.Other)
{ //Clause 3 o2 is other
nslist = o1.Clone();
nslist.RemoveNamespace(o2._targetNamespace);
if (!v1Compat)
{
nslist.RemoveNamespace(string.Empty); //remove ##local
}
}
else if (o1._type == ListType.Other && o2._type == ListType.Set)
{ //Clause 3 o1 is other
nslist = o2.Clone();
nslist.RemoveNamespace(o1._targetNamespace);
if (!v1Compat)
{
nslist.RemoveNamespace(string.Empty); //remove ##local
}
}
else if (o1._type == ListType.Set && o2._type == ListType.Set)
{ //clause 4
nslist = o1.Clone();
nslist = new NamespaceList();
nslist._type = ListType.Set;
nslist._set = new Hashtable();
foreach (string ns in o1._set.Keys)
{
if (o2._set.Contains(ns))
{
nslist._set.Add(ns, ns);
}
}
}
else if (o1._type == ListType.Other && o2._type == ListType.Other)
{
if (o1._targetNamespace == o2._targetNamespace)
{ //negation of same namespace name
nslist = o1.Clone();
return nslist;
}
if (!v1Compat)
{
if (o1._targetNamespace == string.Empty)
{ // clause 6 - o1 is negation of absent
nslist = o2.Clone();
}
else if (o2._targetNamespace == string.Empty)
{ //clause 6 - o1 is negation of absent
nslist = o1.Clone();
}
}
//if it comes here, its not expressible //clause 5
}
return nslist;
}
private void RemoveNamespace(string tns)
{
if (_set[tns] != null)
{
_set.Remove(tns);
}
}
};
internal class NamespaceListV1Compat : NamespaceList
{
public NamespaceListV1Compat(string namespaces, string targetNamespace) : base(namespaces, targetNamespace) { }
public override bool Allows(string ns)
{
if (this.Type == ListType.Other)
{
return ns != Excluded;
}
else
{
return base.Allows(ns);
}
}
}
}
| |
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Globalization;
/// <summary>
/// This class implements SQLiteBase completely, and is the guts of the code that interop's SQLite with .NET
/// </summary>
internal class SQLite3 : SQLiteBase
{
/// <summary>
/// The opaque pointer returned to us by the sqlite provider
/// </summary>
protected SqliteConnectionHandle _sql;
protected string _fileName;
protected bool _usePool;
protected int _poolVersion = 0;
#if !PLATFORM_COMPACTFRAMEWORK
private bool _buildingSchema = false;
#endif
#if MONOTOUCH
GCHandle gch;
#endif
/// <summary>
/// The user-defined functions registered on this connection
/// </summary>
protected SqliteFunction[] _functionsArray;
internal SQLite3(SQLiteDateFormats fmt)
: base(fmt)
{
#if MONOTOUCH
gch = GCHandle.Alloc (this);
#endif
}
protected override void Dispose(bool bDisposing)
{
if (bDisposing)
Close();
}
// It isn't necessary to cleanup any functions we've registered. If the connection
// goes to the pool and is resurrected later, re-registered functions will overwrite the
// previous functions. The SqliteFunctionCookieHandle will take care of freeing unmanaged
// resources belonging to the previously-registered functions.
internal override void Close()
{
if (_sql != null)
{
if (_usePool)
{
SQLiteBase.ResetConnection(_sql);
SqliteConnectionPool.Add(_fileName, _sql, _poolVersion);
}
else
_sql.Dispose();
}
_sql = null;
#if MONOTOUCH
if (gch.IsAllocated)
gch.Free ();
#endif
}
internal override void Cancel()
{
UnsafeNativeMethods.sqlite3_interrupt(_sql);
}
internal override string Version
{
get
{
return SQLite3.SQLiteVersion;
}
}
internal static string SQLiteVersion
{
get
{
return UTF8ToString(UnsafeNativeMethods.sqlite3_libversion(), -1);
}
}
internal override int Changes
{
get
{
return UnsafeNativeMethods.sqlite3_changes(_sql);
}
}
internal override void Open(string strFilename, SQLiteOpenFlagsEnum flags, int maxPoolSize, bool usePool)
{
if (_sql != null) return;
_usePool = usePool;
if (usePool)
{
_fileName = strFilename;
_sql = SqliteConnectionPool.Remove(strFilename, maxPoolSize, out _poolVersion);
}
if (_sql == null)
{
IntPtr db;
#if !SQLITE_STANDARD
int n = UnsafeNativeMethods.sqlite3_open_interop(ToUTF8(strFilename), (int)flags, out db);
#else
// Compatibility with versions < 3.5.0
int n;
try {
n = UnsafeNativeMethods.sqlite3_open_v2(ToUTF8(strFilename), out db, (int)flags, IntPtr.Zero);
} catch (EntryPointNotFoundException) {
Console.WriteLine ("Your sqlite3 version is old - please upgrade to at least v3.5.0!");
n = UnsafeNativeMethods.sqlite3_open (ToUTF8 (strFilename), out db);
}
#endif
if (n > 0) throw new SqliteException(n, null);
_sql = db;
}
// Bind functions to this connection. If any previous functions of the same name
// were already bound, then the new bindings replace the old.
_functionsArray = SqliteFunction.BindFunctions(this);
SetTimeout(0);
}
internal override void ClearPool()
{
SqliteConnectionPool.ClearPool(_fileName);
}
internal override void SetTimeout(int nTimeoutMS)
{
int n = UnsafeNativeMethods.sqlite3_busy_timeout(_sql, nTimeoutMS);
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override bool Step(SqliteStatement stmt)
{
int n;
Random rnd = null;
uint starttick = (uint)Environment.TickCount;
uint timeout = (uint)(stmt._command._commandTimeout * 1000);
while (true)
{
n = UnsafeNativeMethods.sqlite3_step(stmt._sqlite_stmt);
if (n == 100) return true;
if (n == 101) return false;
if (n > 0)
{
int r;
// An error occurred, attempt to reset the statement. If the reset worked because the
// schema has changed, re-try the step again. If it errored our because the database
// is locked, then keep retrying until the command timeout occurs.
r = Reset(stmt);
if (r == 0)
throw new SqliteException(n, SQLiteLastError());
else if ((r == 6 || r == 5) && stmt._command != null) // SQLITE_LOCKED || SQLITE_BUSY
{
// Keep trying
if (rnd == null) // First time we've encountered the lock
rnd = new Random();
// If we've exceeded the command's timeout, give up and throw an error
if ((uint)Environment.TickCount - starttick > timeout)
{
throw new SqliteException(r, SQLiteLastError());
}
else
{
// Otherwise sleep for a random amount of time up to 150ms
System.Threading.Thread.CurrentThread.Join(rnd.Next(1, 150));
}
}
}
}
}
internal override int Reset(SqliteStatement stmt)
{
int n;
#if !SQLITE_STANDARD
n = UnsafeNativeMethods.sqlite3_reset_interop(stmt._sqlite_stmt);
#else
n = UnsafeNativeMethods.sqlite3_reset(stmt._sqlite_stmt);
#endif
// If the schema changed, try and re-prepare it
if (n == 17) // SQLITE_SCHEMA
{
// Recreate a dummy statement
string str;
using (SqliteStatement tmp = Prepare(null, stmt._sqlStatement, null, (uint)(stmt._command._commandTimeout * 1000), out str))
{
// Finalize the existing statement
stmt._sqlite_stmt.Dispose();
// Reassign a new statement pointer to the old statement and clear the temporary one
stmt._sqlite_stmt = tmp._sqlite_stmt;
tmp._sqlite_stmt = null;
// Reapply parameters
stmt.BindParameters();
}
return -1; // Reset was OK, with schema change
}
else if (n == 6 || n == 5) // SQLITE_LOCKED || SQLITE_BUSY
return n;
if (n > 0)
throw new SqliteException(n, SQLiteLastError());
return 0; // We reset OK, no schema changes
}
internal override string SQLiteLastError()
{
return SQLiteBase.SQLiteLastError(_sql);
}
internal override SqliteStatement Prepare(SqliteConnection cnn, string strSql, SqliteStatement previous, uint timeoutMS, out string strRemain)
{
IntPtr stmt = IntPtr.Zero;
IntPtr ptr = IntPtr.Zero;
int len = 0;
int n = 17;
int retries = 0;
byte[] b = ToUTF8(strSql);
string typedefs = null;
SqliteStatement cmd = null;
Random rnd = null;
uint starttick = (uint)Environment.TickCount;
GCHandle handle = GCHandle.Alloc(b, GCHandleType.Pinned);
IntPtr psql = handle.AddrOfPinnedObject();
try
{
while ((n == 17 || n == 6 || n == 5) && retries < 3)
{
#if !SQLITE_STANDARD
n = UnsafeNativeMethods.sqlite3_prepare_interop(_sql, psql, b.Length - 1, out stmt, out ptr, out len);
#else
n = UnsafeNativeMethods.sqlite3_prepare(_sql, psql, b.Length - 1, out stmt, out ptr);
len = -1;
#endif
if (n == 17)
retries++;
else if (n == 1)
{
if (String.Compare(SQLiteLastError(), "near \"TYPES\": syntax error", StringComparison.OrdinalIgnoreCase) == 0)
{
int pos = strSql.IndexOf(';');
if (pos == -1) pos = strSql.Length - 1;
typedefs = strSql.Substring(0, pos + 1);
strSql = strSql.Substring(pos + 1);
strRemain = "";
while (cmd == null && strSql.Length > 0)
{
cmd = Prepare(cnn, strSql, previous, timeoutMS, out strRemain);
strSql = strRemain;
}
if (cmd != null)
cmd.SetTypes(typedefs);
return cmd;
}
#if PLATFORM_COMPACTFRAMEWORK
else if (_buildingSchema == false && String.Compare(SQLiteLastError(), 0, "no such table: TEMP.SCHEMA", 0, 26, StringComparison.OrdinalIgnoreCase) == 0)
{
strRemain = "";
_buildingSchema = true;
try
{
ISQLiteSchemaExtensions ext = ((IServiceProvider)SqliteFactory.Instance).GetService(typeof(ISQLiteSchemaExtensions)) as ISQLiteSchemaExtensions;
if (ext != null)
ext.BuildTempSchema(cnn);
while (cmd == null && strSql.Length > 0)
{
cmd = Prepare(cnn, strSql, previous, timeoutMS, out strRemain);
strSql = strRemain;
}
return cmd;
}
finally
{
_buildingSchema = false;
}
}
#endif
}
else if (n == 6 || n == 5) // Locked -- delay a small amount before retrying
{
// Keep trying
if (rnd == null) // First time we've encountered the lock
rnd = new Random();
// If we've exceeded the command's timeout, give up and throw an error
if ((uint)Environment.TickCount - starttick > timeoutMS)
{
throw new SqliteException(n, SQLiteLastError());
}
else
{
// Otherwise sleep for a random amount of time up to 150ms
System.Threading.Thread.CurrentThread.Join(rnd.Next(1, 150));
}
}
}
if (n > 0) throw new SqliteException(n, SQLiteLastError());
strRemain = UTF8ToString(ptr, len);
if (stmt != IntPtr.Zero) cmd = new SqliteStatement(this, stmt, strSql.Substring(0, strSql.Length - strRemain.Length), previous);
return cmd;
}
finally
{
handle.Free();
}
}
internal override void Bind_Double(SqliteStatement stmt, int index, double value)
{
#if !PLATFORM_COMPACTFRAMEWORK
int n = UnsafeNativeMethods.sqlite3_bind_double(stmt._sqlite_stmt, index, value);
#else
int n = UnsafeNativeMethods.sqlite3_bind_double_interop(stmt._sqlite_stmt, index, ref value);
#endif
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void Bind_Int32(SqliteStatement stmt, int index, int value)
{
int n = UnsafeNativeMethods.sqlite3_bind_int(stmt._sqlite_stmt, index, value);
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void Bind_Int64(SqliteStatement stmt, int index, long value)
{
#if !PLATFORM_COMPACTFRAMEWORK
int n = UnsafeNativeMethods.sqlite3_bind_int64(stmt._sqlite_stmt, index, value);
#else
int n = UnsafeNativeMethods.sqlite3_bind_int64_interop(stmt._sqlite_stmt, index, ref value);
#endif
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void Bind_Text(SqliteStatement stmt, int index, string value)
{
byte[] b = ToUTF8(value);
int n = UnsafeNativeMethods.sqlite3_bind_text(stmt._sqlite_stmt, index, b, b.Length - 1, (IntPtr)(-1));
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void Bind_DateTime(SqliteStatement stmt, int index, DateTime dt)
{
byte[] b = ToUTF8(dt);
int n = UnsafeNativeMethods.sqlite3_bind_text(stmt._sqlite_stmt, index, b, b.Length - 1, (IntPtr)(-1));
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void Bind_Blob(SqliteStatement stmt, int index, byte[] blobData)
{
int n = UnsafeNativeMethods.sqlite3_bind_blob(stmt._sqlite_stmt, index, blobData, blobData.Length, (IntPtr)(-1));
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void Bind_Null(SqliteStatement stmt, int index)
{
int n = UnsafeNativeMethods.sqlite3_bind_null(stmt._sqlite_stmt, index);
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override int Bind_ParamCount(SqliteStatement stmt)
{
return UnsafeNativeMethods.sqlite3_bind_parameter_count(stmt._sqlite_stmt);
}
internal override string Bind_ParamName(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_bind_parameter_name_interop(stmt._sqlite_stmt, index, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_bind_parameter_name(stmt._sqlite_stmt, index), -1);
#endif
}
internal override int Bind_ParamIndex(SqliteStatement stmt, string paramName)
{
return UnsafeNativeMethods.sqlite3_bind_parameter_index(stmt._sqlite_stmt, ToUTF8(paramName));
}
internal override int ColumnCount(SqliteStatement stmt)
{
return UnsafeNativeMethods.sqlite3_column_count(stmt._sqlite_stmt);
}
internal override string ColumnName(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_name_interop(stmt._sqlite_stmt, index, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_name(stmt._sqlite_stmt, index), -1);
#endif
}
internal override TypeAffinity ColumnAffinity(SqliteStatement stmt, int index)
{
return UnsafeNativeMethods.sqlite3_column_type(stmt._sqlite_stmt, index);
}
internal override string ColumnType(SqliteStatement stmt, int index, out TypeAffinity nAffinity)
{
int len;
#if !SQLITE_STANDARD
IntPtr p = UnsafeNativeMethods.sqlite3_column_decltype_interop(stmt._sqlite_stmt, index, out len);
#else
len = -1;
IntPtr p = UnsafeNativeMethods.sqlite3_column_decltype(stmt._sqlite_stmt, index);
#endif
nAffinity = ColumnAffinity(stmt, index);
if (p != IntPtr.Zero) return UTF8ToString(p, len);
else
{
string[] ar = stmt.TypeDefinitions;
if (ar != null)
{
if (index < ar.Length && ar[index] != null)
return ar[index];
}
return String.Empty;
//switch (nAffinity)
//{
// case TypeAffinity.Int64:
// return "BIGINT";
// case TypeAffinity.Double:
// return "DOUBLE";
// case TypeAffinity.Blob:
// return "BLOB";
// default:
// return "TEXT";
//}
}
}
internal override int ColumnIndex(SqliteStatement stmt, string columnName)
{
int x = ColumnCount(stmt);
for (int n = 0; n < x; n++)
{
if (String.Compare(columnName, ColumnName(stmt, n), true, CultureInfo.InvariantCulture) == 0)
return n;
}
return -1;
}
internal override string ColumnOriginalName(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_origin_name_interop(stmt._sqlite_stmt, index, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_origin_name(stmt._sqlite_stmt, index), -1);
#endif
}
internal override string ColumnDatabaseName(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_database_name_interop(stmt._sqlite_stmt, index, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_database_name(stmt._sqlite_stmt, index), -1);
#endif
}
internal override string ColumnTableName(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_table_name_interop(stmt._sqlite_stmt, index, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_table_name(stmt._sqlite_stmt, index), -1);
#endif
}
internal override void ColumnMetaData(string dataBase, string table, string column, out string dataType, out string collateSequence, out bool notNull, out bool primaryKey, out bool autoIncrement)
{
IntPtr dataTypePtr;
IntPtr collSeqPtr;
int nnotNull;
int nprimaryKey;
int nautoInc;
int n;
int dtLen;
int csLen;
#if !SQLITE_STANDARD
n = UnsafeNativeMethods.sqlite3_table_column_metadata_interop(_sql, ToUTF8(dataBase), ToUTF8(table), ToUTF8(column), out dataTypePtr, out collSeqPtr, out nnotNull, out nprimaryKey, out nautoInc, out dtLen, out csLen);
#else
dtLen = -1;
csLen = -1;
n = UnsafeNativeMethods.sqlite3_table_column_metadata(_sql, ToUTF8(dataBase), ToUTF8(table), ToUTF8(column), out dataTypePtr, out collSeqPtr, out nnotNull, out nprimaryKey, out nautoInc);
#endif
if (n > 0) throw new SqliteException(n, SQLiteLastError());
dataType = UTF8ToString(dataTypePtr, dtLen);
collateSequence = UTF8ToString(collSeqPtr, csLen);
notNull = (nnotNull == 1);
primaryKey = (nprimaryKey == 1);
autoIncrement = (nautoInc == 1);
}
internal override double GetDouble(SqliteStatement stmt, int index)
{
double value;
#if !PLATFORM_COMPACTFRAMEWORK
value = UnsafeNativeMethods.sqlite3_column_double(stmt._sqlite_stmt, index);
#else
UnsafeNativeMethods.sqlite3_column_double_interop(stmt._sqlite_stmt, index, out value);
#endif
return value;
}
internal override int GetInt32(SqliteStatement stmt, int index)
{
return UnsafeNativeMethods.sqlite3_column_int(stmt._sqlite_stmt, index);
}
internal override long GetInt64(SqliteStatement stmt, int index)
{
long value;
#if !PLATFORM_COMPACTFRAMEWORK
value = UnsafeNativeMethods.sqlite3_column_int64(stmt._sqlite_stmt, index);
#else
UnsafeNativeMethods.sqlite3_column_int64_interop(stmt._sqlite_stmt, index, out value);
#endif
return value;
}
internal override string GetText(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_text_interop(stmt._sqlite_stmt, index, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_column_text(stmt._sqlite_stmt, index), -1);
#endif
}
internal override DateTime GetDateTime(SqliteStatement stmt, int index)
{
#if !SQLITE_STANDARD
int len;
return ToDateTime(UnsafeNativeMethods.sqlite3_column_text_interop(stmt._sqlite_stmt, index, out len), len);
#else
return ToDateTime(UnsafeNativeMethods.sqlite3_column_text(stmt._sqlite_stmt, index), -1);
#endif
}
internal override long GetBytes(SqliteStatement stmt, int index, int nDataOffset, byte[] bDest, int nStart, int nLength)
{
IntPtr ptr;
int nlen;
int nCopied = nLength;
nlen = UnsafeNativeMethods.sqlite3_column_bytes(stmt._sqlite_stmt, index);
ptr = UnsafeNativeMethods.sqlite3_column_blob(stmt._sqlite_stmt, index);
if (bDest == null) return nlen;
if (nCopied + nStart > bDest.Length) nCopied = bDest.Length - nStart;
if (nCopied + nDataOffset > nlen) nCopied = nlen - nDataOffset;
unsafe {
if (nCopied > 0)
Marshal.Copy((IntPtr)((byte*)ptr + nDataOffset), bDest, nStart, nCopied);
else nCopied = 0;
}
return nCopied;
}
internal override long GetChars(SqliteStatement stmt, int index, int nDataOffset, char[] bDest, int nStart, int nLength)
{
int nlen;
int nCopied = nLength;
string str = GetText(stmt, index);
nlen = str.Length;
if (bDest == null) return nlen;
if (nCopied + nStart > bDest.Length) nCopied = bDest.Length - nStart;
if (nCopied + nDataOffset > nlen) nCopied = nlen - nDataOffset;
if (nCopied > 0)
str.CopyTo(nDataOffset, bDest, nStart, nCopied);
else nCopied = 0;
return nCopied;
}
internal override bool IsNull(SqliteStatement stmt, int index)
{
return (ColumnAffinity(stmt, index) == TypeAffinity.Null);
}
internal override int AggregateCount(IntPtr context)
{
return UnsafeNativeMethods.sqlite3_aggregate_count(context);
}
#if MONOTOUCH
class FunctionData {
public SQLiteCallback Func;
public SQLiteCallback FuncStep;
public SQLiteFinalCallback FuncFinal;
}
#endif
internal override void CreateFunction(string strFunction, int nArgs, bool needCollSeq, SQLiteCallback func, SQLiteCallback funcstep, SQLiteFinalCallback funcfinal)
{
int n;
#if MONOTOUCH
var data = new FunctionData();
data.Func = func;
data.FuncStep = funcstep;
data.FuncFinal = funcfinal;
SQLiteCallback func_callback = func == null ? null : new SQLiteCallback(scalar_callback);
SQLiteCallback funcstep_callback = funcstep == null ? null : new SQLiteCallback(step_callback);
SQLiteFinalCallback funcfinal_callback = funcfinal == null ? null : new SQLiteFinalCallback(final_callback);
IntPtr user_data;
user_data = GCHandle.ToIntPtr(GCHandle.Alloc(data));
n = UnsafeNativeMethods.sqlite3_create_function_v2(_sql, ToUTF8(strFunction), nArgs, 4, user_data, func_callback, funcstep_callback, funcfinal_callback, destroy_callback);
if (n == 0) {
// sqlite3_create_function_v2 will call 'destroy_callback' if it fails, so we need to recreate the gchandle here.
user_data = GCHandle.ToIntPtr(GCHandle.Alloc(data));
n = UnsafeNativeMethods.sqlite3_create_function_v2(_sql, ToUTF8(strFunction), nArgs, 1, user_data, func_callback, funcstep_callback, funcfinal_callback, destroy_callback);
}
#elif !SQLITE_STANDARD
n = UnsafeNativeMethods.sqlite3_create_function_interop(_sql, ToUTF8(strFunction), nArgs, 4, IntPtr.Zero, func, funcstep, funcfinal, (needCollSeq == true) ? 1 : 0);
if (n == 0) n = UnsafeNativeMethods.sqlite3_create_function_interop(_sql, ToUTF8(strFunction), nArgs, 1, IntPtr.Zero, func, funcstep, funcfinal, (needCollSeq == true) ? 1 : 0);
#else
n = UnsafeNativeMethods.sqlite3_create_function(_sql, ToUTF8(strFunction), nArgs, 4, IntPtr.Zero, func, funcstep, funcfinal);
if (n == 0) n = UnsafeNativeMethods.sqlite3_create_function(_sql, ToUTF8(strFunction), nArgs, 1, IntPtr.Zero, func, funcstep, funcfinal);
#endif
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void CreateCollation(string strCollation, SQLiteCollation func, SQLiteCollation func16, IntPtr user_data)
{
int n = UnsafeNativeMethods.sqlite3_create_collation(_sql, ToUTF8(strCollation), 2, user_data, func16);
if (n == 0) UnsafeNativeMethods.sqlite3_create_collation(_sql, ToUTF8(strCollation), 1, user_data, func);
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback(typeof(SQLiteCallback))]
internal static void scalar_callback(IntPtr context, int nArgs, IntPtr argsptr)
{
var handle = GCHandle.FromIntPtr (UnsafeNativeMethods.sqlite3_user_data(context));
var func = (FunctionData)handle.Target;
func.Func(context, nArgs, argsptr);
}
[MonoTouch.MonoPInvokeCallback(typeof(SQLiteCallback))]
internal static void step_callback(IntPtr context, int nArgs, IntPtr argsptr)
{
var handle = GCHandle.FromIntPtr(UnsafeNativeMethods.sqlite3_user_data(context));
var func = (FunctionData)handle.Target;
func.FuncStep(context, nArgs, argsptr);
}
[MonoTouch.MonoPInvokeCallback(typeof(SQLiteFinalCallback))]
internal static void final_callback(IntPtr context)
{
var handle = GCHandle.FromIntPtr(UnsafeNativeMethods.sqlite3_user_data(context));
var func = (FunctionData)handle.Target;
func.FuncFinal(context);
}
[MonoTouch.MonoPInvokeCallback(typeof(SQLiteFinalCallback))]
internal static void destroy_callback(IntPtr context)
{
GCHandle.FromIntPtr(context).Free();
}
#endif
internal override int ContextCollateCompare(CollationEncodingEnum enc, IntPtr context, string s1, string s2)
{
#if !SQLITE_STANDARD
byte[] b1;
byte[] b2;
System.Text.Encoding converter = null;
switch (enc)
{
case CollationEncodingEnum.UTF8:
converter = System.Text.Encoding.UTF8;
break;
case CollationEncodingEnum.UTF16LE:
converter = System.Text.Encoding.Unicode;
break;
case CollationEncodingEnum.UTF16BE:
converter = System.Text.Encoding.BigEndianUnicode;
break;
}
b1 = converter.GetBytes(s1);
b2 = converter.GetBytes(s2);
return UnsafeNativeMethods.sqlite3_context_collcompare(context, b1, b1.Length, b2, b2.Length);
#else
throw new NotImplementedException();
#endif
}
internal override int ContextCollateCompare(CollationEncodingEnum enc, IntPtr context, char[] c1, char[] c2)
{
#if !SQLITE_STANDARD
byte[] b1;
byte[] b2;
System.Text.Encoding converter = null;
switch (enc)
{
case CollationEncodingEnum.UTF8:
converter = System.Text.Encoding.UTF8;
break;
case CollationEncodingEnum.UTF16LE:
converter = System.Text.Encoding.Unicode;
break;
case CollationEncodingEnum.UTF16BE:
converter = System.Text.Encoding.BigEndianUnicode;
break;
}
b1 = converter.GetBytes(c1);
b2 = converter.GetBytes(c2);
return UnsafeNativeMethods.sqlite3_context_collcompare(context, b1, b1.Length, b2, b2.Length);
#else
throw new NotImplementedException();
#endif
}
internal override CollationSequence GetCollationSequence(SqliteFunction func, IntPtr context)
{
#if !SQLITE_STANDARD
CollationSequence seq = new CollationSequence();
int len;
int type;
int enc;
IntPtr p = UnsafeNativeMethods.sqlite3_context_collseq(context, out type, out enc, out len);
if (p != null) seq.Name = UTF8ToString(p, len);
seq.Type = (CollationTypeEnum)type;
seq._func = func;
seq.Encoding = (CollationEncodingEnum)enc;
return seq;
#else
throw new NotImplementedException();
#endif
}
internal override long GetParamValueBytes(IntPtr p, int nDataOffset, byte[] bDest, int nStart, int nLength)
{
IntPtr ptr;
int nlen;
int nCopied = nLength;
nlen = UnsafeNativeMethods.sqlite3_value_bytes(p);
ptr = UnsafeNativeMethods.sqlite3_value_blob(p);
if (bDest == null) return nlen;
if (nCopied + nStart > bDest.Length) nCopied = bDest.Length - nStart;
if (nCopied + nDataOffset > nlen) nCopied = nlen - nDataOffset;
unsafe {
if (nCopied > 0)
Marshal.Copy((IntPtr)((byte*)ptr + nDataOffset), bDest, nStart, nCopied);
else nCopied = 0;
}
return nCopied;
}
internal override double GetParamValueDouble(IntPtr ptr)
{
double value;
#if !PLATFORM_COMPACTFRAMEWORK
value = UnsafeNativeMethods.sqlite3_value_double(ptr);
#else
UnsafeNativeMethods.sqlite3_value_double_interop(ptr, out value);
#endif
return value;
}
internal override int GetParamValueInt32(IntPtr ptr)
{
return UnsafeNativeMethods.sqlite3_value_int(ptr);
}
internal override long GetParamValueInt64(IntPtr ptr)
{
Int64 value;
#if !PLATFORM_COMPACTFRAMEWORK
value = UnsafeNativeMethods.sqlite3_value_int64(ptr);
#else
UnsafeNativeMethods.sqlite3_value_int64_interop(ptr, out value);
#endif
return value;
}
internal override string GetParamValueText(IntPtr ptr)
{
#if !SQLITE_STANDARD
int len;
return UTF8ToString(UnsafeNativeMethods.sqlite3_value_text_interop(ptr, out len), len);
#else
return UTF8ToString(UnsafeNativeMethods.sqlite3_value_text(ptr), -1);
#endif
}
internal override TypeAffinity GetParamValueType(IntPtr ptr)
{
return UnsafeNativeMethods.sqlite3_value_type(ptr);
}
internal override void ReturnBlob(IntPtr context, byte[] value)
{
UnsafeNativeMethods.sqlite3_result_blob(context, value, value.Length, (IntPtr)(-1));
}
internal override void ReturnDouble(IntPtr context, double value)
{
#if !PLATFORM_COMPACTFRAMEWORK
UnsafeNativeMethods.sqlite3_result_double(context, value);
#else
UnsafeNativeMethods.sqlite3_result_double_interop(context, ref value);
#endif
}
internal override void ReturnError(IntPtr context, string value)
{
UnsafeNativeMethods.sqlite3_result_error(context, ToUTF8(value), value.Length);
}
internal override void ReturnInt32(IntPtr context, int value)
{
UnsafeNativeMethods.sqlite3_result_int(context, value);
}
internal override void ReturnInt64(IntPtr context, long value)
{
#if !PLATFORM_COMPACTFRAMEWORK
UnsafeNativeMethods.sqlite3_result_int64(context, value);
#else
UnsafeNativeMethods.sqlite3_result_int64_interop(context, ref value);
#endif
}
internal override void ReturnNull(IntPtr context)
{
UnsafeNativeMethods.sqlite3_result_null(context);
}
internal override void ReturnText(IntPtr context, string value)
{
byte[] b = ToUTF8(value);
UnsafeNativeMethods.sqlite3_result_text(context, ToUTF8(value), b.Length - 1, (IntPtr)(-1));
}
internal override IntPtr AggregateContext(IntPtr context)
{
return UnsafeNativeMethods.sqlite3_aggregate_context(context, 1);
}
internal override void SetPassword(byte[] passwordBytes)
{
int n = UnsafeNativeMethods.sqlite3_key(_sql, passwordBytes, passwordBytes.Length);
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
internal override void ChangePassword(byte[] newPasswordBytes)
{
int n = UnsafeNativeMethods.sqlite3_rekey(_sql, newPasswordBytes, (newPasswordBytes == null) ? 0 : newPasswordBytes.Length);
if (n > 0) throw new SqliteException(n, SQLiteLastError());
}
#if MONOTOUCH
SQLiteUpdateCallback update_callback;
SQLiteCommitCallback commit_callback;
SQLiteRollbackCallback rollback_callback;
[MonoTouch.MonoPInvokeCallback (typeof (SQLiteUpdateCallback))]
static void update (IntPtr puser, int type, IntPtr database, IntPtr table, Int64 rowid)
{
SQLite3 instance = GCHandle.FromIntPtr (puser).Target as SQLite3;
instance.update_callback (puser, type, database, table, rowid);
}
internal override void SetUpdateHook (SQLiteUpdateCallback func)
{
update_callback = func;
if (func == null)
UnsafeNativeMethods.sqlite3_update_hook (_sql, null, IntPtr.Zero);
else
UnsafeNativeMethods.sqlite3_update_hook (_sql, update, GCHandle.ToIntPtr (gch));
}
[MonoTouch.MonoPInvokeCallback (typeof (SQLiteCommitCallback))]
static int commit (IntPtr puser)
{
SQLite3 instance = GCHandle.FromIntPtr (puser).Target as SQLite3;
return instance.commit_callback (puser);
}
internal override void SetCommitHook (SQLiteCommitCallback func)
{
commit_callback = func;
if (func == null)
UnsafeNativeMethods.sqlite3_commit_hook (_sql, null, IntPtr.Zero);
else
UnsafeNativeMethods.sqlite3_commit_hook (_sql, commit, GCHandle.ToIntPtr (gch));
}
[MonoTouch.MonoPInvokeCallback (typeof (SQLiteRollbackCallback))]
static void rollback (IntPtr puser)
{
SQLite3 instance = GCHandle.FromIntPtr (puser).Target as SQLite3;
instance.rollback_callback (puser);
}
internal override void SetRollbackHook (SQLiteRollbackCallback func)
{
rollback_callback = func;
if (func == null)
UnsafeNativeMethods.sqlite3_rollback_hook (_sql, null, IntPtr.Zero);
else
UnsafeNativeMethods.sqlite3_rollback_hook (_sql, rollback, GCHandle.ToIntPtr (gch));
}
#else
internal override void SetUpdateHook(SQLiteUpdateCallback func)
{
UnsafeNativeMethods.sqlite3_update_hook(_sql, func, IntPtr.Zero);
}
internal override void SetCommitHook(SQLiteCommitCallback func)
{
UnsafeNativeMethods.sqlite3_commit_hook(_sql, func, IntPtr.Zero);
}
internal override void SetRollbackHook(SQLiteRollbackCallback func)
{
UnsafeNativeMethods.sqlite3_rollback_hook(_sql, func, IntPtr.Zero);
}
#endif
/// <summary>
/// Helper function to retrieve a column of data from an active statement.
/// </summary>
/// <param name="stmt">The statement being step()'d through</param>
/// <param name="index">The column index to retrieve</param>
/// <param name="typ">The type of data contained in the column. If Uninitialized, this function will retrieve the datatype information.</param>
/// <returns>Returns the data in the column</returns>
internal override object GetValue(SqliteStatement stmt, int index, SQLiteType typ)
{
if (IsNull(stmt, index)) return DBNull.Value;
TypeAffinity aff = typ.Affinity;
Type t = null;
if (typ.Type != DbType.Object)
{
t = SqliteConvert.SQLiteTypeToType(typ);
aff = TypeToAffinity(t);
}
switch (aff)
{
case TypeAffinity.Blob:
if (typ.Type == DbType.Guid && typ.Affinity == TypeAffinity.Text)
return new Guid(GetText(stmt, index));
int n = (int)GetBytes(stmt, index, 0, null, 0, 0);
byte[] b = new byte[n];
GetBytes(stmt, index, 0, b, 0, n);
if (typ.Type == DbType.Guid && n == 16)
return new Guid(b);
return b;
case TypeAffinity.DateTime:
return GetDateTime(stmt, index);
case TypeAffinity.Double:
if (t == null) return GetDouble(stmt, index);
else
return Convert.ChangeType(GetDouble(stmt, index), t, null);
case TypeAffinity.Int64:
if (t == null) return GetInt64(stmt, index);
else
return Convert.ChangeType(GetInt64(stmt, index), t, null);
default:
return GetText(stmt, index);
}
}
internal override int GetCursorForTable(SqliteStatement stmt, int db, int rootPage)
{
#if !SQLITE_STANDARD
return UnsafeNativeMethods.sqlite3_table_cursor(stmt._sqlite_stmt, db, rootPage);
#else
return -1;
#endif
}
internal override long GetRowIdForCursor(SqliteStatement stmt, int cursor)
{
#if !SQLITE_STANDARD
long rowid;
int rc = UnsafeNativeMethods.sqlite3_cursor_rowid(stmt._sqlite_stmt, cursor, out rowid);
if (rc == 0) return rowid;
return 0;
#else
return 0;
#endif
}
internal override void GetIndexColumnExtendedInfo(string database, string index, string column, out int sortMode, out int onError, out string collationSequence)
{
#if !SQLITE_STANDARD
IntPtr coll;
int colllen;
int rc;
rc = UnsafeNativeMethods.sqlite3_index_column_info_interop(_sql, ToUTF8(database), ToUTF8(index), ToUTF8(column), out sortMode, out onError, out coll, out colllen);
if (rc != 0) throw new SqliteException(rc, "");
collationSequence = UTF8ToString(coll, colllen);
#else
sortMode = 0;
onError = 2;
collationSequence = "BINARY";
#endif
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Text;
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class TargetConfigurationTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void SimpleElementSyntaxTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='Debug'>
<name>d</name>
<layout>${message}</layout>
</target>
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void ArrayParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter name='p1' layout='${message}' />
<parameter name='p2' layout='${level}' />
<parameter name='p3' layout='${logger}' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
Assert.Equal("'${level}'", t.Parameters[1].Layout.ToString());
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void ArrayElementParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter>
<name>p1</name>
<layout>${message}</layout>
</parameter>
<parameter>
<name>p2</name>
<layout type='CsvLayout'>
<column name='x' layout='${message}' />
<column name='y' layout='${level}' />
</layout>
</parameter>
<parameter>
<name>p3</name>
<layout>${logger}</layout>
</parameter>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;
Assert.NotNull(csvLayout);
Assert.Equal(2, csvLayout.Columns.Count);
Assert.Equal("x", csvLayout.Columns[0].Name);
Assert.Equal("y", csvLayout.Columns[1].Name);
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void SimpleTest2()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message} ${level}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message} ${level}", l.Text);
Assert.NotNull(l);
Assert.Equal(3, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
Assert.IsType(typeof(LiteralLayoutRenderer), l.Renderers[1]);
Assert.IsType(typeof(LevelLayoutRenderer), l.Renderers[2]);
Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text);
}
[Fact]
public void WrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper name='a' type='AsyncWrapper'>
<target name='c' type='Debug' layout='${message}' />
</wrapper>
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void WrapperRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='c' type='Debug' layout='${message}' />
<wrapper name='a' type='AsyncWrapper'>
<target-ref name='c' />
</wrapper>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper-target-ref name='a' />
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void CompoundTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<compound-target name='rr' type='RoundRobinGroup'>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.Equal(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.Equal(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.Equal(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Fact]
public void CompoundRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
<compound-target name='rr' type='RoundRobinGroup'>
<target-ref name='d1' />
<target-ref name='d2' />
<target-ref name='d3' />
<target-ref name='d4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.Equal(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.Equal(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.Equal(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Fact]
public void AsyncWrappersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets async='true'>
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d_wrapped", wrappedTarget.Name);
t = c.FindTargetByName("d2") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal(t.Name, "d2");
wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d2_wrapped", wrappedTarget.Name);
}
[Fact]
public void DefaultTargetParametersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
t = c.FindTargetByName("d2") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
}
[Fact]
public void DefaultWrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-wrapper type='BufferingWrapper'>
<wrapper type='RetryingWrapper' />
</default-wrapper>
<target type='Debug' name='d' layout='${level}' />
<target type='Debug' name='d2' layout='${level}' />
</targets>
</nlog>");
var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper;
Assert.NotNull(bufferingTargetWrapper);
var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper;
Assert.NotNull(retryingTargetWrapper);
Assert.Null(retryingTargetWrapper.Name);
var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget;
Assert.NotNull(debugTarget);
Assert.Equal("d_wrapped", debugTarget.Name);
Assert.Equal("'${level}'", debugTarget.Layout.ToString());
}
[Fact]
public void DataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.Equal(true, myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Fact]
public void NullableDataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyNullableTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.Equal(true, myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Target("MyTarget")]
public class MyTarget : Target
{
public byte ByteProperty { get; set; }
public short Int16Property { get; set; }
public int Int32Property { get; set; }
public long Int64Property { get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
public double DoubleProperty { get; set; }
public float FloatProperty { get; set; }
public MyEnum EnumProperty { get; set; }
public MyFlagsEnum FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
}
[Target("MyNullableTarget")]
public class MyNullableTarget : Target
{
public byte? ByteProperty { get; set; }
public short? Int16Property { get; set; }
public int? Int32Property { get; set; }
public long? Int64Property { get; set; }
public string StringProperty { get; set; }
public bool? BoolProperty { get; set; }
public double? DoubleProperty { get; set; }
public float? FloatProperty { get; set; }
public MyEnum? EnumProperty { get; set; }
public MyFlagsEnum? FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
}
public enum MyEnum
{
Value1,
Value2,
Value3,
}
[Flags]
public enum MyFlagsEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
}
}
}
| |
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
#pragma warning disable
using System;
using System.Collections;
using System.Collections.Generic;
using Consulo.Internal.UnityEditor;
namespace Consulo.Internal.UnityEditor
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem)
{
}
public virtual JSONNode this[int aIndex]
{
get
{
return null;
}
set
{
}
}
public virtual JSONNode this[string aKey]
{
get
{
return null;
}
set
{
}
}
public virtual string Value
{
get
{
return "";
}
set
{
}
}
public virtual int Count
{
get
{
return 0;
}
}
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey)
{
return null;
}
public virtual JSONNode Remove(int aIndex)
{
return null;
}
public virtual JSONNode Remove(JSONNode aNode)
{
return aNode;
}
public virtual IEnumerable<JSONNode> Childs
{
get
{
yield break;
}
}
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach(var C in Childs)
foreach(var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if(int.TryParse(Value, out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if(float.TryParse(Value, out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if(double.TryParse(Value, out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if(bool.TryParse(Value, out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if(b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a, b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while(i < aJSON.Length)
{
switch(aJSON[i])
{
case '{':
if(QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if(ctx != null)
{
TokenName = TokenName.Trim();
if(ctx is JSONArray)
ctx.Add(stack.Peek());
else if(TokenName != "")
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if(QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if(ctx != null)
{
TokenName = TokenName.Trim();
if(ctx is JSONArray)
ctx.Add(stack.Peek());
else if(TokenName != "")
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if(QuoteMode)
{
Token += aJSON[i];
break;
}
if(stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if(Token != "")
{
TokenName = TokenName.Trim();
if(ctx is JSONArray)
ctx.Add(Token);
else if(TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
if(stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if(QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if(QuoteMode)
{
Token += aJSON[i];
break;
}
if(Token != "")
{
if(ctx is JSONArray)
ctx.Add(Token);
else if(TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if(QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if(QuoteMode)
{
char C = aJSON[i];
switch(C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if(QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter)
{
}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using (var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using (var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using (var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if(aIndex < 0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if(aIndex < 0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this);
}
set
{
m_List.Add(value);
}
}
public override int Count
{
get
{
return m_List.Count;
}
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if(aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach(JSONNode N in m_List)
{
if(result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach(JSONNode N in m_List)
{
if(result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix + " ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if(m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if(m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey, value);
}
}
public override JSONNode this[int aIndex]
{
get
{
throw new Exception("[int] is not implemented");
}
set
{
throw new Exception("[int] is not implemented");
}
}
public override int Count
{
get
{
return m_Dict.Count;
}
}
public override void Add(string aKey, JSONNode aItem)
{
if(!string.IsNullOrEmpty(aKey))
{
if(m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if(!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
throw new Exception("Remove is not implemented");
}
public override JSONNode Remove(JSONNode aNode)
{
throw new Exception("Remove is not implemented");
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
{
if(result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
{
if(result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix + " ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get
{
return m_Data;
}
set
{
m_Data = value;
}
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if(tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if(tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if(tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if(tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if(m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if(b == null)
return true;
return System.Object.ReferenceEquals(a, b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if(obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input;
using osu.Framework.Utils;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
using osuTK.Graphics;
using JetBrains.Annotations;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneDrawableScrollingRuleset : OsuTestScene
{
/// <summary>
/// The amount of time visible by the "view window" of the playfield.
/// All hitobjects added through <see cref="createBeatmap"/> are spaced apart by this value, such that for a beat length of 1000,
/// there will be at most 2 hitobjects visible in the "view window".
/// </summary>
private const double time_range = 1000;
private readonly ManualClock testClock = new ManualClock();
private TestDrawableScrollingRuleset drawableRuleset;
[SetUp]
public void Setup() => Schedule(() => testClock.CurrentTime = 0);
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestHitObjectLifetime(string pooled)
{
var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject());
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertPosition(0, 0f);
assertDead(3);
setTime(3 * time_range);
assertPosition(3, 0f);
assertDead(0);
setTime(0 * time_range);
assertPosition(0, 0f);
assertDead(3);
}
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestNestedHitObject(string pooled)
{
var beatmap = createBeatmap(i =>
{
var h = pooled == "pooled" ? new TestPooledParentHitObject() : new TestParentHitObject();
h.Duration = 300;
h.ChildTimeOffset = i % 3 * 100;
return h;
});
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertPosition(0, 0f);
assertHeight(0);
assertChildPosition(0);
setTime(5 * time_range);
assertPosition(5, 0f);
assertHeight(5);
assertChildPosition(5);
}
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestLifetimeRecomputedWhenTimeRangeChanges(string pooled)
{
var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject());
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertDead(3);
AddStep("increase time range", () => drawableRuleset.TimeRange.Value = 3 * time_range);
assertPosition(3, 1);
}
[Test]
public void TestRelativeBeatLengthScaleSingleTimingPoint()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
assertPosition(0, 0f);
// The single timing point is 1x speed relative to itself, such that the hitobject occurring time_range milliseconds later should appear
// at the bottom of the view window regardless of the timing point's beat length
assertPosition(1, 1f);
}
[Test]
public void TestRelativeBeatLengthScaleTimingPointBeyondEndDoesNotBecomeDominant()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 });
beatmap.ControlPointInfo.Add(12000, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(100000, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
assertPosition(0, 0f);
assertPosition(1, 1f);
}
[Test]
public void TestRelativeBeatLengthScaleFromSecondTimingPoint()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
// The first timing point should have a relative velocity of 2
assertPosition(0, 0f);
assertPosition(1, 0.5f);
assertPosition(2, 1f);
// Move to the second timing point
setTime(3 * time_range);
assertPosition(3, 0f);
// As above, this is the timing point that is 1x speed relative to itself, so the hitobject occurring time_range milliseconds later should be at the bottom of the view window
assertPosition(4, 1f);
}
[Test]
public void TestNonRelativeScale()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap);
assertPosition(0, 0f);
assertPosition(1, 1);
// Move to the second timing point
setTime(3 * time_range);
assertPosition(3, 0f);
// For a beat length of 500, the view window of this timing point is elongated 2x (1000 / 500), such that the second hitobject is two TimeRanges away (offscreen)
// To bring it on-screen, half TimeRange is added to the current time, bringing the second half of the view window into view, and the hitobject should appear at the bottom
setTime(3 * time_range + time_range / 2);
assertPosition(4, 1f);
}
[Test]
public void TestSliderMultiplierDoesNotAffectRelativeBeatLength()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.Difficulty.SliderMultiplier = 2;
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 5000);
for (int i = 0; i < 5; i++)
assertPosition(i, i / 5f);
}
[Test]
public void TestSliderMultiplierAffectsNonRelativeBeatLength()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.Difficulty.SliderMultiplier = 2;
createTest(beatmap);
AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 2000);
assertPosition(0, 0);
assertPosition(1, 1);
}
/// <summary>
/// Get a <see cref="DrawableTestHitObject" /> corresponding to the <paramref name="index"/>'th <see cref="TestHitObject"/>.
/// When the hit object is not alive, `null` is returned.
/// </summary>
[CanBeNull]
private DrawableTestHitObject getDrawableHitObject(int index)
{
var hitObject = drawableRuleset.Beatmap.HitObjects.ElementAt(index);
return (DrawableTestHitObject)drawableRuleset.Playfield.HitObjectContainer.AliveObjects.FirstOrDefault(obj => obj.HitObject == hitObject);
}
private float yScale => drawableRuleset.Playfield.HitObjectContainer.DrawHeight;
private void assertDead(int index) => AddAssert($"hitobject {index} is dead", () => getDrawableHitObject(index) == null);
private void assertHeight(int index) => AddAssert($"hitobject {index} height", () =>
{
var d = getDrawableHitObject(index);
return d != null && Precision.AlmostEquals(d.DrawHeight, yScale * (float)(d.HitObject.Duration / time_range), 0.1f);
});
private void assertChildPosition(int index) => AddAssert($"hitobject {index} child position", () =>
{
var d = getDrawableHitObject(index);
return d is DrawableTestParentHitObject && Precision.AlmostEquals(
d.NestedHitObjects.First().DrawPosition.Y,
yScale * (float)((TestParentHitObject)d.HitObject).ChildTimeOffset / time_range, 0.1f);
});
private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}",
() => Precision.AlmostEquals(getDrawableHitObject(index)?.DrawPosition.Y ?? -1, yScale * relativeY));
private void setTime(double time)
{
AddStep($"set time = {time}", () => testClock.CurrentTime = time);
}
/// <summary>
/// Creates an <see cref="IBeatmap"/>, containing 10 hitobjects and user-provided timing points.
/// The hitobjects are spaced <see cref="time_range"/> milliseconds apart.
/// </summary>
/// <returns>The <see cref="IBeatmap"/>.</returns>
private IBeatmap createBeatmap(Func<int, TestHitObject> createAction = null)
{
var beatmap = new Beatmap<TestHitObject> { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } };
for (int i = 0; i < 10; i++)
{
var h = createAction?.Invoke(i) ?? new TestHitObject();
h.StartTime = i * time_range;
beatmap.HitObjects.Add(h);
}
return beatmap;
}
private void createTest(IBeatmap beatmap, Action<TestDrawableScrollingRuleset> overrideAction = null) => AddStep("create test", () =>
{
var ruleset = new TestScrollingRuleset();
drawableRuleset = (TestDrawableScrollingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap).GetPlayableBeatmap(ruleset.RulesetInfo));
drawableRuleset.FrameStablePlayback = false;
overrideAction?.Invoke(drawableRuleset);
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
Height = 0.75f,
Width = 400,
Masking = true,
Clock = new FramedClock(testClock),
Child = drawableRuleset
};
});
#region Ruleset
private class TestScrollingRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => new TestDrawableScrollingRuleset(this, beatmap, mods);
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap, null);
public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description { get; } = string.Empty;
public override string ShortName { get; } = string.Empty;
}
private class TestDrawableScrollingRuleset : DrawableScrollingRuleset<TestHitObject>
{
public bool RelativeScaleBeatLengthsOverride { get; set; }
protected override bool RelativeScaleBeatLengths => RelativeScaleBeatLengthsOverride;
protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping;
public new Bindable<double> TimeRange => base.TimeRange;
public TestDrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
TimeRange.Value = time_range;
}
public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h)
{
switch (h)
{
case TestPooledHitObject _:
case TestPooledParentHitObject _:
return null;
case TestParentHitObject p:
return new DrawableTestParentHitObject(p);
default:
return new DrawableTestHitObject(h);
}
}
protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager();
protected override Playfield CreatePlayfield() => new TestPlayfield();
}
private class TestPlayfield : ScrollingPlayfield
{
public TestPlayfield()
{
AddInternal(new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.2f,
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 150 },
Children = new Drawable[]
{
new Box
{
Anchor = Anchor.TopCentre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = 2,
Colour = Color4.Green
},
HitObjectContainer
}
}
}
});
RegisterPool<TestPooledHitObject, DrawableTestPooledHitObject>(1);
RegisterPool<TestPooledParentHitObject, DrawableTestPooledParentHitObject>(1);
}
}
private class TestBeatmapConverter : BeatmapConverter<TestHitObject>
{
public TestBeatmapConverter(IBeatmap beatmap, Ruleset ruleset)
: base(beatmap, ruleset)
{
}
public override bool CanConvert() => true;
protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken) =>
throw new NotImplementedException();
}
#endregion
#region HitObject
private class TestHitObject : HitObject, IHasDuration
{
public double EndTime => StartTime + Duration;
public double Duration { get; set; } = 100;
}
private class TestPooledHitObject : TestHitObject
{
}
private class TestParentHitObject : TestHitObject
{
public double ChildTimeOffset;
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
AddNested(new TestHitObject { StartTime = StartTime + ChildTimeOffset });
}
}
private class TestPooledParentHitObject : TestParentHitObject
{
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
AddNested(new TestPooledHitObject { StartTime = StartTime + ChildTimeOffset });
}
}
private class DrawableTestHitObject : DrawableHitObject<TestHitObject>
{
public DrawableTestHitObject([CanBeNull] TestHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.TopCentre;
Origin = Anchor.TopCentre;
Size = new Vector2(100, 25);
AddRangeInternal(new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.LightPink
},
new Box
{
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.X,
Height = 2,
Colour = Color4.Red
}
});
}
protected override void Update() => LifetimeEnd = HitObject.EndTime;
}
private class DrawableTestPooledHitObject : DrawableTestHitObject
{
public DrawableTestPooledHitObject()
: base(null)
{
InternalChildren[0].Colour = Color4.LightSkyBlue;
InternalChildren[1].Colour = Color4.Blue;
}
}
private class DrawableTestParentHitObject : DrawableTestHitObject
{
private readonly Container<DrawableHitObject> container;
public DrawableTestParentHitObject([CanBeNull] TestHitObject hitObject)
: base(hitObject)
{
InternalChildren[0].Colour = Color4.LightYellow;
InternalChildren[1].Colour = Color4.Yellow;
AddInternal(container = new Container<DrawableHitObject>
{
RelativeSizeAxes = Axes.Both,
});
}
protected override DrawableHitObject CreateNestedHitObject(HitObject hitObject) =>
new DrawableTestHitObject((TestHitObject)hitObject);
protected override void AddNestedHitObject(DrawableHitObject hitObject) => container.Add(hitObject);
protected override void ClearNestedHitObjects() => container.Clear(false);
}
private class DrawableTestPooledParentHitObject : DrawableTestParentHitObject
{
public DrawableTestPooledParentHitObject()
: base(null)
{
InternalChildren[0].Colour = Color4.LightSeaGreen;
InternalChildren[1].Colour = Color4.Green;
}
}
#endregion
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// <p>Encapsulates functionality and implementation that is common to UPC and EAN families
/// of one-dimensional barcodes.</p>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// <author>Sean Owen</author>
/// <author>alasdair@google.com (Alasdair Mackintosh)</author>
/// </summary>
public abstract class UPCEANReader : OneDReader
{
// These two values are critical for determining how permissive the decoding will be.
// We've arrived at these values through a lot of trial and error. Setting them any higher
// lets false positives creep in quickly.
private static readonly int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.48f);
private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
/// <summary>
/// Start/end guard pattern.
/// </summary>
internal static int[] START_END_PATTERN = { 1, 1, 1, };
/// <summary>
/// Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
/// </summary>
internal static int[] MIDDLE_PATTERN = { 1, 1, 1, 1, 1 };
/// <summary>
/// end guard pattern.
/// </summary>
internal static int[] END_PATTERN = {1, 1, 1, 1, 1, 1};
/// <summary>
/// "Odd", or "L" patterns used to encode UPC/EAN digits.
/// </summary>
internal static int[][] L_PATTERNS = {
new[] {3, 2, 1, 1}, // 0
new[] {2, 2, 2, 1}, // 1
new[] {2, 1, 2, 2}, // 2
new[] {1, 4, 1, 1}, // 3
new[] {1, 1, 3, 2}, // 4
new[] {1, 2, 3, 1}, // 5
new[] {1, 1, 1, 4}, // 6
new[] {1, 3, 1, 2}, // 7
new[] {1, 2, 1, 3}, // 8
new[] {3, 1, 1, 2} // 9
};
/// <summary>
/// As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
/// </summary>
internal static int[][] L_AND_G_PATTERNS;
static UPCEANReader()
{
L_AND_G_PATTERNS = new int[20][];
Array.Copy(L_PATTERNS, 0, L_AND_G_PATTERNS, 0, 10);
for (int i = 10; i < 20; i++)
{
int[] widths = L_PATTERNS[i - 10];
int[] reversedWidths = new int[widths.Length];
for (int j = 0; j < widths.Length; j++)
{
reversedWidths[j] = widths[widths.Length - j - 1];
}
L_AND_G_PATTERNS[i] = reversedWidths;
}
}
private readonly StringBuilder decodeRowStringBuffer;
private readonly UPCEANExtensionSupport extensionReader;
private readonly EANManufacturerOrgSupport eanManSupport;
/// <summary>
/// Initializes a new instance of the <see cref="UPCEANReader"/> class.
/// </summary>
protected UPCEANReader()
{
decodeRowStringBuffer = new StringBuilder(20);
extensionReader = new UPCEANExtensionSupport();
eanManSupport = new EANManufacturerOrgSupport();
}
internal static int[] findStartGuardPattern(BitArray row)
{
bool foundStart = false;
int[] startRange = null;
int nextStart = 0;
int[] counters = new int[START_END_PATTERN.Length];
while (!foundStart)
{
for (int idx = 0; idx < START_END_PATTERN.Length; idx++)
counters[idx] = 0;
startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN, counters);
if (startRange == null)
return null;
int start = startRange[0];
nextStart = startRange[1];
// Make sure there is a quiet zone at least as big as the start pattern before the barcode.
// If this check would run off the left edge of the image, do not accept this barcode,
// as it is very likely to be a false positive.
int quietStart = start - (nextStart - start);
if (quietStart >= 0)
{
foundStart = row.isRange(quietStart, start, false);
}
}
return startRange;
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns>
/// <see cref="Result"/>containing encoded string and start/end of barcode or null, if an error occurs or barcode cannot be found
/// </returns>
public override Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
}
/// <summary>
/// <p>Like <see cref="decodeRow(int,ZXing.Common.BitArray,System.Collections.Generic.IDictionary{ZXing.DecodeHintType,object})"/>, but
/// allows caller to inform method about where the UPC/EAN start pattern is
/// found. This allows this to be computed once and reused across many implementations.</p>
/// </summary>
/// <param name="rowNumber">row index into the image</param>
/// <param name="row">encoding of the row of the barcode image</param>
/// <param name="startGuardRange">start/end column where the opening start pattern was found</param>
/// <param name="hints">optional hints that influence decoding</param>
/// <returns><see cref="Result"/> encapsulating the result of decoding a barcode in the row</returns>
public virtual Result decodeRow(int rowNumber,
BitArray row,
int[] startGuardRange,
IDictionary<DecodeHintType, object> hints)
{
var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null :
(ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(
(startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
));
}
var result = decodeRowStringBuffer;
result.Length = 0;
var endStart = decodeMiddle(row, startGuardRange, result);
if (endStart < 0)
return null;
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(
endStart, rowNumber
));
}
var endRange = decodeEnd(row, endStart);
if (endRange == null)
return null;
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(
(endRange[0] + endRange[1]) / 2.0f, rowNumber
));
}
// Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
// spec might want more whitespace, but in practice this is the maximum we can count on.
var end = endRange[1];
var quietEnd = end + (end - endRange[0]);
if (quietEnd >= row.Size || !row.isRange(end, quietEnd, false))
{
return null;
}
var resultString = result.ToString();
// UPC/EAN should never be less than 8 chars anyway
if (resultString.Length < 8)
{
return null;
}
if (!checkChecksum(resultString))
{
return null;
}
var left = (startGuardRange[1] + startGuardRange[0]) / 2.0f;
var right = (endRange[1] + endRange[0]) / 2.0f;
var format = BarcodeFormat;
var decodeResult = new Result(resultString,
null, // no natural byte representation for these barcodes
new ResultPoint[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
format);
var extensionResult = extensionReader.decodeRow(rowNumber, row, endRange[1]);
if (extensionResult != null)
{
decodeResult.putMetadata(ResultMetadataType.UPC_EAN_EXTENSION, extensionResult.Text);
decodeResult.putAllMetadata(extensionResult.ResultMetadata);
decodeResult.addResultPoints(extensionResult.ResultPoints);
int extensionLength = extensionResult.Text.Length;
int[] allowedExtensions = hints != null && hints.ContainsKey(DecodeHintType.ALLOWED_EAN_EXTENSIONS) ?
(int[]) hints[DecodeHintType.ALLOWED_EAN_EXTENSIONS] : null;
if (allowedExtensions != null)
{
bool valid = false;
foreach (int length in allowedExtensions)
{
if (extensionLength == length)
{
valid = true;
break;
}
}
if (!valid)
{
return null;
}
}
}
if (format == BarcodeFormat.EAN_13 || format == BarcodeFormat.UPC_A)
{
String countryID = eanManSupport.lookupCountryIdentifier(resultString);
if (countryID != null)
{
decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID);
}
}
return decodeResult;
}
/// <summary>
/// </summary>
/// <param name="s">string of digits to check</param>
/// <returns>see <see cref="checkStandardUPCEANChecksum(String)"/></returns>
protected virtual bool checkChecksum(String s)
{
return checkStandardUPCEANChecksum(s);
}
/// <summary>
/// Computes the UPC/EAN checksum on a string of digits, and reports
/// whether the checksum is correct or not.
/// </summary>
/// <param name="s">string of digits to check</param>
/// <returns>true iff string of digits passes the UPC/EAN checksum algorithm</returns>
internal static bool checkStandardUPCEANChecksum(String s)
{
int length = s.Length;
if (length == 0)
{
return false;
}
int check = s[length - 1] - '0';
return getStandardUPCEANChecksum(s.Substring(0, length - 1)) == check;
}
internal static int? getStandardUPCEANChecksum(String s)
{
int length = s.Length;
int sum = 0;
for (int i = length - 1; i >= 0; i -= 2)
{
int digit = s[i] - '0';
if (digit < 0 || digit > 9)
{
throw new ArgumentException("Contents should only contain digits, but got '" + s[i] + "'");
}
sum += digit;
}
sum *= 3;
for (int i = length - 2; i >= 0; i -= 2)
{
int digit = s[i] - '0';
if (digit < 0 || digit > 9)
{
throw new ArgumentException("Contents should only contain digits, but got '" + s[i] + "'");
}
sum += digit;
}
return (1000 - sum)%10;
}
/// <summary>
/// Decodes the end.
/// </summary>
/// <param name="row">The row.</param>
/// <param name="endStart">The end start.</param>
/// <returns></returns>
protected virtual int[] decodeEnd(BitArray row, int endStart)
{
return findGuardPattern(row, endStart, false, START_END_PATTERN);
}
internal static int[] findGuardPattern(BitArray row,
int rowOffset,
bool whiteFirst,
int[] pattern)
{
return findGuardPattern(row, rowOffset, whiteFirst, pattern, new int[pattern.Length]);
}
/// <summary>
/// </summary>
/// <param name="row">row of black/white values to search</param>
/// <param name="rowOffset">position to start search</param>
/// <param name="whiteFirst">if true, indicates that the pattern specifies white/black/white/...</param>
/// pixel counts, otherwise, it is interpreted as black/white/black/...
/// <param name="pattern">pattern of counts of number of black and white pixels that are being</param>
/// searched for as a pattern
/// <param name="counters">array of counters, as long as pattern, to re-use</param>
/// <returns>start/end horizontal offset of guard pattern, as an array of two ints</returns>
internal static int[] findGuardPattern(BitArray row,
int rowOffset,
bool whiteFirst,
int[] pattern,
int[] counters)
{
int patternLength = pattern.Length;
int width = row.Size;
bool isWhite = whiteFirst;
rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset);
int counterPosition = 0;
int patternStart = rowOffset;
for (int x = rowOffset; x < width; x++)
{
if (row[x] != isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE)
{
return new int[] { patternStart, x };
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, counterPosition - 1);
counters[counterPosition - 1] = 0;
counters[counterPosition] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
/// <summary>
/// Attempts to decode a single UPC/EAN-encoded digit.
/// </summary>
/// <param name="row">row of black/white values to decode</param>
/// <param name="counters">the counts of runs of observed black/white/black/... values</param>
/// <param name="rowOffset">horizontal offset to start decoding from</param>
/// <param name="patterns">the set of patterns to use to decode -- sometimes different encodings</param>
/// for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
/// be used
/// <returns>horizontal offset of first pixel beyond the decoded digit</returns>
internal static bool decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns, out int digit)
{
digit = -1;
if (!recordPattern(row, rowOffset, counters))
return false;
int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
int max = patterns.Length;
for (int i = 0; i < max; i++)
{
int[] pattern = patterns[i];
int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance)
{
bestVariance = variance;
digit = i;
}
}
return digit >= 0;
}
/// <summary>
/// Get the format of this decoder.
/// </summary>
/// <returns>The 1D format.</returns>
internal abstract BarcodeFormat BarcodeFormat { get; }
/// <summary>
/// Subclasses override this to decode the portion of a barcode between the start
/// and end guard patterns.
/// </summary>
/// <param name="row">row of black/white values to search</param>
/// <param name="startRange">start/end offset of start guard pattern</param>
/// <param name="resultString"><see cref="StringBuilder" />to append decoded chars to</param>
/// <returns>horizontal offset of first pixel after the "middle" that was decoded or -1 if decoding could not complete successfully</returns>
protected internal abstract int decodeMiddle(BitArray row,
int[] startRange,
StringBuilder resultString);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol>
{
private struct LocalNameAndScope : IEquatable<LocalNameAndScope>
{
internal readonly string LocalName;
internal readonly int ScopeStart;
internal readonly int ScopeEnd;
internal LocalNameAndScope(string localName, int scopeStart, int scopeEnd)
{
LocalName = localName;
ScopeStart = scopeStart;
ScopeEnd = scopeEnd;
}
public bool Equals(LocalNameAndScope other)
{
return ScopeStart == other.ScopeStart &&
ScopeEnd == other.ScopeEnd &&
string.Equals(LocalName, other.LocalName, StringComparison.Ordinal);
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
public override int GetHashCode()
{
return Hash.Combine(
Hash.Combine(ScopeStart, ScopeEnd),
LocalName.GetHashCode());
}
}
public unsafe static MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadMethodDebugInfo(
ISymUnmanagedReader3 symReader,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProviderOpt, // TODO: only null in DTEE case where we looking for default namesapace
int methodToken,
int methodVersion,
int ilOffset,
bool isVisualBasicMethod)
{
// no symbols
if (symReader == null)
{
return None;
}
if (symReader is ISymUnmanagedReader5 symReader5)
{
int hr = symReader5.GetPortableDebugMetadataByVersion(methodVersion, out byte* metadata, out int size);
SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr);
if (hr == 0)
{
var mdReader = new MetadataReader(metadata, size);
try
{
return ReadFromPortable(mdReader, methodToken, ilOffset, symbolProviderOpt, isVisualBasicMethod);
}
catch (BadImageFormatException)
{
// bad CDI, ignore
return None;
}
}
}
var allScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
var containingScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
try
{
var symMethod = symReader.GetMethodByVersion(methodToken, methodVersion);
if (symMethod != null)
{
symMethod.GetAllScopes(allScopes, containingScopes, ilOffset, isScopeEndInclusive: isVisualBasicMethod);
}
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups;
ImmutableArray<ExternAliasRecord> externAliasRecords;
string defaultNamespaceName;
if (isVisualBasicMethod)
{
ReadVisualBasicImportsDebugInfo(
symReader,
methodToken,
methodVersion,
out importRecordGroups,
out defaultNamespaceName);
externAliasRecords = ImmutableArray<ExternAliasRecord>.Empty;
}
else
{
Debug.Assert(symbolProviderOpt != null);
ReadCSharpNativeImportsInfo(
symReader,
symbolProviderOpt,
methodToken,
methodVersion,
out importRecordGroups,
out externAliasRecords);
defaultNamespaceName = "";
}
ImmutableArray<HoistedLocalScopeRecord> hoistedLocalScopeRecords = ImmutableArray<HoistedLocalScopeRecord>.Empty;
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap = null;
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap = null;
ImmutableDictionary<int, ImmutableArray<string>> tupleLocalMap = null;
ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMap = null;
byte[] customDebugInfo = symReader.GetCustomDebugInfoBytes(methodToken, methodVersion);
if (customDebugInfo != null)
{
if (!isVisualBasicMethod)
{
var customDebugInfoRecord = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.StateMachineHoistedLocalScopes);
if (!customDebugInfoRecord.IsDefault)
{
hoistedLocalScopeRecords = CustomDebugInfoReader.DecodeStateMachineHoistedLocalScopesRecord(customDebugInfoRecord)
.SelectAsArray(s => new HoistedLocalScopeRecord(s.StartOffset, s.EndOffset - s.StartOffset + 1));
}
GetCSharpDynamicLocalInfo(
customDebugInfo,
allScopes,
out dynamicLocalMap,
out dynamicLocalConstantMap);
}
GetTupleElementNamesLocalInfo(
customDebugInfo,
out tupleLocalMap,
out tupleLocalConstantMap);
}
var constantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance();
if (symbolProviderOpt != null) // TODO
{
GetConstants(constantsBuilder, symbolProviderOpt, containingScopes, dynamicLocalConstantMap, tupleLocalConstantMap);
}
var reuseSpan = GetReuseSpan(allScopes, ilOffset, isVisualBasicMethod);
return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>(
hoistedLocalScopeRecords,
importRecordGroups,
externAliasRecords,
dynamicLocalMap,
tupleLocalMap,
defaultNamespaceName,
containingScopes.GetLocalNames(),
constantsBuilder.ToImmutableAndFree(),
reuseSpan);
}
catch (InvalidOperationException)
{
// bad CDI, ignore
return None;
}
finally
{
allScopes.Free();
containingScopes.Free();
}
}
/// <summary>
/// Get the (unprocessed) import strings for a given method.
/// </summary>
/// <remarks>
/// Doesn't consider forwarding.
///
/// CONSIDER: Dev12 doesn't just check the root scope - it digs around to find the best
/// match based on the IL offset and then walks up to the root scope (see PdbUtil::GetScopeFromOffset).
/// However, it's not clear that this matters, since imports can't be scoped in VB. This is probably
/// just based on the way they were extracting locals and constants based on a specific scope.
///
/// Returns empty array if there are no import strings for the specified method.
/// </remarks>
private static ImmutableArray<string> GetImportStrings(ISymUnmanagedReader reader, int methodToken, int methodVersion)
{
var method = reader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
// In rare circumstances (only bad PDBs?) GetMethodByVersion can return null.
// If there's no debug info for the method, then no import strings are available.
return ImmutableArray<string>.Empty;
}
ISymUnmanagedScope rootScope = method.GetRootScope();
if (rootScope == null)
{
Debug.Assert(false, "Expected a root scope.");
return ImmutableArray<string>.Empty;
}
var childScopes = rootScope.GetChildren();
if (childScopes.Length == 0)
{
// It seems like there should always be at least one child scope, but we've
// seen PDBs where that is not the case.
return ImmutableArray<string>.Empty;
}
// As in NamespaceListWrapper::Init, we only consider namespaces in the first
// child of the root scope.
ISymUnmanagedScope firstChildScope = childScopes[0];
var namespaces = firstChildScope.GetNamespaces();
if (namespaces.Length == 0)
{
// It seems like there should always be at least one namespace (i.e. the global
// namespace), but we've seen PDBs where that is not the case.
return ImmutableArray<string>.Empty;
}
return ImmutableArray.CreateRange(namespaces.Select(n => n.GetName()));
}
private static void ReadCSharpNativeImportsInfo(
ISymUnmanagedReader3 reader,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
int methodToken,
int methodVersion,
out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
out ImmutableArray<ExternAliasRecord> externAliasRecords)
{
ImmutableArray<string> externAliasStrings;
var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings(
methodToken,
KeyValuePair.Create(reader, methodVersion),
getMethodCustomDebugInfo: (token, arg) => arg.Key.GetCustomDebugInfoBytes(token, arg.Value),
getMethodImportStrings: (token, arg) => GetImportStrings(arg.Key, token, arg.Value),
externAliasStrings: out externAliasStrings);
Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault);
ArrayBuilder<ImmutableArray<ImportRecord>> importRecordGroupBuilder = null;
ArrayBuilder<ExternAliasRecord> externAliasRecordBuilder = null;
if (!importStringGroups.IsDefault)
{
importRecordGroupBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance(importStringGroups.Length);
foreach (var importStringGroup in importStringGroups)
{
var groupBuilder = ArrayBuilder<ImportRecord>.GetInstance(importStringGroup.Length);
foreach (var importString in importStringGroup)
{
ImportRecord record;
if (TryCreateImportRecordFromCSharpImportString(symbolProvider, importString, out record))
{
groupBuilder.Add(record);
}
else
{
Debug.WriteLine($"Failed to parse import string {importString}");
}
}
importRecordGroupBuilder.Add(groupBuilder.ToImmutableAndFree());
}
if (!externAliasStrings.IsDefault)
{
externAliasRecordBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance(externAliasStrings.Length);
foreach (string externAliasString in externAliasStrings)
{
string alias;
string externAlias;
string target;
ImportTargetKind kind;
if (!CustomDebugInfoReader.TryParseCSharpImportString(externAliasString, out alias, out externAlias, out target, out kind))
{
Debug.WriteLine($"Unable to parse extern alias '{externAliasString}'");
continue;
}
Debug.Assert(kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?");
Debug.Assert(alias != null); // Name of the extern alias.
Debug.Assert(externAlias == null); // Not used.
Debug.Assert(target != null); // Name of the target assembly.
AssemblyIdentity targetIdentity;
if (!AssemblyIdentity.TryParseDisplayName(target, out targetIdentity))
{
Debug.WriteLine($"Unable to parse target of extern alias '{externAliasString}'");
continue;
}
externAliasRecordBuilder.Add(new ExternAliasRecord(alias, targetIdentity));
}
}
}
importRecordGroups = importRecordGroupBuilder?.ToImmutableAndFree() ?? ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
externAliasRecords = externAliasRecordBuilder?.ToImmutableAndFree() ?? ImmutableArray<ExternAliasRecord>.Empty;
}
private static bool TryCreateImportRecordFromCSharpImportString(EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, string importString, out ImportRecord record)
{
ImportTargetKind targetKind;
string externAlias;
string alias;
string targetString;
if (CustomDebugInfoReader.TryParseCSharpImportString(importString, out alias, out externAlias, out targetString, out targetKind))
{
ITypeSymbol type = null;
if (targetKind == ImportTargetKind.Type)
{
type = symbolProvider.GetTypeSymbolForSerializedType(targetString);
targetString = null;
}
record = new ImportRecord(
targetKind: targetKind,
alias: alias,
targetType: type,
targetString: targetString,
targetAssembly: null,
targetAssemblyAlias: externAlias);
return true;
}
record = default(ImportRecord);
return false;
}
/// <exception cref="InvalidOperationException">Bad data.</exception>
private static void GetCSharpDynamicLocalInfo(
byte[] customDebugInfo,
IEnumerable<ISymUnmanagedScope> scopes,
out ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap,
out ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap)
{
dynamicLocalMap = null;
dynamicLocalConstantMap = null;
var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.DynamicLocals);
if (record.IsDefault)
{
return;
}
var localKindsByName = PooledDictionary<string, LocalKind>.GetInstance();
GetLocalKindByName(localKindsByName, scopes);
ImmutableDictionary<int, ImmutableArray<bool>>.Builder localBuilder = null;
ImmutableDictionary<string, ImmutableArray<bool>>.Builder constantBuilder = null;
var dynamicLocals = CustomDebugInfoReader.DecodeDynamicLocalsRecord(record);
foreach (var dynamicLocal in dynamicLocals)
{
int slot = dynamicLocal.SlotId;
var flags = GetFlags(dynamicLocal);
if (slot == 0)
{
LocalKind kind;
var name = dynamicLocal.LocalName;
localKindsByName.TryGetValue(name, out kind);
switch (kind)
{
case LocalKind.DuplicateName:
// Drop locals with ambiguous names.
continue;
case LocalKind.ConstantName:
constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder<string, ImmutableArray<bool>>();
constantBuilder[name] = flags;
continue;
}
}
localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder<int, ImmutableArray<bool>>();
localBuilder[slot] = flags;
}
if (localBuilder != null)
{
dynamicLocalMap = localBuilder.ToImmutable();
}
if (constantBuilder != null)
{
dynamicLocalConstantMap = constantBuilder.ToImmutable();
}
localKindsByName.Free();
}
private static ImmutableArray<bool> GetFlags(DynamicLocalInfo bucket)
{
int flagCount = bucket.FlagCount;
ulong flags = bucket.Flags;
var builder = ArrayBuilder<bool>.GetInstance(flagCount);
for (int i = 0; i < flagCount; i++)
{
builder.Add((flags & (1u << i)) != 0);
}
return builder.ToImmutableAndFree();
}
private enum LocalKind { DuplicateName, VariableName, ConstantName }
/// <summary>
/// Dynamic CDI encodes slot id and name for each dynamic local variable, but only name for a constant.
/// Constants have slot id set to 0. As a result there is a potential for ambiguity. If a variable in a slot 0
/// and a constant defined anywhere in the method body have the same name we can't say which one
/// the dynamic flags belong to (if there is a dynamic record for at least one of them).
///
/// This method returns the local kind (variable, constant, or duplicate) based on name.
/// </summary>
private static void GetLocalKindByName(Dictionary<string, LocalKind> localNames, IEnumerable<ISymUnmanagedScope> scopes)
{
Debug.Assert(localNames.Count == 0);
var localSlot0 = scopes.SelectMany(scope => scope.GetLocals()).FirstOrDefault(variable => variable.GetSlot() == 0);
if (localSlot0 != null)
{
localNames.Add(localSlot0.GetName(), LocalKind.VariableName);
}
foreach (var scope in scopes)
{
foreach (var constant in scope.GetConstants())
{
string name = constant.GetName();
localNames[name] = localNames.ContainsKey(name) ? LocalKind.DuplicateName : LocalKind.ConstantName;
}
}
}
private static void GetTupleElementNamesLocalInfo(
byte[] customDebugInfo,
out ImmutableDictionary<int, ImmutableArray<string>> tupleLocalMap,
out ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMap)
{
tupleLocalMap = null;
tupleLocalConstantMap = null;
var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.TupleElementNames);
if (record.IsDefault)
{
return;
}
ImmutableDictionary<int, ImmutableArray<string>>.Builder localBuilder = null;
ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>>.Builder constantBuilder = null;
var tuples = CustomDebugInfoReader.DecodeTupleElementNamesRecord(record);
foreach (var tuple in tuples)
{
var slotIndex = tuple.SlotIndex;
var elementNames = tuple.ElementNames;
if (slotIndex < 0)
{
constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder<LocalNameAndScope, ImmutableArray<string>>();
var localAndScope = new LocalNameAndScope(tuple.LocalName, tuple.ScopeStart, tuple.ScopeEnd);
constantBuilder[localAndScope] = elementNames;
}
else
{
localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder<int, ImmutableArray<string>>();
localBuilder[slotIndex] = elementNames;
}
}
if (localBuilder != null)
{
tupleLocalMap = localBuilder.ToImmutable();
}
if (constantBuilder != null)
{
tupleLocalConstantMap = constantBuilder.ToImmutable();
}
}
private static void ReadVisualBasicImportsDebugInfo(
ISymUnmanagedReader reader,
int methodToken,
int methodVersion,
out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
out string defaultNamespaceName)
{
importRecordGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(
methodToken,
KeyValuePair.Create(reader, methodVersion),
(token, arg) => GetImportStrings(arg.Key, token, arg.Value));
if (importStrings.IsDefault)
{
defaultNamespaceName = "";
return;
}
defaultNamespaceName = null;
var projectLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance();
var fileLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance();
foreach (string importString in importStrings)
{
Debug.Assert(importString != null);
if (importString.Length > 0 && importString[0] == '*')
{
string alias = null;
string target = null;
ImportTargetKind kind = 0;
VBImportScopeKind scope = 0;
if (!CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out target, out kind, out scope))
{
Debug.WriteLine($"Unable to parse import string '{importString}'");
continue;
}
else if (kind == ImportTargetKind.Defunct)
{
continue;
}
Debug.Assert(alias == null); // The default namespace is never aliased.
Debug.Assert(target != null);
Debug.Assert(kind == ImportTargetKind.DefaultNamespace);
// We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal
// implicitly uses the last one if there are multiple.
Debug.Assert(defaultNamespaceName == null);
defaultNamespaceName = target;
}
else
{
ImportRecord importRecord;
VBImportScopeKind scope = 0;
if (TryCreateImportRecordFromVisualBasicImportString(importString, out importRecord, out scope))
{
if (scope == VBImportScopeKind.Project)
{
projectLevelImportRecords.Add(importRecord);
}
else
{
Debug.Assert(scope == VBImportScopeKind.File || scope == VBImportScopeKind.Unspecified);
fileLevelImportRecords.Add(importRecord);
}
}
else
{
Debug.WriteLine($"Failed to parse import string {importString}");
}
}
}
importRecordGroups = ImmutableArray.Create(
fileLevelImportRecords.ToImmutableAndFree(),
projectLevelImportRecords.ToImmutableAndFree());
defaultNamespaceName = defaultNamespaceName ?? "";
}
private static bool TryCreateImportRecordFromVisualBasicImportString(string importString, out ImportRecord record, out VBImportScopeKind scope)
{
ImportTargetKind targetKind;
string alias;
string targetString;
if (CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out targetString, out targetKind, out scope))
{
record = new ImportRecord(
targetKind: targetKind,
alias: alias,
targetType: null,
targetString: targetString,
targetAssembly: null,
targetAssemblyAlias: null);
return true;
}
record = default(ImportRecord);
return false;
}
private static ILSpan GetReuseSpan(ArrayBuilder<ISymUnmanagedScope> scopes, int ilOffset, bool isEndInclusive)
{
return MethodContextReuseConstraints.CalculateReuseSpan(
ilOffset,
ILSpan.MaxValue,
scopes.Select(scope => new ILSpan((uint)scope.GetStartOffset(), (uint)(scope.GetEndOffset() + (isEndInclusive ? 1 : 0)))));
}
private static void GetConstants(
ArrayBuilder<TLocalSymbol> builder,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ArrayBuilder<ISymUnmanagedScope> scopes,
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMapOpt,
ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMapOpt)
{
foreach (var scope in scopes)
{
foreach (var constant in scope.GetConstants())
{
string name = constant.GetName();
object rawValue = constant.GetValue();
var signature = constant.GetSignature().ToImmutableArray();
TTypeSymbol type;
try
{
type = symbolProvider.DecodeLocalVariableType(signature);
}
catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException)
{
// ignore
continue;
}
if (type.Kind == SymbolKind.ErrorType)
{
continue;
}
ConstantValue constantValue = PdbHelpers.GetSymConstantValue(type, rawValue);
// TODO (https://github.com/dotnet/roslyn/issues/1815): report error properly when the symbol is used
if (constantValue.IsBad)
{
continue;
}
var dynamicFlags = default(ImmutableArray<bool>);
if (dynamicLocalConstantMapOpt != null)
{
dynamicLocalConstantMapOpt.TryGetValue(name, out dynamicFlags);
}
var tupleElementNames = default(ImmutableArray<string>);
if (tupleLocalConstantMapOpt != null)
{
int scopeStart = scope.GetStartOffset();
int scopeEnd = scope.GetEndOffset();
tupleLocalConstantMapOpt.TryGetValue(new LocalNameAndScope(name, scopeStart, scopeEnd), out tupleElementNames);
}
builder.Add(symbolProvider.GetLocalConstant(name, type, constantValue, dynamicFlags, tupleElementNames));
}
}
}
/// <summary>
/// Returns symbols for the locals emitted in the original method,
/// based on the local signatures from the IL and the names and
/// slots from the PDB. The actual locals are needed to ensure the
/// local slots in the generated method match the original.
/// </summary>
public static void GetLocals(
ArrayBuilder<TLocalSymbol> builder,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ImmutableArray<string> names,
ImmutableArray<LocalInfo<TTypeSymbol>> localInfo,
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMapOpt,
ImmutableDictionary<int, ImmutableArray<string>> tupleLocalConstantMapOpt)
{
if (localInfo.Length == 0)
{
// When debugging a .dmp without a heap, localInfo will be empty although
// names may be non-empty if there is a PDB. Since there's no type info, the
// locals are dropped. Note this means the local signature of any generated
// method will not match the original signature, so new locals will overlap
// original locals. That is ok since there is no live process for the debugger
// to update (any modified values exist in the debugger only).
return;
}
Debug.Assert(localInfo.Length >= names.Length);
for (int i = 0; i < localInfo.Length; i++)
{
string name = (i < names.Length) ? names[i] : null;
var dynamicFlags = default(ImmutableArray<bool>);
dynamicLocalMapOpt?.TryGetValue(i, out dynamicFlags);
var tupleElementNames = default(ImmutableArray<string>);
tupleLocalConstantMapOpt?.TryGetValue(i, out tupleElementNames);
builder.Add(symbolProvider.GetLocalVariable(name, i, localInfo[i], dynamicFlags, tupleElementNames));
}
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using System;
using System.Globalization;
namespace NodaTime.TimeZones
{
/// <summary>
/// Defines an offset within a year as an expression that can be used to reference multiple
/// years.
/// </summary>
/// <remarks>
/// <para>
/// A year offset defines a way of determining an offset into a year based on certain criteria.
/// The most basic is the month of the year and the day of the month. If only these two are
/// supplied then the offset is always the same day of each year. The only exception is if the
/// day is February 29th, then it only refers to those years that have a February 29th.
/// </para>
/// <para>
/// If the day of the week is specified then the offset determined by the month and day are
/// adjusted to the nearest day that falls on the given day of the week. If the month and day
/// fall on that day of the week then nothing changes. Otherwise the offset is moved forward or
/// backward up to 6 days to make the day fall on the correct day of the week. The direction the
/// offset is moved is determined by the <see cref="AdvanceDayOfWeek"/> property.
/// </para>
/// <para>
/// Finally the <see cref="Mode"/> property deterines whether the <see cref="TimeOfDay"/> value
/// is added to the calculated offset to generate an offset within the day.
/// </para>
/// <para>
/// Immutable, thread safe
/// </para>
/// </remarks>
internal sealed class ZoneYearOffset : IEquatable<ZoneYearOffset?>
{
private readonly int dayOfMonth;
private readonly int dayOfWeek;
private readonly int monthOfYear;
private readonly bool addDay;
/// <summary>
/// Gets the method by which offsets are added to Instants to get LocalInstants.
/// </summary>
public TransitionMode Mode { get; }
/// <summary>
/// Gets a value indicating whether [advance day of week].
/// </summary>
public bool AdvanceDayOfWeek { get; }
/// <summary>
/// Gets the time of day when the rule takes effect.
/// </summary>
public LocalTime TimeOfDay { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ZoneYearOffset"/> class.
/// </summary>
/// <param name="mode">The transition mode.</param>
/// <param name="monthOfYear">The month year offset.</param>
/// <param name="dayOfMonth">The day of month. Negatives count from end of month.</param>
/// <param name="dayOfWeek">The day of week. 0 means not set.</param>
/// <param name="advance">if set to <c>true</c> [advance].</param>
/// <param name="timeOfDay">The tick within the day.</param>
internal ZoneYearOffset(TransitionMode mode, int monthOfYear, int dayOfMonth, int dayOfWeek, bool advance, LocalTime timeOfDay)
: this(mode, monthOfYear, dayOfMonth, dayOfWeek, advance, timeOfDay, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZoneYearOffset"/> class.
/// </summary>
/// <param name="mode">The transition mode.</param>
/// <param name="monthOfYear">The month year offset.</param>
/// <param name="dayOfMonth">The day of month. Negatives count from end of month.</param>
/// <param name="dayOfWeek">The day of week. 0 means not set.</param>
/// <param name="advance">if set to <c>true</c> [advance].</param>
/// <param name="timeOfDay">The time of day at which the transition occurs.</param>
/// <param name="addDay">Whether to add an extra day (for 24:00 handling).</param>
internal ZoneYearOffset(TransitionMode mode, int monthOfYear, int dayOfMonth, int dayOfWeek, bool advance, LocalTime timeOfDay, bool addDay)
{
VerifyFieldValue(1, 12, "monthOfYear", monthOfYear, false);
VerifyFieldValue(1, 31, "dayOfMonth", dayOfMonth, true);
if (dayOfWeek != 0)
{
VerifyFieldValue(1, 7, "dayOfWeek", dayOfWeek, false);
}
this.Mode = mode;
this.monthOfYear = monthOfYear;
this.dayOfMonth = dayOfMonth;
this.dayOfWeek = dayOfWeek;
this.AdvanceDayOfWeek = advance;
this.TimeOfDay = timeOfDay;
this.addDay = addDay;
}
/// <summary>
/// Verifies the input value against the valid range of the calendar field.
/// </summary>
/// <remarks>
/// If this becomes more widely required, move to Preconditions.
/// </remarks>
/// <param name="minimum">The minimum valid value.</param>
/// <param name="maximum">The maximum valid value (inclusive).</param>
/// <param name="name">The name of the field for the error message.</param>
/// <param name="value">The value to check.</param>
/// <param name="allowNegated">if set to <c>true</c> all the range of value to be the negative as well.</param>
/// <exception cref="ArgumentOutOfRangeException">If the given value is not in the valid range of the given calendar field.</exception>
private static void VerifyFieldValue(long minimum, long maximum, string name, long value, bool allowNegated)
{
bool failed = false;
if (allowNegated && value < 0)
{
if (value < -maximum || -minimum < value)
{
failed = true;
}
}
else
{
if (value < minimum || maximum < value)
{
failed = true;
}
}
if (failed)
{
string range = allowNegated ? $"[{minimum}, {maximum}] or [{-maximum}, {-minimum}]" : $"[{minimum}, {maximum}]";
throw new ArgumentOutOfRangeException(name, value, $"{name} is not in the valid range: {range}");
}
}
#region IEquatable<ZoneYearOffset> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(ZoneYearOffset? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Mode == other.Mode &&
monthOfYear == other.monthOfYear &&
dayOfMonth == other.dayOfMonth &&
dayOfWeek == other.dayOfWeek &&
AdvanceDayOfWeek == other.AdvanceDayOfWeek &&
TimeOfDay == other.TimeOfDay &&
addDay == other.addDay;
}
#endregion
public override string ToString() =>
string.Format(CultureInfo.InvariantCulture,
"ZoneYearOffset[mode:{0} monthOfYear:{1} dayOfMonth:{2} dayOfWeek:{3} advance:{4} timeOfDay:{5:r} addDay:{6}]",
Mode, monthOfYear, dayOfMonth, dayOfWeek, AdvanceDayOfWeek, TimeOfDay, addDay);
/// <summary>
/// Returns the occurrence of this rule within the given year, as a LocalInstant.
/// </summary>
/// <remarks>LocalInstant is used here so that we can use the representation of "AfterMaxValue"
/// for December 31st 9999 24:00.</remarks>
internal LocalInstant GetOccurrenceForYear(int year)
{
unchecked
{
int actualDayOfMonth = dayOfMonth > 0 ? dayOfMonth : CalendarSystem.Iso.GetDaysInMonth(year, monthOfYear) + dayOfMonth + 1;
if (monthOfYear == 2 && dayOfMonth == 29 && !CalendarSystem.Iso.IsLeapYear(year))
{
// In zic.c, this would result in an error if dayOfWeek is 0 or AdvanceDayOfWeek is true.
// However, it's very convenient to be able to ask any rule for its occurrence in any year.
// We rely on genuine rules being well-written - and before releasing an nzd file we always
// check that it's in line with zic anyway. Ignoring the brokenness is simpler than fixing
// rules that are only in force for a single year.
actualDayOfMonth = 28; // We'll now look backwards for the right day-of-week.
}
LocalDate date = new LocalDate(year, monthOfYear, actualDayOfMonth);
if (dayOfWeek != 0)
{
// Optimized "go to next or previous occurrence of day or week". Try to do as few comparisons
// as possible, and only fetch DayOfWeek once. (If we call Next or Previous, it will work it out again.)
int currentDayOfWeek = (int) date.DayOfWeek;
if (currentDayOfWeek != dayOfWeek)
{
int diff = dayOfWeek - currentDayOfWeek;
if (diff > 0)
{
if (!AdvanceDayOfWeek)
{
diff -= 7;
}
}
else if (AdvanceDayOfWeek)
{
diff += 7;
}
date = date.PlusDays(diff);
}
}
if (addDay)
{
// Adding a day to the last representable day will fail, but we can return an infinite value instead.
if (year == 9999 && date.Month == 12 && date.Day == 31)
{
return LocalInstant.AfterMaxValue;
}
date = date.PlusDays(1);
}
return (date + TimeOfDay).ToLocalInstant();
}
}
/// <summary>
/// Writes this object to the given <see cref="IDateTimeZoneWriter"/>.
/// </summary>
/// <param name="writer">Where to send the output.</param>
internal void Write(IDateTimeZoneWriter writer)
{
// Flags contains four pieces of information in a single byte:
// 0MMDDDAP:
// - MM is the mode (0-2)
// - DDD is the day of week (0-7)
// - A is the AdvanceDayOfWeek
// - P is the "addDay" (24:00) flag
int flags = ((int) Mode << 5) |
(dayOfWeek << 2) |
(AdvanceDayOfWeek ? 2 : 0) |
(addDay ? 1 : 0);
writer.WriteByte((byte) flags);
writer.WriteCount(monthOfYear);
writer.WriteSignedCount(dayOfMonth);
// The time of day is written as a number of milliseconds historical reasons.
writer.WriteMilliseconds((int) (TimeOfDay.TickOfDay / NodaConstants.TicksPerMillisecond));
}
public static ZoneYearOffset Read(IDateTimeZoneReader reader)
{
Preconditions.CheckNotNull(reader, nameof(reader));
int flags = reader.ReadByte();
var mode = (TransitionMode) (flags >> 5);
var dayOfWeek = (flags >> 2) & 7;
var advance = (flags & 2) != 0;
var addDay = (flags & 1) != 0;
int monthOfYear = reader.ReadCount();
int dayOfMonth = reader.ReadSignedCount();
// The time of day is written as a number of milliseconds for historical reasons.
var timeOfDay = LocalTime.FromMillisecondsSinceMidnight(reader.ReadMilliseconds());
return new ZoneYearOffset(mode, monthOfYear, dayOfMonth, dayOfWeek, advance, timeOfDay, addDay);
}
/// <summary>
/// Returns the offset to use for this rule's <see cref="TransitionMode"/>.
/// The year/month/day/time for a rule is in a specific frame of reference:
/// UTC, "wall" or "standard".
/// </summary>
/// <param name="standardOffset">The standard offset.</param>
/// <param name="savings">The daylight savings adjustment.</param>
/// <returns>The base time offset as a <see cref="Duration"/>.</returns>
internal Offset GetRuleOffset(Offset standardOffset, Offset savings) => Mode switch
{
TransitionMode.Wall => standardOffset + savings,
TransitionMode.Standard => standardOffset,
_ => Offset.Zero
};
#region Object overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance;
/// otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => Equals(obj as ZoneYearOffset);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </returns>
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(Mode)
.Hash(monthOfYear)
.Hash(dayOfMonth)
.Hash(dayOfWeek)
.Hash(AdvanceDayOfWeek)
.Hash(TimeOfDay)
.Hash(addDay)
.Value;
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// A simple symbol.
/// </summary>
public class SimpleSymbol : OutlinedSymbol, ISimpleSymbol
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class.
/// </summary>
public SimpleSymbol()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class with the specified color.
/// </summary>
/// <param name="color">The color of the symbol.</param>
public SimpleSymbol(Color color)
: this()
{
Color = color;
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class with the specified color and shape.
/// </summary>
/// <param name="color">The color of the symbol.</param>
/// <param name="shape">The shape of the symbol.</param>
public SimpleSymbol(Color color, PointShape shape)
: this(color)
{
PointShape = shape;
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class with the specified color, shape and size. The size is used for
/// both the horizontal and vertical directions.
/// </summary>
/// <param name="color">The color of the symbol.</param>
/// <param name="shape">The shape of the symbol.</param>
/// <param name="size">The size of the symbol.</param>
public SimpleSymbol(Color color, PointShape shape, double size)
: this(color, shape)
{
Size = new Size2D(size, size);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the Color.
/// </summary>
[XmlIgnore]
public Color Color { get; set; }
/// <summary>
/// Gets or sets the opacity as a floating point value ranging from 0 to 1, where
/// 0 is fully transparent and 1 is fully opaque. This actually adjusts the alpha of the color value.
/// </summary>
[Serialize("Opacity")]
[ShallowCopy]
public float Opacity
{
get
{
return Color.A / 255F;
}
set
{
int alpha = (int)(value * 255);
if (alpha > 255) alpha = 255;
if (alpha < 0) alpha = 0;
if (alpha != Color.A)
{
Color = Color.FromArgb(alpha, Color);
}
}
}
/// <summary>
/// Gets or sets the PointTypes enumeration that describes how to draw the simple symbol.
/// </summary>
[Serialize("PointShapes")]
public PointShape PointShape { get; set; }
/// <summary>
/// Gets or sets the xml color. This is only provided because XML Serialization doesn't work for colors.
/// </summary>
[XmlElement("Color")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Serialize("XmlColor")]
[ShallowCopy]
public string XmlColor
{
get
{
return ColorTranslator.ToHtml(Color);
}
set
{
Color = ColorTranslator.FromHtml(value);
}
}
#endregion
#region Methods
/// <summary>
/// Draws an ellipse on the specified graphics surface.
/// </summary>
/// <param name="gp">The GraphicsPath to add this shape to.</param>
/// <param name="scaledSize">The size to fit the ellipse into (the ellipse will be centered at 0, 0).</param>
public static void AddEllipse(GraphicsPath gp, SizeF scaledSize)
{
PointF upperLeft = new PointF(-scaledSize.Width / 2, -scaledSize.Height / 2);
RectangleF destRect = new RectangleF(upperLeft, scaledSize);
gp.AddEllipse(destRect);
}
/// <summary>
/// Draws a regular polygon with equal sides. The first point will be located all the way to the right on the X axis.
/// </summary>
/// <param name="gp">Specifies the GraphicsPath surface to draw on.</param>
/// <param name="scaledSize">Specifies the SizeF to fit the polygon into.</param>
/// <param name="numSides">Specifies the integer number of sides that the polygon should have.</param>
public static void AddRegularPoly(GraphicsPath gp, SizeF scaledSize, int numSides)
{
PointF[] polyPoints = new PointF[numSides + 1];
// Instead of figuring out the points in cartesian, figure them out in angles and re-convert them.
for (int i = 0; i <= numSides; i++)
{
double ang = i * (2 * Math.PI) / numSides;
float x = Convert.ToSingle(Math.Cos(ang)) * scaledSize.Width / 2f;
float y = Convert.ToSingle(Math.Sin(ang)) * scaledSize.Height / 2f;
polyPoints[i] = new PointF(x, y);
}
gp.AddPolygon(polyPoints);
}
/// <summary>
/// Draws a 5 pointed star with the points having twice the radius as the bends.
/// </summary>
/// <param name="gp">The GraphicsPath to add the start to.</param>
/// <param name="scaledSize">The SizeF size to fit the Start to.</param>
public static void AddStar(GraphicsPath gp, SizeF scaledSize)
{
PointF[] polyPoints = new PointF[11];
GetStars(scaledSize, polyPoints);
gp.AddPolygon(polyPoints);
}
/// <summary>
/// Draws an ellipse on the specified graphics surface.
/// </summary>
/// <param name="g">The graphics surface to draw on.</param>
/// <param name="scaledBorderPen">The Pen to use for the border, or null if no border should be drawn.</param>
/// <param name="fillBrush">The Brush to use for the fill, or null if no fill should be drawn.</param>
/// <param name="scaledSize">The size to fit the ellipse into (the ellipse will be centered at 0, 0).</param>
public static void DrawEllipse(Graphics g, Pen scaledBorderPen, Brush fillBrush, SizeF scaledSize)
{
PointF upperLeft = new PointF(-scaledSize.Width / 2, -scaledSize.Height / 2);
RectangleF destRect = new RectangleF(upperLeft, scaledSize);
if (fillBrush != null)
{
g.FillEllipse(fillBrush, destRect);
}
if (scaledBorderPen != null)
{
g.DrawEllipse(scaledBorderPen, destRect);
}
}
/// <summary>
/// Draws a regular polygon with equal sides. The first point will be located all the way to the right on the X axis.
/// </summary>
/// <param name="g">Specifies the Graphics surface to draw on.</param>
/// <param name="scaledBorderPen">Specifies the Pen to use for the border.</param>
/// <param name="fillBrush">Specifies the Brush to use for to fill the shape.</param>
/// <param name="scaledSize">Specifies the SizeF to fit the polygon into.</param>
/// <param name="numSides">Specifies the integer number of sides that the polygon should have.</param>
public static void DrawRegularPoly(Graphics g, Pen scaledBorderPen, Brush fillBrush, SizeF scaledSize, int numSides)
{
PointF[] polyPoints = new PointF[numSides + 1];
// Instead of figuring out the points in cartesian, figure them out in angles and re-convert them.
for (int i = 0; i <= numSides; i++)
{
double ang = i * (2 * Math.PI) / numSides;
float x = Convert.ToSingle(Math.Cos(ang)) * scaledSize.Width / 2f;
float y = Convert.ToSingle(Math.Sin(ang)) * scaledSize.Height / 2f;
polyPoints[i] = new PointF(x, y);
}
if (fillBrush != null)
{
g.FillPolygon(fillBrush, polyPoints, FillMode.Alternate);
}
if (scaledBorderPen != null)
{
g.DrawPolygon(scaledBorderPen, polyPoints);
}
}
/// <summary>
/// Draws a 5 pointed star with the points having twice the radius as the bends.
/// </summary>
/// <param name="g">The Graphics surface to draw on.</param>
/// <param name="scaledBorderPen">The Pen to draw the border with.</param>
/// <param name="fillBrush">The Brush to use to fill the Star.</param>
/// <param name="scaledSize">The SizeF size to fit the Start to.</param>
public static void DrawStar(Graphics g, Pen scaledBorderPen, Brush fillBrush, SizeF scaledSize)
{
PointF[] polyPoints = new PointF[11];
GetStars(scaledSize, polyPoints);
if (fillBrush != null)
{
g.FillPolygon(fillBrush, polyPoints, FillMode.Alternate);
}
if (scaledBorderPen != null)
{
g.DrawPolygon(scaledBorderPen, polyPoints);
}
}
/// <summary>
/// Gets the font color of this symbol to represent the color of this symbol.
/// </summary>
/// <returns>The color of this symbol as a font.</returns>
public override Color GetColor()
{
return Color;
}
/// <summary>
/// Sets the fill color of this symbol to the specified color.
/// </summary>
/// <param name="color">The Color.</param>
public override void SetColor(Color color)
{
Color = color;
}
/// <summary>
/// Handles the specific drawing for this symbol.
/// </summary>
/// <param name="g">The System.Drawing.Graphics surface to draw with.</param>
/// <param name="scaleSize">A double controling the scaling of the symbol.</param>
protected override void OnDraw(Graphics g, double scaleSize)
{
if (scaleSize == 0) return;
if (Size.Width == 0 || Size.Height == 0) return;
SizeF size = new SizeF((float)(scaleSize * Size.Width), (float)(scaleSize * Size.Height));
Brush fillBrush = new SolidBrush(Color);
GraphicsPath gp = new GraphicsPath();
switch (PointShape)
{
case PointShape.Diamond:
AddRegularPoly(gp, size, 4);
break;
case PointShape.Ellipse:
AddEllipse(gp, size);
break;
case PointShape.Hexagon:
AddRegularPoly(gp, size, 6);
break;
case PointShape.Pentagon:
AddRegularPoly(gp, size, 5);
break;
case PointShape.Rectangle:
gp.AddRectangle(new RectangleF(-size.Width / 2, -size.Height / 2, size.Width, size.Height));
break;
case PointShape.Star:
AddStar(gp, size);
break;
case PointShape.Triangle:
AddRegularPoly(gp, size, 3);
break;
}
g.FillPath(fillBrush, gp);
OnDrawOutline(g, scaleSize, gp);
gp.Dispose();
}
/// <summary>
/// Occurs during the randomizing process.
/// </summary>
/// <param name="generator">The random genrator to use.</param>
protected override void OnRandomize(Random generator)
{
Color = generator.NextColor();
Opacity = generator.NextFloat();
PointShape = generator.NextEnum<PointShape>();
base.OnRandomize(generator);
}
private static void GetStars(SizeF scaledSize, PointF[] polyPoints)
{
for (int i = 0; i <= 10; i++)
{
double ang = i * Math.PI / 5;
float x = Convert.ToSingle(Math.Cos(ang)) * scaledSize.Width / 2f;
float y = Convert.ToSingle(Math.Sin(ang)) * scaledSize.Height / 2f;
if (i % 2 == 0)
{
x /= 2; // the shorter radius points of the star
y /= 2;
}
polyPoints[i] = new PointF(x, y);
}
}
private void Configure()
{
SymbolType = SymbolType.Simple;
Color = SymbologyGlobal.RandomColor();
PointShape = PointShape.Rectangle;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
class TestHelper
{
public static void Assert(bool exp,string msg="")
{
TestLibrary.Assert.IsTrue(exp, msg);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct S_INTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_UINTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_SHORTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_WORDArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_LONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public long[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_ULONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_DOUBLEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_FLOATArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_BYTEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_CHARArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_INTPTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public IntPtr[] arr;
}
//struct array in a struct
[StructLayout(LayoutKind.Sequential)]
public struct TestStruct
{
public int x;
public double d;
public long l;
public string str;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_StructArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_BOOLArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_INTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_UINTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_SHORTArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_WORDArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_LONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public long[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_ULONG64Array_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_DOUBLEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_FLOATArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_BYTEArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_CHARArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_LPSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_LPCSTRArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
//struct array in a class
[StructLayout(LayoutKind.Sequential)]
public class C_StructArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Sequential)]
public class C_BOOLArray_Seq
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_INTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_UINTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_SHORTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_WORDArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_LONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.I8)]
public long[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_ULONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_DOUBLEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_FLOATArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_BYTEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_CHARArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_LPSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_LPCSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
//struct array in a struct
[StructLayout(LayoutKind.Explicit)]
public struct S_StructArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public struct S_BOOLArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_INTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public int[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_UINTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public uint[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_SHORTArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public short[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_WORDArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ushort[] arr;
}
[StructLayout(LayoutKind.Explicit, Pack = 8)]
public class C_LONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public long[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_ULONG64Array_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public ulong[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_DOUBLEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public double[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_FLOATArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public float[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_BYTEArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public byte[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_CHARArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public char[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_LPSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_LPCSTRArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public string[] arr;
}
//struct array in a class
[StructLayout(LayoutKind.Explicit)]
public class C_StructArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public TestStruct[] arr;
}
[StructLayout(LayoutKind.Explicit)]
public class C_BOOLArray_Exp
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)]
public bool[] arr;
}
class Test
{
//for RunTest1
[DllImport("MarshalArrayByValNative")]
static extern bool TakeIntArraySeqStructByVal([In]S_INTArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeUIntArraySeqStructByVal([In]S_UINTArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeShortArraySeqStructByVal([In]S_SHORTArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeWordArraySeqStructByVal([In]S_WORDArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLong64ArraySeqStructByVal([In]S_LONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeULong64ArraySeqStructByVal([In]S_ULONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeDoubleArraySeqStructByVal([In]S_DOUBLEArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeFloatArraySeqStructByVal([In]S_FLOATArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeByteArraySeqStructByVal([In]S_BYTEArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeCharArraySeqStructByVal([In]S_CHARArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeIntPtrArraySeqStructByVal([In]S_INTPTRArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeStructArraySeqStructByVal([In]S_StructArray_Seq s, int size);
//for RunTest2
[DllImport("MarshalArrayByValNative")]
static extern bool TakeIntArraySeqClassByVal([In]C_INTArray_Seq c, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeUIntArraySeqClassByVal([In]C_UINTArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeShortArraySeqClassByVal([In]C_SHORTArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeWordArraySeqClassByVal([In]C_WORDArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLong64ArraySeqClassByVal([In]C_LONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeULong64ArraySeqClassByVal([In]C_ULONG64Array_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeDoubleArraySeqClassByVal([In]C_DOUBLEArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeFloatArraySeqClassByVal([In]C_FLOATArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeByteArraySeqClassByVal([In]C_BYTEArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeCharArraySeqClassByVal([In]C_CHARArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLPSTRArraySeqClassByVal([In]C_LPSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLPCSTRArraySeqClassByVal([In]C_LPCSTRArray_Seq s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeStructArraySeqClassByVal([In]C_StructArray_Seq s, int size);
//for RunTest3
[DllImport("MarshalArrayByValNative")]
static extern bool TakeIntArrayExpStructByVal([In]S_INTArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeUIntArrayExpStructByVal([In]S_UINTArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeShortArrayExpStructByVal([In]S_SHORTArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeWordArrayExpStructByVal([In]S_WORDArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLong64ArrayExpStructByVal([In]S_LONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeULong64ArrayExpStructByVal([In]S_ULONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeDoubleArrayExpStructByVal([In]S_DOUBLEArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeFloatArrayExpStructByVal([In]S_FLOATArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeByteArrayExpStructByVal([In]S_BYTEArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeCharArrayExpStructByVal([In]S_CHARArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLPSTRArrayExpStructByVal([In]S_LPSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLPCSTRArrayExpStructByVal([In]S_LPCSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeStructArrayExpStructByVal([In]S_StructArray_Exp s, int size);
//for RunTest4
[DllImport("MarshalArrayByValNative")]
static extern bool TakeIntArrayExpClassByVal([In]C_INTArray_Exp c, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeUIntArrayExpClassByVal([In]C_UINTArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeShortArrayExpClassByVal([In]C_SHORTArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeWordArrayExpClassByVal([In]C_WORDArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLong64ArrayExpClassByVal([In]C_LONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeULong64ArrayExpClassByVal([In]C_ULONG64Array_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeDoubleArrayExpClassByVal([In]C_DOUBLEArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeFloatArrayExpClassByVal([In]C_FLOATArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeByteArrayExpClassByVal([In]C_BYTEArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeCharArrayExpClassByVal([In]C_CHARArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLPSTRArrayExpClassByVal([In]C_LPSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeLPCSTRArrayExpClassByVal([In]C_LPCSTRArray_Exp s, int size);
[DllImport("MarshalArrayByValNative")]
static extern bool TakeStructArrayExpClassByVal([In]C_StructArray_Exp s, int size);
//for RunTest5
//get struct on C++ side as sequential class
[DllImport("MarshalArrayByValNative")]
static extern C_INTArray_Seq S_INTArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_UINTArray_Seq S_UINTArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_SHORTArray_Seq S_SHORTArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_WORDArray_Seq S_WORDArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_LONG64Array_Seq S_LONG64Array_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_ULONG64Array_Seq S_ULONG64Array_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_DOUBLEArray_Seq S_DOUBLEArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_FLOATArray_Seq S_FLOATArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_BYTEArray_Seq S_BYTEArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_CHARArray_Seq S_CHARArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_LPSTRArray_Seq S_LPSTRArray_Ret();
[DllImport("MarshalArrayByValNative")]
static extern C_StructArray_Seq S_StructArray_Ret();
//for RunTest6
//get struct on C++ side as explicit class
[DllImport("MarshalArrayByValNative", EntryPoint = "S_INTArray_Ret")]
static extern C_INTArray_Exp S_INTArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_UINTArray_Ret")]
static extern C_UINTArray_Exp S_UINTArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_SHORTArray_Ret")]
static extern C_SHORTArray_Exp S_SHORTArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_WORDArray_Ret")]
static extern C_WORDArray_Exp S_WORDArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_LONG64Array_Ret")]
static extern C_LONG64Array_Exp S_LONG64Array_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_ULONG64Array_Ret")]
static extern C_ULONG64Array_Exp S_ULONG64Array_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_DOUBLEArray_Ret")]
static extern C_DOUBLEArray_Exp S_DOUBLEArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_FLOATArray_Ret")]
static extern C_FLOATArray_Exp S_FLOATArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_BYTEArray_Ret")]
static extern C_BYTEArray_Exp S_BYTEArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_CHARArray_Ret")]
static extern C_CHARArray_Exp S_CHARArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_LPSTRArray_Ret")]
static extern C_LPSTRArray_Exp S_LPSTRArray_Ret2();
[DllImport("MarshalArrayByValNative", EntryPoint = "S_StructArray_Ret")]
static extern C_StructArray_Exp S_StructArray_Ret2();
internal const int ARRAY_SIZE = 100;
static T[] InitArray<T>(int size)
{
T[] array = new T[size];
for (int i = 0; i < array.Length; i++)
array[i] = (T)Convert.ChangeType(i, typeof(T));
return array;
}
static TestStruct[] InitStructArray(int size)
{
TestStruct[] array = new TestStruct[size];
for (int i = 0; i < array.Length; i++)
{
array[i].x = i;
array[i].d = i;
array[i].l = i;
array[i].str = i.ToString();
}
return array;
}
static bool[] InitBoolArray(int size)
{
bool[] array = new bool[size];
for (int i = 0; i < array.Length; i++)
{
if (i % 2 == 0)
array[i] = true;
else
array[i] = false;
}
return array;
}
static IntPtr[] InitIntPtrArray(int size)
{
IntPtr[] array = new IntPtr[size];
for (int i = 0; i < array.Length; i++)
array[i] = new IntPtr(i);
return array;
}
static bool Equals<T>(T[] arr1, T[] arr2)
{
if (arr1 == null && arr2 == null)
return true;
else if (arr1 == null && arr2 != null)
return false;
else if (arr1 != null && arr2 == null)
return false;
else if (arr1.Length != arr2.Length)
return false;
for (int i = 0; i < arr2.Length; ++i)
{
if (!Object.Equals(arr1[i], arr2[i]))
{
Console.WriteLine("Array marshaling error, when type is {0}", typeof(T));
Console.WriteLine("Expected: {0}, Actual: {1}", arr1[i], arr2[i]);
return false;
}
}
return true;
}
static bool TestStructEquals(TestStruct[] tsArr1, TestStruct[] tsArr2)
{
if (tsArr1 == null && tsArr2 == null)
return true;
else if (tsArr1 == null && tsArr2 != null)
return false;
else if (tsArr1 != null && tsArr2 == null)
return false;
else if (tsArr1.Length != tsArr2.Length)
return false;
bool result = true;
for (int i = 0; i < tsArr2.Length; i++)
{
result = (tsArr1[i].x == tsArr2[i].x &&
tsArr1[i].d == tsArr2[i].d &&
tsArr1[i].l == tsArr2[i].l &&
tsArr1[i].str == tsArr2[i].str) && result;
}
return result;
}
static bool RunTest1(string report)
{
Console.WriteLine(report);
S_INTArray_Seq s1 = new S_INTArray_Seq();
s1.arr = InitArray<int>(ARRAY_SIZE);
TestHelper.Assert(TakeIntArraySeqStructByVal(s1, s1.arr.Length), "TakeIntArraySeqStructByVal");
S_UINTArray_Seq s2 = new S_UINTArray_Seq();
s2.arr = InitArray<uint>(ARRAY_SIZE);
TestHelper.Assert(TakeUIntArraySeqStructByVal(s2, s2.arr.Length), "TakeUIntArraySeqStructByVal");
S_SHORTArray_Seq s3 = new S_SHORTArray_Seq();
s3.arr = InitArray<short>(ARRAY_SIZE);
TestHelper.Assert(TakeShortArraySeqStructByVal(s3, s3.arr.Length), "TakeShortArraySeqStructByVal");
S_WORDArray_Seq s4 = new S_WORDArray_Seq();
s4.arr = InitArray<ushort>(ARRAY_SIZE);
TestHelper.Assert(TakeWordArraySeqStructByVal(s4, s4.arr.Length), "TakeWordArraySeqStructByVal");
S_LONG64Array_Seq s5 = new S_LONG64Array_Seq();
s5.arr = InitArray<long>(ARRAY_SIZE);
TestHelper.Assert(TakeLong64ArraySeqStructByVal(s5, s5.arr.Length), "TakeLong64ArraySeqStructByVal");
S_ULONG64Array_Seq s6 = new S_ULONG64Array_Seq();
s6.arr = InitArray<ulong>(ARRAY_SIZE);
TestHelper.Assert(TakeULong64ArraySeqStructByVal(s6, s6.arr.Length), "TakeULong64ArraySeqStructByVal");
S_DOUBLEArray_Seq s7 = new S_DOUBLEArray_Seq();
s7.arr = InitArray<double>(ARRAY_SIZE);
TestHelper.Assert(TakeDoubleArraySeqStructByVal(s7, s7.arr.Length), "TakeDoubleArraySeqStructByVal");
S_FLOATArray_Seq s8 = new S_FLOATArray_Seq();
s8.arr = InitArray<float>(ARRAY_SIZE);
TestHelper.Assert(TakeFloatArraySeqStructByVal(s8, s8.arr.Length), "TakeFloatArraySeqStructByVal");
S_BYTEArray_Seq s9 = new S_BYTEArray_Seq();
s9.arr = InitArray<byte>(ARRAY_SIZE);
TestHelper.Assert(TakeByteArraySeqStructByVal(s9, s9.arr.Length), "TakeByteArraySeqStructByVal");
S_CHARArray_Seq s10 = new S_CHARArray_Seq();
s10.arr = InitArray<char>(ARRAY_SIZE);
TestHelper.Assert(TakeCharArraySeqStructByVal(s10, s10.arr.Length), "TakeCharArraySeqStructByVal");
S_INTPTRArray_Seq s11 = new S_INTPTRArray_Seq();
s11.arr = InitIntPtrArray(ARRAY_SIZE);
TestHelper.Assert(TakeIntPtrArraySeqStructByVal(s11, s11.arr.Length), "TakeIntPtrArraySeqStructByVal");
#if NONWINDOWS_BUG
S_StructArray_Seq s14 = new S_StructArray_Seq();
s14.arr = InitStructArray(ARRAY_SIZE);
TestHelper.Assert(TakeStructArraySeqStructByVal(s14, s14.arr.Length),"TakeStructArraySeqStructByVal");
#endif
return true;
}
static bool RunTest2(string report)
{
C_INTArray_Seq c1 = new C_INTArray_Seq();
c1.arr = InitArray<int>(ARRAY_SIZE);
TestHelper.Assert(TakeIntArraySeqClassByVal(c1, c1.arr.Length));
C_UINTArray_Seq c2 = new C_UINTArray_Seq();
c2.arr = InitArray<uint>(ARRAY_SIZE);
TestHelper.Assert(TakeUIntArraySeqClassByVal(c2, c2.arr.Length));
C_SHORTArray_Seq c3 = new C_SHORTArray_Seq();
c3.arr = InitArray<short>(ARRAY_SIZE);
TestHelper.Assert(TakeShortArraySeqClassByVal(c3, c3.arr.Length));
C_WORDArray_Seq c4 = new C_WORDArray_Seq();
c4.arr = InitArray<ushort>(ARRAY_SIZE);
TestHelper.Assert(TakeWordArraySeqClassByVal(c4, c4.arr.Length));
C_LONG64Array_Seq c5 = new C_LONG64Array_Seq();
c5.arr = InitArray<long>(ARRAY_SIZE);
TestHelper.Assert(TakeLong64ArraySeqClassByVal(c5, c5.arr.Length));
C_ULONG64Array_Seq c6 = new C_ULONG64Array_Seq();
c6.arr = InitArray<ulong>(ARRAY_SIZE);
TestHelper.Assert(TakeULong64ArraySeqClassByVal(c6, c6.arr.Length));
C_DOUBLEArray_Seq c7 = new C_DOUBLEArray_Seq();
c7.arr = InitArray<double>(ARRAY_SIZE);
TestHelper.Assert(TakeDoubleArraySeqClassByVal(c7, c7.arr.Length));
C_FLOATArray_Seq c8 = new C_FLOATArray_Seq();
c8.arr = InitArray<float>(ARRAY_SIZE);
TestHelper.Assert(TakeFloatArraySeqClassByVal(c8, c8.arr.Length));
C_BYTEArray_Seq c9 = new C_BYTEArray_Seq();
c9.arr = InitArray<byte>(ARRAY_SIZE);
TestHelper.Assert(TakeByteArraySeqClassByVal(c9, c9.arr.Length));
C_CHARArray_Seq c10 = new C_CHARArray_Seq();
c10.arr = InitArray<char>(ARRAY_SIZE);
TestHelper.Assert(TakeCharArraySeqClassByVal(c10, c10.arr.Length));
C_LPSTRArray_Seq c11 = new C_LPSTRArray_Seq();
c11.arr = InitArray<string>(ARRAY_SIZE);
TestHelper.Assert(TakeLPSTRArraySeqClassByVal(c11, c11.arr.Length));
C_LPCSTRArray_Seq c12 = new C_LPCSTRArray_Seq();
c12.arr = InitArray<string>(ARRAY_SIZE);
TestHelper.Assert(TakeLPCSTRArraySeqClassByVal(c12, c12.arr.Length));
#if NONWINDOWS_BUG
C_StructArray_Seq c14 = new C_StructArray_Seq();
c14.arr = InitStructArray(ARRAY_SIZE);
TestHelper.Assert(TakeStructArraySeqClassByVal(c14, c14.arr.Length));
#endif
return true;
}
static bool RunTest3(string report)
{
Console.WriteLine(report);
S_INTArray_Exp s1 = new S_INTArray_Exp();
s1.arr = InitArray<int>(ARRAY_SIZE);
TestHelper.Assert(TakeIntArrayExpStructByVal(s1, s1.arr.Length), "TakeIntArrayExpStructByVal");
S_UINTArray_Exp s2 = new S_UINTArray_Exp();
s2.arr = InitArray<uint>(ARRAY_SIZE);
TestHelper.Assert(TakeUIntArrayExpStructByVal(s2, s2.arr.Length), "TakeUIntArrayExpStructByVal");
S_SHORTArray_Exp s3 = new S_SHORTArray_Exp();
s3.arr = InitArray<short>(ARRAY_SIZE);
TestHelper.Assert(TakeShortArrayExpStructByVal(s3, s3.arr.Length), "TakeShortArrayExpStructByVal");
S_WORDArray_Exp s4 = new S_WORDArray_Exp();
s4.arr = InitArray<ushort>(ARRAY_SIZE);
TestHelper.Assert(TakeWordArrayExpStructByVal(s4, s4.arr.Length), "TakeWordArrayExpStructByVal");
S_LONG64Array_Exp s5 = new S_LONG64Array_Exp();
s5.arr = InitArray<long>(ARRAY_SIZE);
TestHelper.Assert(TakeLong64ArrayExpStructByVal(s5, s5.arr.Length), "TakeLong64ArrayExpStructByVal");
S_ULONG64Array_Exp s6 = new S_ULONG64Array_Exp();
s6.arr = InitArray<ulong>(ARRAY_SIZE);
TestHelper.Assert(TakeULong64ArrayExpStructByVal(s6, s6.arr.Length), "TakeULong64ArrayExpStructByVal");
S_DOUBLEArray_Exp s7 = new S_DOUBLEArray_Exp();
s7.arr = InitArray<double>(ARRAY_SIZE);
TestHelper.Assert(TakeDoubleArrayExpStructByVal(s7, s7.arr.Length), "TakeDoubleArrayExpStructByVal");
S_FLOATArray_Exp s8 = new S_FLOATArray_Exp();
s8.arr = InitArray<float>(ARRAY_SIZE);
TestHelper.Assert(TakeFloatArrayExpStructByVal(s8, s8.arr.Length), "TakeFloatArrayExpStructByVal");
S_BYTEArray_Exp s9 = new S_BYTEArray_Exp();
s9.arr = InitArray<byte>(ARRAY_SIZE);
TestHelper.Assert(TakeByteArrayExpStructByVal(s9, s9.arr.Length), "TakeByteArrayExpStructByVal");
S_CHARArray_Exp s10 = new S_CHARArray_Exp();
s10.arr = InitArray<char>(ARRAY_SIZE);
TestHelper.Assert(TakeCharArrayExpStructByVal(s10, s10.arr.Length), "TakeCharArrayExpStructByVal");
S_LPSTRArray_Exp s11 = new S_LPSTRArray_Exp();
s11.arr = InitArray<string>(ARRAY_SIZE);
TestHelper.Assert(TakeLPSTRArrayExpStructByVal(s11, s11.arr.Length));
S_LPCSTRArray_Exp s12 = new S_LPCSTRArray_Exp();
s12.arr = InitArray<string>(ARRAY_SIZE);
TestHelper.Assert(TakeLPCSTRArrayExpStructByVal(s12, s12.arr.Length));
#if NONWINDOWS_BUG
S_StructArray_Exp s14 = new S_StructArray_Exp();
s14.arr = InitStructArray(ARRAY_SIZE);
TestHelper.Assert(TakeStructArrayExpStructByVal(s14, s14.arr.Length));
#endif
return true;
}
static bool RunTest4(string report)
{
Console.WriteLine(report);
C_INTArray_Exp c1 = new C_INTArray_Exp();
c1.arr = InitArray<int>(ARRAY_SIZE);
TestHelper.Assert(TakeIntArrayExpClassByVal(c1, c1.arr.Length));
C_UINTArray_Exp c2 = new C_UINTArray_Exp();
c2.arr = InitArray<uint>(ARRAY_SIZE);
TestHelper.Assert(TakeUIntArrayExpClassByVal(c2, c2.arr.Length));
C_SHORTArray_Exp c3 = new C_SHORTArray_Exp();
c3.arr = InitArray<short>(ARRAY_SIZE);
TestHelper.Assert(TakeShortArrayExpClassByVal(c3, c3.arr.Length));
C_WORDArray_Exp c4 = new C_WORDArray_Exp();
c4.arr = InitArray<ushort>(ARRAY_SIZE);
TestHelper.Assert(TakeWordArrayExpClassByVal(c4, c4.arr.Length));
C_LONG64Array_Exp c5 = new C_LONG64Array_Exp();
c5.arr = InitArray<long>(ARRAY_SIZE);
TestHelper.Assert(TakeLong64ArrayExpClassByVal(c5, c5.arr.Length));
C_ULONG64Array_Exp c6 = new C_ULONG64Array_Exp();
c6.arr = InitArray<ulong>(ARRAY_SIZE);
TestHelper.Assert(TakeULong64ArrayExpClassByVal(c6, c6.arr.Length));
C_DOUBLEArray_Exp c7 = new C_DOUBLEArray_Exp();
c7.arr = InitArray<double>(ARRAY_SIZE);
TestHelper.Assert(TakeDoubleArrayExpClassByVal(c7, c7.arr.Length));
C_FLOATArray_Exp c8 = new C_FLOATArray_Exp();
c8.arr = InitArray<float>(ARRAY_SIZE);
TestHelper.Assert(TakeFloatArrayExpClassByVal(c8, c8.arr.Length));
C_BYTEArray_Exp c9 = new C_BYTEArray_Exp();
c9.arr = InitArray<byte>(ARRAY_SIZE);
TestHelper.Assert(TakeByteArrayExpClassByVal(c9, c9.arr.Length));
C_CHARArray_Exp c10 = new C_CHARArray_Exp();
c10.arr = InitArray<char>(ARRAY_SIZE);
TestHelper.Assert(TakeCharArrayExpClassByVal(c10, c10.arr.Length));
C_LPSTRArray_Exp c11 = new C_LPSTRArray_Exp();
c11.arr = InitArray<string>(ARRAY_SIZE);
TestHelper.Assert(TakeLPSTRArrayExpClassByVal(c11, c11.arr.Length));
C_LPCSTRArray_Exp c12 = new C_LPCSTRArray_Exp();
c12.arr = InitArray<string>(ARRAY_SIZE);
TestHelper.Assert(TakeLPCSTRArrayExpClassByVal(c12, c12.arr.Length));
#if NONWINDOWS_BUG
C_StructArray_Exp c14 = new C_StructArray_Exp();
c14.arr = InitStructArray(ARRAY_SIZE);
TestHelper.Assert(TakeStructArrayExpClassByVal(c14, c14.arr.Length));
#endif
return true;
}
static bool RunTest5(string report)
{
C_INTArray_Seq retval1 = S_INTArray_Ret();
TestHelper.Assert(Equals(InitArray<int>(ARRAY_SIZE), retval1.arr));
C_UINTArray_Seq retval2 = S_UINTArray_Ret();
TestHelper.Assert(Equals(InitArray<uint>(ARRAY_SIZE), retval2.arr));
C_SHORTArray_Seq retval3 = S_SHORTArray_Ret();
TestHelper.Assert(Equals(InitArray<short>(ARRAY_SIZE), retval3.arr));
C_WORDArray_Seq retval4 = S_WORDArray_Ret();
TestHelper.Assert(Equals(InitArray<ushort>(ARRAY_SIZE), retval4.arr));
C_LONG64Array_Seq retval5 = S_LONG64Array_Ret();
TestHelper.Assert(Equals(InitArray<long>(ARRAY_SIZE), retval5.arr));
C_ULONG64Array_Seq retval6 = S_ULONG64Array_Ret();
TestHelper.Assert(Equals(InitArray<ulong>(ARRAY_SIZE), retval6.arr));
C_DOUBLEArray_Seq retval7 = S_DOUBLEArray_Ret();
TestHelper.Assert(Equals(InitArray<double>(ARRAY_SIZE), retval7.arr));
C_FLOATArray_Seq retval8 = S_FLOATArray_Ret();
TestHelper.Assert(Equals(InitArray<float>(ARRAY_SIZE), retval8.arr));
C_BYTEArray_Seq retval9 = S_BYTEArray_Ret();
TestHelper.Assert(Equals(InitArray<byte>(ARRAY_SIZE), retval9.arr));
C_CHARArray_Seq retval10 = S_CHARArray_Ret();
TestHelper.Assert(Equals(InitArray<char>(ARRAY_SIZE), retval10.arr));
C_LPSTRArray_Seq retval11 = S_LPSTRArray_Ret();
TestHelper.Assert(Equals(InitArray<string>(ARRAY_SIZE), retval11.arr));
#if NONWINDOWS_BUG
C_StructArray_Seq retval13 = S_StructArray_Ret();
TestHelper.Assert(TestStructEquals(InitStructArray(ARRAY_SIZE), retval13.arr));
#endif
return true;
}
static bool RunTest6(string report)
{
C_INTArray_Exp retval1 = S_INTArray_Ret2();
TestHelper.Assert(Equals(InitArray<int>(ARRAY_SIZE), retval1.arr));
C_UINTArray_Exp retval2 = S_UINTArray_Ret2();
TestHelper.Assert(Equals(InitArray<uint>(ARRAY_SIZE), retval2.arr));
C_SHORTArray_Exp retval3 = S_SHORTArray_Ret2();
TestHelper.Assert(Equals(InitArray<short>(ARRAY_SIZE), retval3.arr));
C_WORDArray_Exp retval4 = S_WORDArray_Ret2();
TestHelper.Assert(Equals(InitArray<ushort>(ARRAY_SIZE), retval4.arr));
C_LONG64Array_Exp retval5 = S_LONG64Array_Ret2();
TestHelper.Assert(Equals(InitArray<long>(ARRAY_SIZE), retval5.arr));
C_ULONG64Array_Exp retval6 = S_ULONG64Array_Ret2();
TestHelper.Assert(Equals(InitArray<ulong>(ARRAY_SIZE), retval6.arr));
C_DOUBLEArray_Exp retval7 = S_DOUBLEArray_Ret2();
TestHelper.Assert(Equals(InitArray<double>(ARRAY_SIZE), retval7.arr));
C_FLOATArray_Exp retval8 = S_FLOATArray_Ret2();
TestHelper.Assert(Equals(InitArray<float>(ARRAY_SIZE), retval8.arr));
C_BYTEArray_Exp retval9 = S_BYTEArray_Ret2();
TestHelper.Assert(Equals(InitArray<byte>(ARRAY_SIZE), retval9.arr));
C_CHARArray_Exp retval10 = S_CHARArray_Ret2();
TestHelper.Assert(Equals(InitArray<char>(ARRAY_SIZE), retval10.arr));
C_LPSTRArray_Exp retval11 = S_LPSTRArray_Ret2();
TestHelper.Assert(Equals(InitArray<string>(ARRAY_SIZE), retval11.arr));
#if NONWINDOWS_BUG
C_StructArray_Exp retval13 = S_StructArray_Ret2();
TestHelper.Assert(TestStructEquals(InitStructArray(ARRAY_SIZE), retval13.arr));
#endif
return true;
}
static int Main(string[] args)
{
RunTest1("RunTest1 : Marshal array as field as ByValArray in sequential struct as parameter.");
RunTest2("RunTest2 : Marshal array as field as ByValArray in sequential class as parameter.");
RunTest3("RunTest3 : Marshal array as field as ByValArray in explicit struct as parameter.");
RunTest4("RunTest4 : Marshal array as field as ByValArray in explicit class as parameter.");
RunTest5("RunTest5 : Marshal array as field as ByValArray in sequential class as return type.");
RunTest6("RunTest6 : Marshal array as field as ByValArray in explicit class as return type.");
return 100;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Collections;
using System.Windows.Forms;
using DowUtils;
namespace Factotum{
public class EPipeSchedule : IEntity
{
public static event EventHandler<EntityChangedEventArgs> Changed;
protected virtual void OnChanged(Guid? ID)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<EntityChangedEventArgs> temp = Changed;
if (temp != null)
temp(this, new EntityChangedEventArgs(ID));
}
// Mapped database columns
// Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not).
// Use int?, decimal?, etc for numbers (whether they're nullable or not).
// Strings, images, etc, are reference types already
private Guid? PslDBid;
private decimal? PslOd;
private decimal? PslNomWall;
private string PslSchedule;
private decimal? PslNomDia;
private bool PslIsLclChg;
// Textbox limits
public static int PslOdCharLimit = 8;
public static int PslNomWallCharLimit = 7;
public static int PslScheduleCharLimit = 20;
public static int PslNomDiaCharLimit = 7;
// Field-specific error message strings (normally just needed for textbox data)
private string PslOdErrMsg;
private string PslNomWallErrMsg;
private string PslScheduleErrMsg;
private string PslNomDiaErrMsg;
// Form level validation message
private string PslErrMsg;
//--------------------------------------------------------
// Field Properties
//--------------------------------------------------------
// Primary key accessor
public Guid? ID
{
get { return PslDBid; }
}
public decimal? PipeScheduleOd
{
get { return PslOd; }
set { PslOd = value; }
}
public decimal? PipeScheduleNomWall
{
get { return PslNomWall; }
set { PslNomWall = value; }
}
public string PipeScheduleSchedule
{
get { return PslSchedule; }
set { PslSchedule = Util.NullifyEmpty(value); }
}
public decimal? PipeScheduleNomDia
{
get { return PslNomDia; }
set { PslNomDia = value; }
}
public bool PipeScheduleIsLclChg
{
get { return PslIsLclChg; }
set { PslIsLclChg = value; }
}
// Set the property to null to set the default string
// or set the property to a specific string.
public string PipeScheduleAndNomDiaText
{
get
{
string pipeScheduleAndNomDiaText;
if (PslSchedule != null && PslNomDia != null)
{
pipeScheduleAndNomDiaText = string.Format("{0} - {1:0.000} in. Nom",
new object[] { PslSchedule, PslNomDia });
}
else
{
pipeScheduleAndNomDiaText = "N/A";
}
return pipeScheduleAndNomDiaText;
}
}
//-----------------------------------------------------------------
// Field Level Error Messages.
// Include one for every text column
// In cases where we need to ensure data consistency, we may need
// them for other types.
//-----------------------------------------------------------------
public string PipeScheduleOdErrMsg
{
get { return PslOdErrMsg; }
}
public string PipeScheduleNomWallErrMsg
{
get { return PslNomWallErrMsg; }
}
public string PipeScheduleScheduleErrMsg
{
get { return PslScheduleErrMsg; }
}
public string PipeScheduleNomDiaErrMsg
{
get { return PslNomDiaErrMsg; }
}
//--------------------------------------
// Form level Error Message
//--------------------------------------
public string PipeScheduleErrMsg
{
get { return PslErrMsg; }
set { PslErrMsg = Util.NullifyEmpty(value); }
}
//--------------------------------------
// Textbox Name Length Validation
//--------------------------------------
public bool PipeScheduleOdLengthOk(string s)
{
if (s == null) return true;
if (s.Length > PslOdCharLimit)
{
PslOdErrMsg = string.Format("Pipe Schedule OD's cannot exceed {0} characters", PslOdCharLimit);
return false;
}
else
{
PslOdErrMsg = null;
return true;
}
}
public bool PipeScheduleNomWallLengthOk(string s)
{
if (s == null) return true;
if (s.Length > PslNomWallCharLimit)
{
PslNomWallErrMsg = string.Format("Pipe Schedule Nominal Wall thicknesses cannot exceed {0} characters", PslNomWallCharLimit);
return false;
}
else
{
PslNomWallErrMsg = null;
return true;
}
}
public bool PipeScheduleScheduleLengthOk(string s)
{
if (s == null) return true;
if (s.Length > PslScheduleCharLimit)
{
PslScheduleErrMsg = string.Format("Pipe Schedules cannot exceed {0} characters", PslScheduleCharLimit);
return false;
}
else
{
PslScheduleErrMsg = null;
return true;
}
}
public bool PipeScheduleNomDiaLengthOk(string s)
{
if (s == null) return true;
if (s.Length > PslNomDiaCharLimit)
{
PslNomDiaErrMsg = string.Format("Pipe Schedule Nominal Diameters cannot exceed {0} characters", PslNomDiaCharLimit);
return false;
}
else
{
PslNomDiaErrMsg = null;
return true;
}
}
//--------------------------------------
// Field-Specific Validation
// sets and clears error messages
//--------------------------------------
public bool PipeScheduleOdValid(string value)
{
decimal result;
if (Util.IsNullOrEmpty(value))
{
PslOdErrMsg = null;
return true;
}
if (decimal.TryParse(value, out result) && result > 0)
{
PslOdErrMsg = null;
return true;
}
PslOdErrMsg = string.Format("Please enter a positive number");
return false;
}
public bool PipeScheduleNomWallValid(string value)
{
decimal result;
if (Util.IsNullOrEmpty(value))
{
PslNomWallErrMsg = null;
return true;
}
if (decimal.TryParse(value, out result) && result > 0)
{
PslNomWallErrMsg = null;
return true;
}
PslNomWallErrMsg = string.Format("Please enter a positive number");
return false;
}
public bool PipeScheduleScheduleValid(string value)
{
if (!PipeScheduleScheduleLengthOk(value)) return false;
PslScheduleErrMsg = null;
return true;
}
public bool PipeScheduleNomDiaValid(string value)
{
decimal result;
if (Util.IsNullOrEmpty(value))
{
PslNomDiaErrMsg = null;
return true;
}
if (decimal.TryParse(value, out result) && result > 0)
{
PslNomDiaErrMsg = null;
return true;
}
PslNomDiaErrMsg = string.Format("Please enter a positive number");
return false;
}
//--------------------------------------
// Constructors
//--------------------------------------
// Default constructor. Field defaults must be set here.
// Any defaults set by the database will be overridden.
public EPipeSchedule()
{
this.PslIsLclChg = false;
}
// Constructor which loads itself from the supplied id.
// If the id is null, this gives the same result as using the default constructor.
public EPipeSchedule(Guid? id) : this()
{
Load(id);
}
//--------------------------------------
// Public Methods
//--------------------------------------
//----------------------------------------------------
// Load the object from the database given a Guid?
//----------------------------------------------------
public void Load(Guid? id)
{
if (id == null) return;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
SqlCeDataReader dr;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Select
PslDBid,
PslOd,
PslNomWall,
PslSchedule,
PslNomDia,
PslIsLclChg
from PipeScheduleLookup
where PslDBid = @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// The query should return one record.
// If it doesn't return anything (no match) the object is not affected
if (dr.Read())
{
// For nullable foreign keys, set field to null for dbNull case
// For other nullable values, replace dbNull with null
PslDBid = (Guid?)dr[0];
PslOd = (decimal?)dr[1];
PslNomWall = (decimal?)dr[2];
PslSchedule = (string)dr[3];
PslNomDia = (decimal?)dr[4];
PslIsLclChg = (bool)dr[5];
}
dr.Close();
}
//--------------------------------------
// Save the current record if it's valid
//--------------------------------------
public Guid? Save()
{
if (!Valid())
{
// Note: We're returning null if we fail,
// so don't just assume you're going to get your id back
// and set your id to the result of this function call.
return null;
}
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
if (ID == null)
{
// we are inserting a new record
// If this is not a master db, set the local change flag to true.
if (!Globals.IsMasterDB) PslIsLclChg = true;
// first ask the database for a new Guid
cmd.CommandText = "Select Newid()";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
PslDBid = (Guid?)(cmd.ExecuteScalar());
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", PslDBid),
new SqlCeParameter("@p1", PslOd),
new SqlCeParameter("@p2", PslNomWall),
new SqlCeParameter("@p3", PslSchedule),
new SqlCeParameter("@p4", PslNomDia),
new SqlCeParameter("@p5", PslIsLclChg)
});
cmd.CommandText = @"Insert Into PipeScheduleLookup (
PslDBid,
PslOd,
PslNomWall,
PslSchedule,
PslNomDia,
PslIsLclChg
) values (@p0,@p1,@p2,@p3,@p4,@p5)";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to insert Pipe Schedule Lookup row");
}
}
else
{
// we are updating an existing record
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", PslDBid),
new SqlCeParameter("@p1", PslOd),
new SqlCeParameter("@p2", PslNomWall),
new SqlCeParameter("@p3", PslSchedule),
new SqlCeParameter("@p4", PslNomDia),
new SqlCeParameter("@p5", PslIsLclChg)});
cmd.CommandText =
@"Update PipeScheduleLookup
set
PslOd = @p1,
PslNomWall = @p2,
PslSchedule = @p3,
PslNomDia = @p4,
PslIsLclChg = @p5
Where PslDBid = @p0";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to update pipe schedule lookup row");
}
}
OnChanged(ID);
return ID;
}
//--------------------------------------
// Validate the current record
//--------------------------------------
// Make this public so that the UI can check validation itself
// if it chooses to do so. This is also called by the Save function.
public bool Valid()
{
// Check form to make sure all required fields have been filled in
if (!RequiredFieldsFilled()) return false;
// Check for incorrect field interactions...
return true;
}
//--------------------------------------
// Delete the current record
//--------------------------------------
public bool Delete(bool promptUser)
{
// If the current object doesn't reference a database record, there's nothing to do.
if (PslDBid == null)
{
PipeScheduleErrMsg = "Unable to delete. Record not found.";
return false;
}
if (!PslIsLclChg && !Globals.IsMasterDB)
{
PipeScheduleErrMsg = "Unable to delete because this PipeSchedule was not added during this outage.";
return false;
}
if (HasChildren())
{
PipeScheduleErrMsg = "Unable to delete because there are components that reference this pipe schedule.";
return false;
}
DialogResult rslt = DialogResult.None;
if (promptUser)
{
rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
}
if (!promptUser || rslt == DialogResult.OK)
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Delete from PipeScheduleLookup
where PslDBid = @p0";
cmd.Parameters.Add("@p0", PslDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
// Todo: figure out how I really want to do this.
// Is there a problem with letting the database try to do cascading deletes?
// How should the user be notified of the problem??
if (rowsAffected < 1)
{
PipeScheduleErrMsg = "Unable to delete. Please try again later.";
return false;
}
else
{
OnChanged(ID);
return true;
}
}
else
{
return false;
}
}
private bool HasChildren()
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Select CmpDBid from Components
where CmpPslID = @p0";
cmd.Parameters.Add("@p0", PslDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
bool hasChildren = false;
object result = cmd.ExecuteScalar();
if (result != null) hasChildren = true;
return hasChildren;
}
//--------------------------------------------------------------------
// Static listing methods which return collections of pipeschedules
//--------------------------------------------------------------------
// This helper function builds the collection for you based on the flags you send it
// I originally had a flag that would let you indicate inactive items by appending '(inactive)'
// to the name. This was a bad idea, because sometimes the objects in this collection
// will get modified and saved back to the database -- with the extra text appended to the name.
public static EPipeScheduleCollection ListByScheduleAndNomDia(
bool showactive, bool showinactive, bool addNoSelection)
{
EPipeSchedule pipeschedule;
EPipeScheduleCollection pipeschedules = new EPipeScheduleCollection();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry = @"Select
PslDBid,
PslOd,
PslNomWall,
PslSchedule,
PslNomDia,
PslIsLclChg
from PipeScheduleLookup";
qry += " order by PslSchedule, PslNomDia";
cmd.CommandText = qry;
if (addNoSelection)
{
// Insert a default item with name "<No Selection>"
pipeschedule = new EPipeSchedule();
pipeschedules.Add(pipeschedule);
}
SqlCeDataReader dr;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// Build new objects and add them to the collection
while (dr.Read())
{
pipeschedule = new EPipeSchedule((Guid?)dr[0]);
pipeschedule.PslOd = (decimal?)(dr[1]);
pipeschedule.PslNomWall = (decimal?)(dr[2]);
pipeschedule.PslSchedule = (string)(dr[3]);
pipeschedule.PslNomDia = (decimal?)(dr[4]);
pipeschedule.PslIsLclChg = (bool)(dr[5]);
// The following sets the default text
pipeschedules.Add(pipeschedule);
}
// Finish up
dr.Close();
return pipeschedules;
}
public static EPipeSchedule FindForOdAndTnom(string sOd, string sTnom)
{
decimal od;
decimal tNom;
if (!Decimal.TryParse(sOd, out od) || !Decimal.TryParse(sTnom, out tNom))
return null;
return FindForOdAndTnom(od, tNom);
}
public static EPipeSchedule FindForOdAndTnom(decimal od, decimal tNom)
{
if (od <= 0 || od >= 1000 || tNom <= 0 || tNom >= 100) return null;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select PslDBid From PipeScheduleLookup
Where PslOd >= @p1 and PslOd <= @p2
and PslNomWall >=@p3 and PslNomWall <=@p4";
cmd.Parameters.Add("@p1", od - 0.001m);
cmd.Parameters.Add("@p2", od + 0.001m);
cmd.Parameters.Add("@p3", tNom - 0.001m);
cmd.Parameters.Add("@p4", tNom + 0.001m);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object result = cmd.ExecuteScalar();
if (result == null) return null;
EPipeSchedule ps = new EPipeSchedule((Guid?)result);
return ps;
}
// Get a Default data view with all columns that a user would likely want to see.
// You can bind this view to a DataGridView, hide the columns you don't need, filter, etc.
// I decided not to indicate inactive in the names of inactive items. The 'user'
// can always show the inactive column if they wish.
public static DataView GetDefaultDataView()
{
DataSet ds = new DataSet();
DataView dv;
SqlCeDataAdapter da = new SqlCeDataAdapter();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
// Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and
// makes the column sortable.
// You'll likely want to modify this query further, joining in other tables, etc.
string qry = @"Select
PslDBid as ID,
PslOd as PipeScheduleOd,
PslNomWall as PipeScheduleNomWall,
PslSchedule as PipeScheduleSchedule,
PslNomDia as PipeScheduleNomDia,
CASE
WHEN PslIsLclChg = 0 THEN 'No'
ELSE 'Yes'
END as PipeScheduleIsLclChg
from PipeScheduleLookup";
cmd.CommandText = qry;
da.SelectCommand = cmd;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
da.Fill(ds);
dv = new DataView(ds.Tables[0]);
return dv;
}
//--------------------------------------
// Private utilities
//--------------------------------------
// Check for required fields, setting the individual error messages
private bool RequiredFieldsFilled()
{
bool allFilled = true;
if (PipeScheduleOd == null)
{
PslOdErrMsg = "A Pipe Schedule Outside Diameter is required";
allFilled = false;
}
else
{
PslOdErrMsg = null;
}
if (PipeScheduleNomWall == null)
{
PslNomWallErrMsg = "A Pipe Schedule Nominal Wall Thickness is required";
allFilled = false;
}
else
{
PslNomWallErrMsg = null;
}
if (PipeScheduleSchedule == null)
{
PslScheduleErrMsg = "A Pipe Schedule Schedule is required";
allFilled = false;
}
else
{
PslScheduleErrMsg = null;
}
if (PipeScheduleNomDia == null)
{
PslNomDiaErrMsg = "A Pipe Schedule Nominal Diameter is required";
allFilled = false;
}
else
{
PslNomDiaErrMsg = null;
}
return allFilled;
}
}
//--------------------------------------
// PipeSchedule Collection class
//--------------------------------------
public class EPipeScheduleCollection : CollectionBase
{
//this event is fired when the collection's items have changed
public event EventHandler Changed;
//this is the constructor of the collection.
public EPipeScheduleCollection()
{ }
//the indexer of the collection
public EPipeSchedule this[int index]
{
get
{
return (EPipeSchedule)this.List[index];
}
}
//this method fires the Changed event.
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
public bool ContainsID(Guid? ID)
{
if (ID == null) return false;
foreach (EPipeSchedule pipeschedule in InnerList)
{
if (pipeschedule.ID == ID)
return true;
}
return false;
}
//returns the index of an item in the collection
public int IndexOf(EPipeSchedule item)
{
return InnerList.IndexOf(item);
}
//adds an item to the collection
public void Add(EPipeSchedule item)
{
this.List.Add(item);
OnChanged(EventArgs.Empty);
}
//inserts an item in the collection at a specified index
public void Insert(int index, EPipeSchedule item)
{
this.List.Insert(index, item);
OnChanged(EventArgs.Empty);
}
//removes an item from the collection.
public void Remove(EPipeSchedule item)
{
this.List.Remove(item);
OnChanged(EventArgs.Empty);
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using NLog.Internal;
using NLog.Targets;
#if NET4_5
using System.Web.Http;
using Owin;
using Microsoft.Owin.Hosting;
#endif
using Xunit;
namespace NLog.UnitTests.Targets
{
public class WebServiceTargetTests : NLogTestBase
{
[Fact]
public void Stream_CopyWithOffset_test()
{
var text = @"
Lorem ipsum dolor sit amet consectetuer tellus semper dictum urna consectetuer. Eu iaculis enim tincidunt mi pede id ut sociis non vitae. Condimentum augue Nam Vestibulum faucibus tortor et at Sed et molestie. Interdum morbi Nullam pellentesque Vestibulum pede et eget semper Pellentesque quis. Velit cursus nec dolor vitae id et urna quis ante velit. Neque urna et vitae neque Vestibulum tellus convallis dui.
Tellus nibh enim augue senectus ut augue Donec Pellentesque Sed pretium. Volutpat nunc rutrum auctor dolor pharetra malesuada elit sapien ac nec. Adipiscing et id penatibus turpis a odio risus orci Suspendisse eu. Nibh eu facilisi eu consectetuer nibh eu in Nunc Curabitur rutrum. Quisque sit lacus consectetuer eu Duis quis felis hendrerit lobortis mauris. Nam Vivamus enim Aenean rhoncus.
Nulla tellus dui orci montes Vestibulum Aenean condimentum non id vel. Euismod Nam libero odio ut ut Nunc ac dui Nulla volutpat. Quisque facilisis consequat tempus tempus Curabitur tortor id Phasellus Suspendisse In. Lorem et Phasellus wisi Fusce fringilla pretium pede sapien amet ligula. In sed id In eget tristique quam sed interdum wisi commodo. Volutpat neque nibh mauris Quisque lorem nunc porttitor Cras faucibus augue. Sociis tempus et.
Morbi Nulla justo Aenean orci Vestibulum ullamcorper tincidunt mollis et hendrerit. Enim at laoreet elit eros ut at laoreet vel velit quis. Netus sed Suspendisse sed Curabitur vel sed wisi sapien nonummy congue. Semper Sed a malesuada tristique Vivamus et est eu quis ante. Wisi cursus Suspendisse dictum pretium habitant sodales scelerisque dui tempus libero. Venenatis consequat Lorem eu.
";
var textStream = GenerateStreamFromString(text);
var textBytes = StreamToBytes(textStream);
textStream.Position = 0;
textStream.Flush();
var resultStream = new MemoryStream();
textStream.CopyWithOffset(resultStream, 3);
var result = StreamToBytes(resultStream);
var expected = textBytes.Skip(3).ToArray();
Assert.Equal(result.Length, expected.Length);
Assert.Equal(result, expected);
}
[Fact]
public void WebserviceTest_httppost_utf8_default_no_bom()
{
WebserviceTest_httppost_utf8("", false);
}
[Fact]
public void WebserviceTest_httppost_utf8_with_bom()
{
WebserviceTest_httppost_utf8("includeBOM='true'", true);
}
[Fact]
public void WebserviceTest_httppost_utf8_no_boml()
{
WebserviceTest_httppost_utf8("includeBOM='false'", false);
}
private void WebserviceTest_httppost_utf8(string bomAttr, bool includeBom)
{
var configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='WebService'
name='webservice'
url='http://localhost:57953/Home/Foo2'
protocol='HttpPost'
" + bomAttr + @"
encoding='UTF-8'
methodName='Foo'>
<parameter name='empty' type='System.String' layout=''/> <!-- work around so the guid is decoded properly -->
<parameter name='guid' type='System.String' layout='${guid}'/>
<parameter name='m' type='System.String' layout='${message}'/>
<parameter name='date' type='System.String' layout='${longdate}'/>
<parameter name='logger' type='System.String' layout='${logger}'/>
<parameter name='level' type='System.String' layout='${level}'/>
</target>
</targets>
</nlog>");
var target = configuration.FindTargetByName("webservice") as WebServiceTarget;
Assert.NotNull(target);
Assert.Equal(target.Parameters.Count, 6);
Assert.Equal(target.Encoding.WebName, "utf-8");
//async call with mockup stream
WebRequest webRequest = WebRequest.Create("http://www.test.com");
var request = (HttpWebRequest)webRequest;
var streamMock = new StreamMock();
//event for async testing
var counterEvent = new ManualResetEvent(false);
var parameterValues = new object[] { "", "336cec87129942eeabab3d8babceead7", "Debg", "2014-06-26 23:15:14.6348", "TestClient.Program", "Debug" };
target.DoInvoke(parameterValues, c => counterEvent.Set(), request,
callback =>
{
var t = new Task(() => { });
callback(t);
return t;
},
result => streamMock);
counterEvent.WaitOne(10000);
var bytes = streamMock.bytes;
var url = streamMock.stringed;
const string expectedUrl = "empty=&guid=336cec87129942eeabab3d8babceead7&m=Debg&date=2014-06-26+23%3a15%3a14.6348&logger=TestClient.Program&level=Debug";
Assert.Equal(expectedUrl, url);
Assert.True(bytes.Length > 3);
//not bom
var possbleBomBytes = bytes.Take(3).ToArray();
if (includeBom)
{
Assert.Equal(possbleBomBytes, EncodingHelpers.Utf8BOM);
}
else
{
Assert.NotEqual(possbleBomBytes, EncodingHelpers.Utf8BOM);
}
Assert.Equal(bytes.Length, includeBom ? 126 : 123);
}
#region helpers
private Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
private static byte[] StreamToBytes(Stream stream)
{
stream.Flush();
stream.Position = 0;
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// Mock the stream
/// </summary>
private class StreamMock : MemoryStream
{
public byte[] bytes;
public string stringed;
#region Overrides of MemoryStream
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.IO.MemoryStream"/> class and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
//save stuff before dispose
this.Flush();
bytes = this.ToArray();
stringed = StreamToString(this);
base.Dispose(disposing);
}
private static string StreamToString(Stream s)
{
s.Position = 0;
var sr = new StreamReader(s);
return sr.ReadToEnd();
}
#endregion
}
#endregion
#if NET4_5
//const string WsAddress = "http://localhost:9000/";
/// <summary>
/// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception)
/// </summary>
[Fact]
public void WebserviceTest_restapi_httppost()
{
const string WsAddress = "http://localhost:9000/";
var configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true'>
<targets>
<target type='WebService'
name='ws'
url='{0}{1}'
protocol='HttpPost'
encoding='UTF-8'
>
<parameter name='param1' type='System.String' layout='${{message}}'/>
<parameter name='param2' type='System.String' layout='${{level}}'/>
</target>
</targets>
<rules>
<logger name='*' writeTo='ws'>
</logger>
</rules>
</nlog>", WsAddress, "api/logme"));
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
LogMeController.ResetState(1);
StartOwinTest(() =>
{
logger.Info("message 1 with a post");
}, WsAddress);
}
/// <summary>
/// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpGet"/> (only checking for no exception)
/// </summary>
[Fact]
public void WebserviceTest_restapi_httpget()
{
const string WsAddress = "http://localhost:9001/";
WebServiceTest_httpget("api/logme",WsAddress);
}
[Fact]
public void WebServiceTest_restapi_httpget_querystring()
{
const string WsAddress = "http://localhost:9002/";
WebServiceTest_httpget("api/logme?paramFromConfig=valueFromConfig",WsAddress);
}
private void WebServiceTest_httpget(string relativeUrl, string url)
{
var configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true' >
<targets>
<target type='WebService'
name='ws'
url='{0}{1}'
protocol='HttpGet'
encoding='UTF-8'
>
<parameter name='param1' type='System.String' layout='${{message}}'/>
<parameter name='param2' type='System.String' layout='${{level}}'/>
</target>
</targets>
<rules>
<logger name='*' writeTo='ws'>
</logger>
</rules>
</nlog>", url, relativeUrl));
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
LogMeController.ResetState(1);
StartOwinTest(() =>
{
logger.Info("message 1 with a post");
},url);
}
/// <summary>
/// Timeout for <see cref="WebserviceTest_restapi_httppost_checkingLost"/>.
///
/// in miliseconds. 20000 = 20 sec
/// </summary>
const int webserviceCheckTimeoutMs = 20000;
/// <summary>
/// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception)
///
/// repeats for checking 'lost messages'
/// </summary>
[Fact]
public void WebserviceTest_restapi_httppost_checkingLost()
{
const string WsAddress = "http://localhost:9003/";
var configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true'>
<targets>
<target type='WebService'
name='ws'
url='{0}{1}'
protocol='HttpPost'
encoding='UTF-8'
>
<parameter name='param1' type='System.String' layout='${{message}}'/>
<parameter name='param2' type='System.String' layout='${{level}}'/>
</target>
</targets>
<rules>
<logger name='*' writeTo='ws'>
</logger>
</rules>
</nlog>", WsAddress, "api/logme"));
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
const int messageCount = 500;
var createdMessages = new List<string>(messageCount);
for (int i = 0; i < messageCount; i++)
{
var message = "message " + i;
createdMessages.Add(message);
}
//reset
LogMeController.ResetState(messageCount);
StartOwinTest(() =>
{
foreach (var createdMessage in createdMessages)
{
logger.Info(createdMessage);
}
}, WsAddress);
Assert.Equal(LogMeController.CountdownEvent.CurrentCount, 0);
Assert.Equal(createdMessages.Count, LogMeController.RecievedLogsPostParam1.Count);
//Assert.Equal(createdMessages, ValuesController.RecievedLogsPostParam1);
}
/// <summary>
/// Start/config route of WS
/// </summary>
private class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
private const string LogTemplate = "Method: {0}, param1: '{1}', param2: '{2}', body: {3}";
///<remarks>Must be public </remarks>
public class LogMeController : ApiController
{
/// <summary>
/// Reset the state for unit testing
/// </summary>
/// <param name="expectedMessages"></param>
public static void ResetState(int expectedMessages)
{
RecievedLogsPostParam1 = new ConcurrentBag<string>();
RecievedLogsGetParam1 = new ConcurrentBag<string>();
CountdownEvent = new CountdownEvent(expectedMessages);
}
/// <summary>
/// Countdown event for keeping WS alive.
/// </summary>
public static CountdownEvent CountdownEvent = null;
/// <summary>
/// Recieved param1 values (get)
/// </summary>
public static ConcurrentBag<string> RecievedLogsGetParam1 = new ConcurrentBag<string>();
/// <summary>
/// Recieved param1 values(post)
/// </summary>
public static ConcurrentBag<string> RecievedLogsPostParam1 = new ConcurrentBag<string>();
/// <summary>
/// We need a complex type for modelbinding because of content-type: "application/x-www-form-urlencoded" in <see cref="WebServiceTarget"/>
/// </summary>
public class ComplexType
{
public string Param1 { get; set; }
public string Param2 { get; set; }
}
/// <summary>
/// Get
/// </summary>
public string Get(int id)
{
return "value";
}
// GET api/values
public IEnumerable<string> Get(string param1 = "", string param2 = "")
{
RecievedLogsGetParam1.Add(param1);
var result = new string[] { "value1", "value2" };
if (CountdownEvent != null)
{
CountdownEvent.Signal();
}
return result;
}
/// <summary>
/// Post
/// </summary>
public void Post([FromBody] ComplexType complexType)
{
//this is working.
if (complexType == null)
{
throw new ArgumentNullException("complexType");
}
RecievedLogsPostParam1.Add(complexType.Param1);
if (CountdownEvent != null)
{
CountdownEvent.Signal();
}
}
/// <summary>
/// Put
/// </summary>
public void Put(int id, [FromBody]string value)
{
}
/// <summary>
/// Delete
/// </summary>
public void Delete(int id)
{
}
}
internal static void StartOwinTest(Action testsFunc, string url)
{
// HttpSelfHostConfiguration. So info: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
// Start webservice
using (WebApp.Start<Startup>(url: url))
{
testsFunc();
//wait for all recieved message, or timeout. There is no exception on timeout, so we have to check carefully in the unit test.
if (LogMeController.CountdownEvent != null)
{
LogMeController.CountdownEvent.Wait(webserviceCheckTimeoutMs);
//we need some extra time for completion
Thread.Sleep(1000);
}
}
}
#endif
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Filters;
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class FilteringTargetWrapperTests : NLogTestBase
{
[Fact]
public void FilteringTargetWrapperSyncTest1()
{
var myMockCondition = new MyMockCondition(true);
var myTarget = new MyTarget();
var wrapper = new FilteringTargetWrapper
{
WrappedTarget = myTarget,
Condition = myMockCondition,
};
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
bool continuationHit = false;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit = true;
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.Equal(1, myMockCondition.CallCount);
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit = false;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncTest1()
{
var myMockCondition = new MyMockCondition(true);
var myTarget = new MyAsyncTarget();
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncWithExceptionTest1()
{
var myMockCondition = new MyMockCondition(true);
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
Assert.Equal(1, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
lastException = null;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperSyncTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyTarget();
var wrapper = new FilteringTargetWrapper
{
WrappedTarget = myTarget,
Condition = myMockCondition,
};
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
bool continuationHit = false;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit = true;
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.Equal(1, myMockCondition.CallCount);
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit = false;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyAsyncTarget();
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncWithExceptionTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
lastException = null;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperWhenRepeatedFilter()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<variable name='test' value='${message}' />
<targets>
<target name='debug' type='BufferingWrapper'>
<target name='filter' type='FilteringWrapper'>
<filter type='whenRepeated' layout='${var:test:whenempty=${guid}}' timeoutSeconds='30' action='Ignore' />
<target name='memory' type='Memory' />
</target>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'/>
</rules>
</nlog>");
var myTarget = LogManager.Configuration.FindTargetByName<MemoryTarget>("memory");
var logger = LogManager.GetLogger(nameof(FilteringTargetWrapperWhenRepeatedFilter));
logger.Info("Hello World");
logger.Info("Hello World"); // Will be ignored
logger.Info("Goodbye World");
logger.Warn("Goodbye World");
LogManager.Flush();
Assert.Equal(3, myTarget.Logs.Count);
logger.Info("Hello World"); // Will be ignored
logger.Error("Goodbye World");
logger.Fatal("Goodbye World");
LogManager.Flush();
Assert.Equal(5, myTarget.Logs.Count);
}
[Fact]
public void FilteringTargetWrapperWithConditionAttribute_correctBehavior()
{
// Arrange
LogManager.Configuration = CreateConfigWithCondition();
var myTarget = LogManager.Configuration.FindTargetByName<MemoryTarget>("memory");
// Act
var logger = LogManager.GetLogger(nameof(FilteringTargetWrapperWhenRepeatedFilter));
logger.Info("Hello World");
logger.Info("2"); // Will be ignored
logger.Info("3"); // Will be ignored
LogManager.Flush();
// Assert
Assert.Equal(1, myTarget.Logs.Count);
}
[Fact]
public void FilteringTargetWrapperWithConditionAttribute_validCondition()
{
// Arrange
var expectedCondition = "(length(message) > 2)";
// Act
var config = CreateConfigWithCondition();
// Assert
var myTarget = config.FindTargetByName<FilteringTargetWrapper>("target1");
Assert.Equal(expectedCondition, myTarget.Condition?.ToString());
var conditionBasedFilter = Assert.IsType<ConditionBasedFilter>(myTarget.Filter);
Assert.Equal(expectedCondition, conditionBasedFilter.Condition?.ToString());
}
private static XmlLoggingConfiguration CreateConfigWithCondition()
{
return XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='target1' type='FilteringWrapper' condition='length(message) > 2' >
<target name='memory' type='Memory' />
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='target1'/>
</rules>
</nlog>");
}
class MyAsyncTarget : Target
{
public int WriteCount { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
WriteCount++;
ThreadPool.QueueUserWorkItem(
s =>
{
if (ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
WriteCount++;
}
}
class MyMockCondition : ConditionExpression
{
private bool result;
public int CallCount { get; set; }
public MyMockCondition(bool result)
{
this.result = result;
}
protected override object EvaluateNode(LogEventInfo context)
{
CallCount++;
return result;
}
public override string ToString()
{
return "fake";
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core;
using Microsoft.Msagl.Core.Geometry;
namespace Microsoft.Msagl.Layout.Incremental {
class TNode {
internal LinkedListNode<TNode> stackNode;
internal Node v;
internal bool visited;
internal List<TNode> outNeighbours = new List<TNode>();
internal List<TNode> inNeighbours = new List<TNode>();
internal TNode(Node v) {
this.v = v;
}
}
/// <summary>
/// Create separation constraints between the source and target of edges not involved in cycles
/// in order to better show flow
/// </summary>
public class EdgeConstraintGenerator
{
IdealEdgeLengthSettings settings;
IEnumerable<Edge> edges;
Dictionary<Node, TNode> nodeMap = new Dictionary<Node, TNode>();
LinkedList<TNode> stack = new LinkedList<TNode>();
List<TNode> component;
AxisSolver horizontalSolver;
AxisSolver verticalSolver;
List<Set<Node>> cyclicComponents = new List<Set<Node>>();
/// <summary>
/// Creates a VerticalSeparationConstraint for each edge in the given set to structural constraints,
/// to require these edges to be downward pointing. Also checks for cycles, and edges involved
/// in a cycle receive no VerticalSeparationConstraint, but can optionally receive a circle constraint.
/// </summary>
/// <param name="edges"></param>
/// <param name="settings"></param>
/// <param name="horizontalSolver"></param>
/// <param name="verticalSolver"></param>
internal static void GenerateEdgeConstraints(
IEnumerable<Edge> edges,
IdealEdgeLengthSettings settings,
AxisSolver horizontalSolver,
AxisSolver verticalSolver)
{
if (settings.EdgeDirectionConstraints == Directions.None)
{
return;
}
EdgeConstraintGenerator g = new EdgeConstraintGenerator(edges, settings, horizontalSolver, verticalSolver);
g.GenerateSeparationConstraints();
// we have in the past used Circular constraints to better show cycles... it's a little experimental though
// so it's not currently enabled
//foreach (var c in g.CyclicComponents) {
// constraints.Add(new ProcrustesCircleConstraint(c));
//}
}
internal EdgeConstraintGenerator(
IEnumerable<Edge> edges,
IdealEdgeLengthSettings settings,
AxisSolver horizontalSolver,
AxisSolver verticalSolver)
{
// filter out self edges
this.edges = edges.Where(e => e.Source != e.Target);
this.settings = settings;
this.horizontalSolver = horizontalSolver;
this.verticalSolver = verticalSolver;
foreach (var e in this.edges) {
TNode u = CreateTNode(e.Source), v = CreateTNode(e.Target);
u.outNeighbours.Add(v);
v.inNeighbours.Add(u);
}
foreach (var v in nodeMap.Values) {
if(v.stackNode==null) {
DFS(v);
}
}
while (stack.Count > 0) {
component = new List<TNode>();
RDFS(stack.Last.Value);
if (component.Count > 1) {
var cyclicComponent = new Set<Node>();
foreach (var v in component) {
cyclicComponent.Insert(v.v);
}
cyclicComponents.Add(cyclicComponent);
}
}
switch (settings.EdgeDirectionConstraints) {
case Directions.South:
this.addConstraint = this.AddSConstraint;
break;
case Directions.North:
this.addConstraint = this.AddNConstraint;
break;
case Directions.West:
this.addConstraint = this.AddWConstraint;
break;
case Directions.East:
this.addConstraint = this.AddEConstraint;
break;
}
}
private delegate void AddConstraint(Node u, Node v);
private AddConstraint addConstraint;
private void AddSConstraint(Node u, Node v)
{
verticalSolver.AddStructuralConstraint(
new VerticalSeparationConstraint(u, v, (u.Height + v.Height) / 2 + settings.ConstrainedEdgeSeparation));
}
private void AddNConstraint(Node u, Node v)
{
verticalSolver.AddStructuralConstraint(
new VerticalSeparationConstraint(v, u, (u.Height + v.Height) / 2 + settings.ConstrainedEdgeSeparation));
}
private void AddEConstraint(Node u, Node v)
{
horizontalSolver.AddStructuralConstraint(
new HorizontalSeparationConstraint(v, u, (u.Width + v.Width) / 2 + settings.ConstrainedEdgeSeparation));
}
private void AddWConstraint(Node u, Node v)
{
horizontalSolver.AddStructuralConstraint(
new HorizontalSeparationConstraint(u, v, (u.Width + v.Width) / 2 + settings.ConstrainedEdgeSeparation));
}
/// <summary>
/// For each edge not involved in a cycle create a constraint
/// </summary>
public void GenerateSeparationConstraints() {
foreach (var e in edges) {
bool edgeInCycle = false;
Node u = e.Source, v = e.Target;
foreach (var c in cyclicComponents) {
if (c.Contains(u) && c.Contains(v)) {
edgeInCycle = true;
break;
}
}
if (!edgeInCycle) {
this.addConstraint(u, v);
}
}
}
/// <summary>
/// Get an Enumeration of CyclicComponents
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public IEnumerable<IEnumerable<Node>> CyclicComponents {
get {
return from c in cyclicComponents
select c.AsEnumerable();
}
}
private void DFS(TNode u) {
u.visited = true;
foreach (var v in u.outNeighbours) {
if (!v.visited) {
DFS(v);
}
}
PushStack(u);
}
private void RDFS(TNode u) {
component.Add(u);
PopStack(u);
foreach (var v in u.inNeighbours) {
if (v.stackNode != null) {
RDFS(v);
}
}
}
private TNode CreateTNode(Node v) {
TNode tv;
if (!nodeMap.ContainsKey(v)) {
tv = new TNode(v);
nodeMap[v] = tv;
} else {
tv = nodeMap[v];
}
return tv;
}
private void PushStack(TNode v) {
v.stackNode = stack.AddLast(v);
}
private void PopStack(TNode v) {
stack.Remove(v.stackNode);
v.stackNode = null;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2014 Daniel Buckmaster
//
// 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.
//-----------------------------------------------------------------------------
$Nav::EditorOpen = false;
function NavEditorGui::onEditorActivated(%this)
{
if(%this.selectedObject)
%this.selectObject(%this.selectedObject);
%this.prepSelectionMode();
}
function NavEditorGui::onEditorDeactivated(%this)
{
if(%this.getMesh())
%this.deselect();
}
function NavEditorGui::onModeSet(%this, %mode)
{
// Callback when the nav editor changes mode. Set the appropriate dynamic
// GUI contents in the properties/actions boxes.
NavInspector.setVisible(false);
%actions = NavEditorOptionsWindow->ActionsBox;
%actions->SelectActions.setVisible(false);
%actions->LinkActions.setVisible(false);
%actions->CoverActions.setVisible(false);
%actions->TileActions.setVisible(false);
%actions->TestActions.setVisible(false);
%properties = NavEditorOptionsWindow->PropertiesBox;
%properties->LinkProperties.setVisible(false);
%properties->TileProperties.setVisible(false);
%properties->TestProperties.setVisible(false);
switch$(%mode)
{
case "SelectMode":
NavInspector.setVisible(true);
%actions->SelectActions.setVisible(true);
case "LinkMode":
%actions->LinkActions.setVisible(true);
%properties->LinkProperties.setVisible(true);
case "CoverMode":
//
%actions->CoverActions.setVisible(true);
case "TileMode":
%actions->TileActions.setVisible(true);
%properties->TileProperties.setVisible(true);
case "TestMode":
%actions->TestActions.setVisible(true);
%properties->TestProperties.setVisible(true);
}
}
function NavEditorGui::paletteSync(%this, %mode)
{
// Synchronise the palette (small buttons on the left) with the actual mode
// the nav editor is in.
%evalShortcut = "ToolsPaletteArray-->" @ %mode @ ".setStateOn(1);";
eval(%evalShortcut);
}
function NavEditorGui::onEscapePressed(%this)
{
return false;
}
function NavEditorGui::selectObject(%this, %obj)
{
NavTreeView.clearSelection();
if(isObject(%obj))
NavTreeView.selectItem(%obj);
%this.onObjectSelected(%obj);
}
function NavEditorGui::onObjectSelected(%this, %obj)
{
if(isObject(%this.selectedObject))
%this.deselect();
%this.selectedObject = %obj;
if(isObject(%obj))
{
%this.selectMesh(%obj);
NavInspector.inspect(%obj);
}
}
function NavEditorGui::deleteMesh(%this)
{
if(isObject(%this.selectedObject))
{
%this.selectedObject.delete();
%this.selectObject(-1);
}
}
function NavEditorGui::deleteSelected(%this)
{
switch$(%this.getMode())
{
case "SelectMode":
// Try to delete the selected NavMesh.
if(isObject(NavEditorGui.selectedObject))
MessageBoxYesNo("Warning",
"Are you sure you want to delete" SPC NavEditorGui.selectedObject.getName(),
"NavEditorGui.deleteMesh();");
case "TestMode":
%this.getPlayer().delete();
%this.onPlayerDeselected();
case "LinkMode":
%this.deleteLink();
%this.isDirty = true;
}
}
function NavEditorGui::buildSelectedMeshes(%this)
{
if(isObject(%this.getMesh()))
{
%this.getMesh().build(NavEditorGui.backgroundBuild, NavEditorGui.saveIntermediates);
%this.isDirty = true;
}
}
function NavEditorGui::buildLinks(%this)
{
if(isObject(%this.getMesh()))
{
%this.getMesh().buildLinks();
%this.isDirty = true;
}
}
function updateLinkData(%control, %flags)
{
%control->LinkWalkFlag.setActive(true);
%control->LinkJumpFlag.setActive(true);
%control->LinkDropFlag.setActive(true);
%control->LinkLedgeFlag.setActive(true);
%control->LinkClimbFlag.setActive(true);
%control->LinkTeleportFlag.setActive(true);
%control->LinkWalkFlag.setStateOn(%flags & $Nav::WalkFlag);
%control->LinkJumpFlag.setStateOn(%flags & $Nav::JumpFlag);
%control->LinkDropFlag.setStateOn(%flags & $Nav::DropFlag);
%control->LinkLedgeFlag.setStateOn(%flags & $Nav::LedgeFlag);
%control->LinkClimbFlag.setStateOn(%flags & $Nav::ClimbFlag);
%control->LinkTeleportFlag.setStateOn(%flags & $Nav::TeleportFlag);
}
function getLinkFlags(%control)
{
return (%control->LinkWalkFlag.isStateOn() ? $Nav::WalkFlag : 0) |
(%control->LinkJumpFlag.isStateOn() ? $Nav::JumpFlag : 0) |
(%control->LinkDropFlag.isStateOn() ? $Nav::DropFlag : 0) |
(%control->LinkLedgeFlag.isStateOn() ? $Nav::LedgeFlag : 0) |
(%control->LinkClimbFlag.isStateOn() ? $Nav::ClimbFlag : 0) |
(%control->LinkTeleportFlag.isStateOn() ? $Nav::TeleportFlag : 0);
}
function disableLinkData(%control)
{
%control->LinkWalkFlag.setActive(false);
%control->LinkJumpFlag.setActive(false);
%control->LinkDropFlag.setActive(false);
%control->LinkLedgeFlag.setActive(false);
%control->LinkClimbFlag.setActive(false);
%control->LinkTeleportFlag.setActive(false);
}
function NavEditorGui::onLinkSelected(%this, %flags)
{
updateLinkData(NavEditorOptionsWindow-->LinkProperties, %flags);
}
function NavEditorGui::onPlayerSelected(%this, %flags)
{
updateLinkData(NavEditorOptionsWindow-->TestProperties, %flags);
}
function NavEditorGui::updateLinkFlags(%this)
{
if(isObject(%this.getMesh()))
{
%properties = NavEditorOptionsWindow-->LinkProperties;
%this.setLinkFlags(getLinkFlags(%properties));
%this.isDirty = true;
}
}
function NavEditorGui::updateTestFlags(%this)
{
if(isObject(%this.getPlayer()))
{
%properties = NavEditorOptionsWindow-->TestProperties;
%player = %this.getPlayer();
%player.allowWwalk = %properties->LinkWalkFlag.isStateOn();
%player.allowJump = %properties->LinkJumpFlag.isStateOn();
%player.allowDrop = %properties->LinkDropFlag.isStateOn();
%player.allowLedge = %properties->LinkLedgeFlag.isStateOn();
%player.allowClimb = %properties->LinkClimbFlag.isStateOn();
%player.allowTeleport = %properties->LinkTeleportFlag.isStateOn();
%this.isDirty = true;
}
}
function NavEditorGui::onLinkDeselected(%this)
{
disableLinkData(NavEditorOptionsWindow-->LinkProperties);
}
function NavEditorGui::onPlayerDeselected(%this)
{
disableLinkData(NavEditorOptionsWindow-->TestProperties);
}
function NavEditorGui::createCoverPoints(%this)
{
if(isObject(%this.getMesh()))
{
%this.getMesh().createCoverPoints();
%this.isDirty = true;
}
}
function NavEditorGui::deleteCoverPoints(%this)
{
if(isObject(%this.getMesh()))
{
%this.getMesh().deleteCoverPoints();
%this.isDirty = true;
}
}
function NavEditorGui::findCover(%this)
{
if(%this.getMode() $= "TestMode" && isObject(%this.getPlayer()))
{
%pos = LocalClientConnection.getControlObject().getPosition();
%text = NavEditorOptionsWindow-->TestProperties->CoverPosition.getText();
if(%text !$= "")
%pos = eval(%text);
%this.getPlayer().findCover(%pos, NavEditorOptionsWindow-->TestProperties->CoverRadius.getText());
}
}
function NavEditorGui::followObject(%this)
{
if(%this.getMode() $= "TestMode" && isObject(%this.getPlayer()))
{
%obj = LocalClientConnection.player;
%text = NavEditorOptionsWindow-->TestProperties->FollowObject.getText();
if(%text !$= "")
{
eval("%obj = " @ %text);
if(!isObject(%obj))
MessageBoxOk("Error", "Cannot find object" SPC %text);
}
if(isObject(%obj))
%this.getPlayer().followObject(%obj, NavEditorOptionsWindow-->TestProperties->FollowRadius.getText());
}
}
function NavInspector::inspect(%this, %obj)
{
%name = "";
if(isObject(%obj))
%name = %obj.getName();
else
NavFieldInfoControl.setText("");
Parent::inspect(%this, %obj);
}
function NavInspector::onInspectorFieldModified(%this, %object, %fieldName, %arrayIndex, %oldValue, %newValue)
{
// Same work to do as for the regular WorldEditor Inspector.
Inspector::onInspectorFieldModified(%this, %object, %fieldName, %arrayIndex, %oldValue, %newValue);
}
function NavInspector::onFieldSelected(%this, %fieldName, %fieldTypeStr, %fieldDoc)
{
NavFieldInfoControl.setText("<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc);
}
function NavTreeView::onInspect(%this, %obj)
{
NavInspector.inspect(%obj);
}
function NavTreeView::onSelect(%this, %obj)
{
NavInspector.inspect(%obj);
NavEditorGui.onObjectSelected(%obj);
}
function NavEditorGui::prepSelectionMode(%this)
{
%this.setMode("SelectMode");
ToolsPaletteArray-->NavEditorSelectMode.setStateOn(1);
}
//-----------------------------------------------------------------------------
function ENavEditorPaletteButton::onClick(%this)
{
// When clicking on a pelette button, add its description to the bottom of
// the editor window.
EditorGuiStatusBar.setInfo(%this.DetailedDesc);
}
//-----------------------------------------------------------------------------
function NavMeshLinkFlagButton::onClick(%this)
{
NavEditorGui.updateLinkFlags();
}
function NavMeshTestFlagButton::onClick(%this)
{
NavEditorGui.updateTestFlags();
}
singleton GuiControlProfile(NavEditorProfile)
{
canKeyFocus = true;
opaque = true;
fillColor = "192 192 192 192";
category = "Editor";
};
singleton GuiControlProfile(GuiSimpleBorderProfile)
{
opaque = false;
border = 1;
category = "Editor";
};
| |
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.Core.Title.Models;
using Orchard.Projections.Descriptors.Filter;
using Orchard.Projections.Descriptors.Layout;
using Orchard.Projections.Descriptors.SortCriterion;
using Orchard.Projections.Models;
using Orchard.Projections.Services;
using Orchard.Projections.ViewModels;
using Orchard.ContentManagement;
using Orchard.Core.Contents.Controllers;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Notify;
using System;
using Orchard.Settings;
using Orchard.UI.Navigation;
namespace Orchard.Projections.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly IOrchardServices _services;
private readonly ISiteService _siteService;
private readonly IQueryService _queryService;
private readonly IProjectionManager _projectionManager;
public AdminController(
IOrchardServices services,
IShapeFactory shapeFactory,
ISiteService siteService,
IQueryService queryService,
IProjectionManager projectionManager) {
_services = services;
_siteService = siteService;
_queryService = queryService;
_projectionManager = projectionManager;
Services = services;
T = NullLocalizer.Instance;
Shape = shapeFactory;
}
dynamic Shape { get; set; }
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list queries")))
return new HttpUnauthorizedResult();
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
// default options
if (options == null)
options = new AdminIndexOptions();
var queries = Services.ContentManager.Query("Query");
switch (options.Filter) {
case QueriesFilter.All:
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!String.IsNullOrWhiteSpace(options.Search)) {
queries = queries.Join<TitlePartRecord>().Where(r => r.Title.Contains(options.Search));
}
var pagerShape = Shape.Pager(pager).TotalItemCount(queries.Count());
switch (options.Order) {
case QueriesOrder.Name:
queries = queries.Join<TitlePartRecord>().OrderBy(u => u.Title);
break;
}
var results = queries
.Slice(pager.GetStartIndex(), pager.PageSize)
.ToList();
var model = new AdminIndexViewModel {
Queries = results.Select(x => new QueryEntry {
Query = x.As<QueryPart>().Record,
QueryId = x.Id,
Name = x.As<QueryPart>().Name
}).ToList(),
Options = options,
Pager = pagerShape
};
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
pagerShape.RouteData(routeData);
return View(model);
}
[HttpPost]
[FormValueRequired("submit.BulkEdit")]
public ActionResult Index(FormCollection input) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage queries")))
return new HttpUnauthorizedResult();
var viewModel = new AdminIndexViewModel { Queries = new List<QueryEntry>(), Options = new AdminIndexOptions() };
UpdateModel(viewModel);
var checkedItems = viewModel.Queries.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case QueriesBulkAction.None:
break;
case QueriesBulkAction.Delete:
foreach (var checkedItem in checkedItems) {
_queryService.DeleteQuery(checkedItem.QueryId);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
return RedirectToAction("Index");
}
public ActionResult Edit(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit queries")))
return new HttpUnauthorizedResult();
var query = _queryService.GetQuery(id);
var viewModel = new AdminEditViewModel {
Id = query.Id,
Name = query.Name
};
#region Load Filters
var filterGroupEntries = new List<FilterGroupEntry>();
var allFilters = _projectionManager.DescribeFilters().SelectMany(x => x.Descriptors).ToList();
foreach (var group in query.FilterGroups) {
var filterEntries = new List<FilterEntry>();
foreach (var filter in group.Filters) {
var category = filter.Category;
var type = filter.Type;
var f = allFilters.FirstOrDefault(x => category == x.Category && type == x.Type);
if (f != null) {
filterEntries.Add(
new FilterEntry {
Category = f.Category,
Type = f.Type,
FilterRecordId = filter.Id,
DisplayText = String.IsNullOrWhiteSpace(filter.Description) ? f.Display(new FilterContext {State = FormParametersHelper.ToDynamic(filter.State)}).Text : filter.Description
});
}
}
filterGroupEntries.Add( new FilterGroupEntry { Id = group.Id, Filters = filterEntries } );
}
viewModel.FilterGroups = filterGroupEntries;
#endregion
#region Load Sort criterias
var sortCriterionEntries = new List<SortCriterionEntry>();
var allSortCriteria = _projectionManager.DescribeSortCriteria().SelectMany(x => x.Descriptors).ToList();
foreach (var sortCriterion in query.SortCriteria.OrderBy(s => s.Position)) {
var category = sortCriterion.Category;
var type = sortCriterion.Type;
var f = allSortCriteria.FirstOrDefault(x => category == x.Category && type == x.Type);
if (f != null) {
sortCriterionEntries.Add(
new SortCriterionEntry {
Category = f.Category,
Type = f.Type,
SortCriterionRecordId = sortCriterion.Id,
DisplayText = String.IsNullOrWhiteSpace(sortCriterion.Description) ? f.Display(new SortCriterionContext { State = FormParametersHelper.ToDynamic(sortCriterion.State) }).Text : sortCriterion.Description
});
}
}
viewModel.SortCriteria = sortCriterionEntries;
#endregion
#region Load Layouts
var layoutEntries = new List<LayoutEntry>();
var allLayouts = _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).ToList();
foreach (var layout in query.Layouts) {
var category = layout.Category;
var type = layout.Type;
var f = allLayouts.FirstOrDefault(x => category == x.Category && type == x.Type);
if (f != null) {
layoutEntries.Add(
new LayoutEntry {
Category = f.Category,
Type = f.Type,
LayoutRecordId = layout.Id,
DisplayText = String.IsNullOrWhiteSpace(layout.Description) ? f.Display(new LayoutContext { State = FormParametersHelper.ToDynamic(layout.State) }).Text : layout.Description
});
}
}
viewModel.Layouts = layoutEntries;
#endregion
return View(viewModel);
}
[HttpPost]
public ActionResult Delete(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage queries")))
return new HttpUnauthorizedResult();
var query = _queryService.GetQuery(id);
if (query == null) {
return HttpNotFound();
}
Services.ContentManager.Remove(query.ContentItem);
Services.Notifier.Information(T("Query {0} deleted", query.Name));
return RedirectToAction("Index");
}
public ActionResult Preview(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage queries")))
return new HttpUnauthorizedResult();
var contentItems = _projectionManager.GetContentItems(id, 0, 20);
var contentShapes = contentItems.Select(item => _services.ContentManager.BuildDisplay(item, "Summary"));
var list = Shape.List();
list.AddRange(contentShapes);
return View((object)list);
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal sealed class StatementSyntaxComparer : SyntaxComparer
{
internal static readonly StatementSyntaxComparer Default = new StatementSyntaxComparer();
private readonly SyntaxNode _oldRootChild;
private readonly SyntaxNode _newRootChild;
private readonly SyntaxNode _oldRoot;
private readonly SyntaxNode _newRoot;
private StatementSyntaxComparer()
{
}
internal StatementSyntaxComparer(SyntaxNode oldRootChild, SyntaxNode newRootChild)
{
_oldRootChild = oldRootChild;
_newRootChild = newRootChild;
_oldRoot = oldRootChild.Parent;
_newRoot = newRootChild.Parent;
}
#region Tree Traversal
protected internal override bool TryGetParent(SyntaxNode node, out SyntaxNode parent)
{
parent = node.Parent;
while (parent != null && !HasLabel(parent))
{
parent = parent.Parent;
}
return parent != null;
}
protected internal override IEnumerable<SyntaxNode> GetChildren(SyntaxNode node)
{
Debug.Assert(HasLabel(node));
if (node == _oldRoot || node == _newRoot)
{
return EnumerateRootChildren(node);
}
return IsLeaf(node) ? null : EnumerateNonRootChildren(node);
}
private IEnumerable<SyntaxNode> EnumerateNonRootChildren(SyntaxNode node)
{
foreach (var child in node.ChildNodes())
{
if (LambdaUtilities.IsLambdaBodyStatementOrExpression(child))
{
continue;
}
if (HasLabel(child))
{
yield return child;
}
else
{
foreach (var descendant in child.DescendantNodes(DescendIntoChildren))
{
if (HasLabel(descendant))
{
yield return descendant;
}
}
}
}
}
private IEnumerable<SyntaxNode> EnumerateRootChildren(SyntaxNode root)
{
Debug.Assert(_oldRoot != null && _newRoot != null);
var child = (root == _oldRoot) ? _oldRootChild : _newRootChild;
if (GetLabelImpl(child) != Label.Ignored)
{
yield return child;
}
else
{
foreach (var descendant in child.DescendantNodes(DescendIntoChildren))
{
if (HasLabel(descendant))
{
yield return descendant;
}
}
}
}
private bool DescendIntoChildren(SyntaxNode node)
{
return !LambdaUtilities.IsLambdaBodyStatementOrExpression(node) && !HasLabel(node);
}
protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node)
{
if (node == _oldRoot || node == _newRoot)
{
Debug.Assert(_oldRoot != null && _newRoot != null);
var rootChild = (node == _oldRoot) ? _oldRootChild : _newRootChild;
if (HasLabel(rootChild))
{
yield return rootChild;
}
node = rootChild;
}
// TODO: avoid allocation of closure
foreach (var descendant in node.DescendantNodes(descendIntoChildren: c => !IsLeaf(c) && (c == node || !LambdaUtilities.IsLambdaBodyStatementOrExpression(c))))
{
if (!LambdaUtilities.IsLambdaBodyStatementOrExpression(descendant) && HasLabel(descendant))
{
yield return descendant;
}
}
}
private static bool IsLeaf(SyntaxNode node)
{
Classify(node.Kind(), node, out var isLeaf);
return isLeaf;
}
#endregion
#region Labels
// Assumptions:
// - Each listed label corresponds to one or more syntax kinds.
// - Nodes with same labels might produce Update edits, nodes with different labels don't.
// - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label.
// (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label).
internal enum Label
{
ConstructorDeclaration,
Block,
CheckedStatement,
UnsafeStatement,
TryStatement,
CatchClause, // tied to parent
CatchDeclaration, // tied to parent
CatchFilterClause, // tied to parent
FinallyClause, // tied to parent
ForStatement,
ForStatementPart, // tied to parent
ForEachStatement,
UsingStatement,
FixedStatement,
LockStatement,
WhileStatement,
DoStatement,
IfStatement,
ElseClause, // tied to parent
SwitchStatement,
SwitchSection,
CasePatternSwitchLabel, // tied to parent
WhenClause,
YieldStatement, // tied to parent
GotoStatement,
GotoCaseStatement,
BreakContinueStatement,
ReturnThrowStatement,
ExpressionStatement,
LabeledStatement,
LocalFunction,
// TODO:
// Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.)
// Also consider handling LocalDeclarationStatement as just a bag of variable declarators,
// so that variable declarators contained in one can be matched with variable declarators contained in the other.
LocalDeclarationStatement, // tied to parent
LocalVariableDeclaration, // tied to parent
LocalVariableDeclarator, // tied to parent
SingleVariableDesignation,
AwaitExpression,
Lambda,
FromClause,
QueryBody,
FromClauseLambda, // tied to parent
LetClauseLambda, // tied to parent
WhereClauseLambda, // tied to parent
OrderByClause, // tied to parent
OrderingLambda, // tied to parent
SelectClauseLambda, // tied to parent
JoinClauseLambda, // tied to parent
JoinIntoClause, // tied to parent
GroupClauseLambda, // tied to parent
QueryContinuation, // tied to parent
// helpers:
Count,
Ignored = IgnoredNode
}
private static int TiedToAncestor(Label label)
{
switch (label)
{
case Label.LocalDeclarationStatement:
case Label.LocalVariableDeclaration:
case Label.LocalVariableDeclarator:
case Label.GotoCaseStatement:
case Label.BreakContinueStatement:
case Label.ElseClause:
case Label.CatchClause:
case Label.CatchDeclaration:
case Label.CatchFilterClause:
case Label.FinallyClause:
case Label.ForStatementPart:
case Label.YieldStatement:
case Label.LocalFunction:
case Label.FromClauseLambda:
case Label.LetClauseLambda:
case Label.WhereClauseLambda:
case Label.OrderByClause:
case Label.OrderingLambda:
case Label.SelectClauseLambda:
case Label.JoinClauseLambda:
case Label.JoinIntoClause:
case Label.GroupClauseLambda:
case Label.QueryContinuation:
case Label.CasePatternSwitchLabel:
return 1;
default:
return 0;
}
}
/// <summary>
/// <paramref name="nodeOpt"/> is null only when comparing value equality of a tree node.
/// </summary>
internal static Label Classify(SyntaxKind kind, SyntaxNode nodeOpt, out bool isLeaf)
{
// Notes:
// A descendant of a leaf node may be a labeled node that we don't want to visit if
// we are comparing its parent node (used for lambda bodies).
//
// Expressions are ignored but they may contain nodes that should be matched by tree comparer.
// (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren.
isLeaf = false;
// If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart".
// We need to capture it in the match since these expressions can be "active statements" and as such we need to map them.
//
// The parent is not available only when comparing nodes for value equality.
if (nodeOpt != null && nodeOpt.Parent.IsKind(SyntaxKind.ForStatement) && nodeOpt is ExpressionSyntax)
{
return Label.ForStatementPart;
}
switch (kind)
{
case SyntaxKind.ConstructorDeclaration:
// Root when matching constructor bodies.
return Label.ConstructorDeclaration;
case SyntaxKind.Block:
return Label.Block;
case SyntaxKind.LocalDeclarationStatement:
return Label.LocalDeclarationStatement;
case SyntaxKind.VariableDeclaration:
return Label.LocalVariableDeclaration;
case SyntaxKind.VariableDeclarator:
return Label.LocalVariableDeclarator;
case SyntaxKind.SingleVariableDesignation:
return Label.SingleVariableDesignation;
case SyntaxKind.LabeledStatement:
return Label.LabeledStatement;
case SyntaxKind.EmptyStatement:
isLeaf = true;
return Label.Ignored;
case SyntaxKind.GotoStatement:
isLeaf = true;
return Label.GotoStatement;
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoDefaultStatement:
isLeaf = true;
return Label.GotoCaseStatement;
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
isLeaf = true;
return Label.BreakContinueStatement;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
return Label.ReturnThrowStatement;
case SyntaxKind.ExpressionStatement:
return Label.ExpressionStatement;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
return Label.YieldStatement;
case SyntaxKind.DoStatement:
return Label.DoStatement;
case SyntaxKind.WhileStatement:
return Label.WhileStatement;
case SyntaxKind.ForStatement:
return Label.ForStatement;
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForEachStatement:
return Label.ForEachStatement;
case SyntaxKind.UsingStatement:
return Label.UsingStatement;
case SyntaxKind.FixedStatement:
return Label.FixedStatement;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return Label.CheckedStatement;
case SyntaxKind.UnsafeStatement:
return Label.UnsafeStatement;
case SyntaxKind.LockStatement:
return Label.LockStatement;
case SyntaxKind.IfStatement:
return Label.IfStatement;
case SyntaxKind.ElseClause:
return Label.ElseClause;
case SyntaxKind.SwitchStatement:
return Label.SwitchStatement;
case SyntaxKind.SwitchSection:
return Label.SwitchSection;
case SyntaxKind.CaseSwitchLabel:
case SyntaxKind.DefaultSwitchLabel:
// Switch labels are included in the "value" of the containing switch section.
// We don't need to analyze case expressions.
isLeaf = true;
return Label.Ignored;
case SyntaxKind.WhenClause:
return Label.WhenClause;
case SyntaxKind.CasePatternSwitchLabel:
return Label.CasePatternSwitchLabel;
case SyntaxKind.TryStatement:
return Label.TryStatement;
case SyntaxKind.CatchClause:
return Label.CatchClause;
case SyntaxKind.CatchDeclaration:
// the declarator of the exception variable
return Label.CatchDeclaration;
case SyntaxKind.CatchFilterClause:
return Label.CatchFilterClause;
case SyntaxKind.FinallyClause:
return Label.FinallyClause;
case SyntaxKind.LocalFunctionStatement:
return Label.LocalFunction;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
return Label.Lambda;
case SyntaxKind.FromClause:
// The first from clause of a query is not a lambda.
// We have to assign it a label different from "FromClauseLambda"
// so that we won't match lambda-from to non-lambda-from.
//
// Since FromClause declares range variables we need to include it in the map,
// so that we are able to map range variable declarations.
// Therefore we assign it a dedicated label.
//
// The parent is not available only when comparing nodes for value equality.
// In that case it doesn't matter what label the node has as long as it has some.
if (nodeOpt == null || nodeOpt.Parent.IsKind(SyntaxKind.QueryExpression))
{
return Label.FromClause;
}
return Label.FromClauseLambda;
case SyntaxKind.QueryBody:
return Label.QueryBody;
case SyntaxKind.QueryContinuation:
return Label.QueryContinuation;
case SyntaxKind.LetClause:
return Label.LetClauseLambda;
case SyntaxKind.WhereClause:
return Label.WhereClauseLambda;
case SyntaxKind.OrderByClause:
return Label.OrderByClause;
case SyntaxKind.AscendingOrdering:
case SyntaxKind.DescendingOrdering:
return Label.OrderingLambda;
case SyntaxKind.SelectClause:
return Label.SelectClauseLambda;
case SyntaxKind.JoinClause:
return Label.JoinClauseLambda;
case SyntaxKind.JoinIntoClause:
return Label.JoinIntoClause;
case SyntaxKind.GroupClause:
return Label.GroupClauseLambda;
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
case SyntaxKind.GenericName:
case SyntaxKind.TypeArgumentList:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.PredefinedType:
case SyntaxKind.ArrayType:
case SyntaxKind.ArrayRankSpecifier:
case SyntaxKind.PointerType:
case SyntaxKind.NullableType:
case SyntaxKind.TupleType:
case SyntaxKind.RefType:
case SyntaxKind.OmittedTypeArgument:
case SyntaxKind.NameColon:
case SyntaxKind.StackAllocArrayCreationExpression:
case SyntaxKind.OmittedArraySizeExpression:
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
case SyntaxKind.ArgListExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.TypeOfExpression:
case SyntaxKind.SizeOfExpression:
case SyntaxKind.DefaultExpression:
case SyntaxKind.ConstantPattern:
case SyntaxKind.DiscardDesignation:
// can't contain a lambda/await/anonymous type:
isLeaf = true;
return Label.Ignored;
case SyntaxKind.AwaitExpression:
return Label.AwaitExpression;
default:
// any other node may contain a lambda:
return Label.Ignored;
}
}
protected internal override int GetLabel(SyntaxNode node)
{
return (int)GetLabelImpl(node);
}
internal static Label GetLabelImpl(SyntaxNode node)
{
return Classify(node.Kind(), node, out var isLeaf);
}
internal static bool HasLabel(SyntaxNode node)
{
return GetLabelImpl(node) != Label.Ignored;
}
protected internal override int LabelCount
{
get { return (int)Label.Count; }
}
protected internal override int TiedToAncestor(int label)
{
return TiedToAncestor((Label)label);
}
#endregion
#region Comparisons
internal static bool IgnoreLabeledChild(SyntaxKind kind)
{
// In most cases we can determine Label based on child kind.
// The only cases when we can't are
// - for Initializer, Condition and Incrementor expressions in ForStatement.
// - first from clause of a query expression.
return Classify(kind, null, out var isLeaf) != Label.Ignored;
}
public override bool ValuesEqual(SyntaxNode left, SyntaxNode right)
{
// only called from the tree matching alg, which only operates on nodes that are labeled.
Debug.Assert(HasLabel(left));
Debug.Assert(HasLabel(right));
Func<SyntaxKind, bool> ignoreChildNode;
switch (left.Kind())
{
case SyntaxKind.SwitchSection:
return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right);
case SyntaxKind.ForStatement:
// The only children of ForStatement are labeled nodes and punctuation.
return true;
default:
// When comparing the value of a node with its partner we are deciding whether to add an Update edit for the pair.
// If the actual change is under a descendant labeled node we don't want to attribute it to the node being compared,
// so we skip all labeled children when recursively checking for equivalence.
if (IsLeaf(left))
{
ignoreChildNode = null;
}
else
{
ignoreChildNode = IgnoreLabeledChild;
}
break;
}
return SyntaxFactory.AreEquivalent(left, right, ignoreChildNode);
}
private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right)
{
return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null)
&& SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: IgnoreLabeledChild);
}
protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance)
{
switch (leftNode.Kind())
{
case SyntaxKind.VariableDeclarator:
distance = ComputeDistance(
((VariableDeclaratorSyntax)leftNode).Identifier,
((VariableDeclaratorSyntax)rightNode).Identifier);
return true;
case SyntaxKind.ForStatement:
var leftFor = (ForStatementSyntax)leftNode;
var rightFor = (ForStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftFor, rightFor);
return true;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
{
var leftForEach = (CommonForEachStatementSyntax)leftNode;
var rightForEach = (CommonForEachStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftForEach, rightForEach);
return true;
}
case SyntaxKind.UsingStatement:
var leftUsing = (UsingStatementSyntax)leftNode;
var rightUsing = (UsingStatementSyntax)rightNode;
if (leftUsing.Declaration != null && rightUsing.Declaration != null)
{
distance = ComputeWeightedDistance(
leftUsing.Declaration,
leftUsing.Statement,
rightUsing.Declaration,
rightUsing.Statement);
}
else
{
distance = ComputeWeightedDistance(
(SyntaxNode)leftUsing.Expression ?? leftUsing.Declaration,
leftUsing.Statement,
(SyntaxNode)rightUsing.Expression ?? rightUsing.Declaration,
rightUsing.Statement);
}
return true;
case SyntaxKind.LockStatement:
var leftLock = (LockStatementSyntax)leftNode;
var rightLock = (LockStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement);
return true;
case SyntaxKind.FixedStatement:
var leftFixed = (FixedStatementSyntax)leftNode;
var rightFixed = (FixedStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement);
return true;
case SyntaxKind.WhileStatement:
var leftWhile = (WhileStatementSyntax)leftNode;
var rightWhile = (WhileStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement);
return true;
case SyntaxKind.DoStatement:
var leftDo = (DoStatementSyntax)leftNode;
var rightDo = (DoStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement);
return true;
case SyntaxKind.IfStatement:
var leftIf = (IfStatementSyntax)leftNode;
var rightIf = (IfStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement);
return true;
case SyntaxKind.Block:
BlockSyntax leftBlock = (BlockSyntax)leftNode;
BlockSyntax rightBlock = (BlockSyntax)rightNode;
return TryComputeWeightedDistance(leftBlock, rightBlock, out distance);
case SyntaxKind.CatchClause:
distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode);
return true;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
distance = ComputeWeightedDistanceOfLambdas(leftNode, rightNode);
return true;
case SyntaxKind.LocalFunctionStatement:
distance = ComputeWeightedDistanceOfLocalFunctions((LocalFunctionStatementSyntax)leftNode, (LocalFunctionStatementSyntax)rightNode);
return true;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
// Ignore the expression of yield return. The structure of the state machine is more important than the yielded values.
distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1;
return true;
default:
distance = 0;
return false;
}
}
private static double ComputeWeightedDistanceOfLocalFunctions(LocalFunctionStatementSyntax leftNode, LocalFunctionStatementSyntax rightNode)
{
double modifierDistance = ComputeDistance(leftNode.Modifiers, rightNode.Modifiers);
double returnTypeDistance = ComputeDistance(leftNode.ReturnType, rightNode.ReturnType);
double identifierDistance = ComputeDistance(leftNode.Identifier, rightNode.Identifier);
double typeParameterDistance = ComputeDistance(leftNode.TypeParameterList, rightNode.TypeParameterList);
double parameterDistance = ComputeDistance(leftNode.ParameterList.Parameters, rightNode.ParameterList.Parameters);
double bodyDistance = ComputeDistance((SyntaxNode)leftNode.Body ?? leftNode.ExpressionBody, (SyntaxNode)rightNode.Body ?? rightNode.ExpressionBody);
return
modifierDistance * 0.1 +
returnTypeDistance * 0.1 +
identifierDistance * 0.2 +
typeParameterDistance * 0.2 +
parameterDistance * 0.2 +
bodyDistance * 0.2;
}
private static double ComputeWeightedDistanceOfLambdas(SyntaxNode leftNode, SyntaxNode rightNode)
{
GetLambdaParts(leftNode, out var leftParameters, out var leftAsync, out var leftBody);
GetLambdaParts(rightNode, out var rightParameters, out var rightAsync, out var rightBody);
if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword))
{
return 1.0;
}
double parameterDistance = ComputeDistance(leftParameters, rightParameters);
double bodyDistance = ComputeDistance(leftBody, rightBody);
return parameterDistance * 0.6 + bodyDistance * 0.4;
}
private static void GetLambdaParts(SyntaxNode lambda, out IEnumerable<SyntaxToken> parameters, out SyntaxToken asyncKeyword, out SyntaxNode body)
{
switch (lambda.Kind())
{
case SyntaxKind.SimpleLambdaExpression:
var simple = (SimpleLambdaExpressionSyntax)lambda;
parameters = simple.Parameter.DescendantTokens();
asyncKeyword = simple.AsyncKeyword;
body = simple.Body;
break;
case SyntaxKind.ParenthesizedLambdaExpression:
var parenthesized = (ParenthesizedLambdaExpressionSyntax)lambda;
parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters);
asyncKeyword = parenthesized.AsyncKeyword;
body = parenthesized.Body;
break;
case SyntaxKind.AnonymousMethodExpression:
var anonymous = (AnonymousMethodExpressionSyntax)lambda;
if (anonymous.ParameterList != null)
{
parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters);
}
else
{
parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>();
}
asyncKeyword = anonymous.AsyncKeyword;
body = anonymous.Block;
break;
default:
throw ExceptionUtilities.UnexpectedValue(lambda.Kind());
}
}
private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance)
{
// No block can be matched with the root block.
// Note that in constructors the root is the constructor declaration, since we need to include
// the constructor initializer in the match.
if (leftBlock.Parent == null ||
rightBlock.Parent == null ||
leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) ||
rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
{
distance = 0.0;
return true;
}
if (GetLabel(leftBlock.Parent) != GetLabel(rightBlock.Parent))
{
distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock);
return true;
}
switch (leftBlock.Parent.Kind())
{
case SyntaxKind.IfStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.FixedStatement:
case SyntaxKind.LockStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.SwitchSection:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
// value distance of the block body is included:
distance = GetDistance(leftBlock.Parent, rightBlock.Parent);
return true;
case SyntaxKind.CatchClause:
var leftCatch = (CatchClauseSyntax)leftBlock.Parent;
var rightCatch = (CatchClauseSyntax)rightBlock.Parent;
if (leftCatch.Declaration == null && leftCatch.Filter == null &&
rightCatch.Declaration == null && rightCatch.Filter == null)
{
var leftTry = (TryStatementSyntax)leftCatch.Parent;
var rightTry = (TryStatementSyntax)rightCatch.Parent;
distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) +
0.5 * ComputeValueDistance(leftBlock, rightBlock);
}
else
{
// value distance of the block body is included:
distance = GetDistance(leftBlock.Parent, rightBlock.Parent);
}
return true;
case SyntaxKind.Block:
case SyntaxKind.LabeledStatement:
distance = ComputeWeightedBlockDistance(leftBlock, rightBlock);
return true;
case SyntaxKind.UnsafeStatement:
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
case SyntaxKind.ElseClause:
case SyntaxKind.FinallyClause:
case SyntaxKind.TryStatement:
distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock);
return true;
default:
throw ExceptionUtilities.UnexpectedValue(leftBlock.Parent.Kind());
}
}
private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock)
{
if (TryComputeLocalsDistance(leftBlock, rightBlock, out var distance))
{
return distance;
}
return ComputeValueDistance(leftBlock, rightBlock);
}
private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right)
{
double blockDistance = ComputeDistance(left.Block, right.Block);
double distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter);
return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3);
}
private static double ComputeWeightedDistance(
CommonForEachStatementSyntax leftCommonForEach,
CommonForEachStatementSyntax rightCommonForEach)
{
double statementDistance = ComputeDistance(leftCommonForEach.Statement, rightCommonForEach.Statement);
double expressionDistance = ComputeDistance(leftCommonForEach.Expression, rightCommonForEach.Expression);
List<SyntaxToken> leftLocals = null;
List<SyntaxToken> rightLocals = null;
GetLocalNames(leftCommonForEach, ref leftLocals);
GetLocalNames(rightCommonForEach, ref rightLocals);
double localNamesDistance = ComputeDistance(leftLocals, rightLocals);
double distance = localNamesDistance * 0.6 + expressionDistance * 0.2 + statementDistance * 0.2;
return AdjustForLocalsInBlock(distance, leftCommonForEach.Statement, rightCommonForEach.Statement, localsWeight: 0.6);
}
private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right)
{
double statementDistance = ComputeDistance(left.Statement, right.Statement);
double conditionDistance = ComputeDistance(left.Condition, right.Condition);
double incDistance = ComputeDistance(
GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors));
double distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4;
if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out var localsDistance))
{
distance = distance * 0.4 + localsDistance * 0.6;
}
return distance;
}
private static double ComputeWeightedDistance(
VariableDeclarationSyntax leftVariables,
StatementSyntax leftStatement,
VariableDeclarationSyntax rightVariables,
StatementSyntax rightStatement)
{
double distance = ComputeDistance(leftStatement, rightStatement);
// Put maximum weight behind the variables declared in the header of the statement.
if (TryComputeLocalsDistance(leftVariables, rightVariables, out var localsDistance))
{
distance = distance * 0.4 + localsDistance * 0.6;
}
// If the statement is a block that declares local variables,
// weight them more than the rest of the statement.
return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2);
}
private static double ComputeWeightedDistance(
SyntaxNode leftHeaderOpt,
StatementSyntax leftStatement,
SyntaxNode rightHeaderOpt,
StatementSyntax rightStatement)
{
Debug.Assert(leftStatement != null);
Debug.Assert(rightStatement != null);
double headerDistance = ComputeDistance(leftHeaderOpt, rightHeaderOpt);
double statementDistance = ComputeDistance(leftStatement, rightStatement);
double distance = headerDistance * 0.6 + statementDistance * 0.4;
return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5);
}
private static double AdjustForLocalsInBlock(
double distance,
StatementSyntax leftStatement,
StatementSyntax rightStatement,
double localsWeight)
{
// If the statement is a block that declares local variables,
// weight them more than the rest of the statement.
if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block)
{
if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out var localsDistance))
{
return localsDistance * localsWeight + distance * (1 - localsWeight);
}
}
return distance;
}
private static bool TryComputeLocalsDistance(VariableDeclarationSyntax leftOpt, VariableDeclarationSyntax rightOpt, out double distance)
{
List<SyntaxToken> leftLocals = null;
List<SyntaxToken> rightLocals = null;
if (leftOpt != null)
{
GetLocalNames(leftOpt, ref leftLocals);
}
if (rightOpt != null)
{
GetLocalNames(rightOpt, ref rightLocals);
}
if (leftLocals == null || rightLocals == null)
{
distance = 0;
return false;
}
distance = ComputeDistance(leftLocals, rightLocals);
return true;
}
private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance)
{
List<SyntaxToken> leftLocals = null;
List<SyntaxToken> rightLocals = null;
GetLocalNames(left, ref leftLocals);
GetLocalNames(right, ref rightLocals);
if (leftLocals == null || rightLocals == null)
{
distance = 0;
return false;
}
distance = ComputeDistance(leftLocals, rightLocals);
return true;
}
// doesn't include variables declared in declaration expressions
private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken> result)
{
foreach (var child in block.ChildNodes())
{
if (child.IsKind(SyntaxKind.LocalDeclarationStatement))
{
GetLocalNames(((LocalDeclarationStatementSyntax)child).Declaration, ref result);
}
}
}
// doesn't include variables declared in declaration expressions
private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken> result)
{
foreach (var local in localDeclaration.Variables)
{
GetLocalNames(local.Identifier, ref result);
}
}
private static void GetLocalNames(CommonForEachStatementSyntax commonForEach, ref List<SyntaxToken> result)
{
switch (commonForEach.Kind())
{
case SyntaxKind.ForEachStatement:
GetLocalNames(((ForEachStatementSyntax)commonForEach).Identifier, ref result);
return;
case SyntaxKind.ForEachVariableStatement:
var forEachVariable = (ForEachVariableStatementSyntax)commonForEach;
GetLocalNames(forEachVariable.Variable, ref result);
return;
default: throw ExceptionUtilities.UnexpectedValue(commonForEach.Kind());
}
}
private static void GetLocalNames(ExpressionSyntax expression, ref List<SyntaxToken> result)
{
switch (expression.Kind())
{
case SyntaxKind.DeclarationExpression:
var declarationExpression = (DeclarationExpressionSyntax)expression;
var localDeclaration = declarationExpression.Designation;
GetLocalNames(localDeclaration, ref result);
return;
case SyntaxKind.TupleExpression:
var tupleExpression = (TupleExpressionSyntax)expression;
foreach(var argument in tupleExpression.Arguments)
{
GetLocalNames(argument.Expression, ref result);
}
return;
default:
// Do nothing for node that cannot have variable declarations inside.
return;
}
}
private static void GetLocalNames(VariableDesignationSyntax designation, ref List<SyntaxToken> result)
{
switch (designation.Kind())
{
case SyntaxKind.SingleVariableDesignation:
GetLocalNames(((SingleVariableDesignationSyntax)designation).Identifier, ref result);
return;
case SyntaxKind.ParenthesizedVariableDesignation:
var parenthesizedVariableDesignation = (ParenthesizedVariableDesignationSyntax)designation;
foreach(var variableDesignation in parenthesizedVariableDesignation.Variables)
{
GetLocalNames(variableDesignation, ref result);
}
return;
default: throw ExceptionUtilities.UnexpectedValue(designation.Kind());
}
}
private static void GetLocalNames(SyntaxToken syntaxToken, ref List<SyntaxToken> result)
{
if (result == null)
{
result = new List<SyntaxToken>();
}
result.Add(syntaxToken);
}
private static double CombineOptional(
double distance0,
SyntaxNode leftOpt1,
SyntaxNode rightOpt1,
SyntaxNode leftOpt2,
SyntaxNode rightOpt2,
double weight0 = 0.8,
double weight1 = 0.5)
{
bool one = leftOpt1 != null || rightOpt1 != null;
bool two = leftOpt2 != null || rightOpt2 != null;
if (!one && !two)
{
return distance0;
}
double distance1 = ComputeDistance(leftOpt1, rightOpt1);
double distance2 = ComputeDistance(leftOpt2, rightOpt2);
double d;
if (one && two)
{
d = distance1 * weight1 + distance2 * (1 - weight1);
}
else if (one)
{
d = distance1;
}
else
{
d = distance2;
}
return distance0 * weight0 + d * (1 - weight0);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net.Config;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Tests.Common;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests
{
[TestFixture]
public class GridConnectorsTests : OpenSimTestCase
{
LocalGridServicesConnector m_LocalConnector;
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("GridService");
config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
config.Configs["GridService"].Set("Region_Test_Region_1", "DefaultRegion");
config.Configs["GridService"].Set("Region_Test_Region_2", "FallbackRegion");
config.Configs["GridService"].Set("Region_Test_Region_3", "FallbackRegion");
config.Configs["GridService"].Set("Region_Other_Region_4", "FallbackRegion");
m_LocalConnector = new LocalGridServicesConnector(config, null);
}
/// <summary>
/// Test region registration.
/// </summary>
[Test]
public void TestRegisterRegion()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
// Create 4 regions
GridRegion r1 = new GridRegion();
r1.RegionName = "Test Region 1";
r1.RegionID = new UUID(1);
r1.RegionLocX = 1000 * (int)Constants.RegionSize;
r1.RegionLocY = 1000 * (int)Constants.RegionSize;
r1.ExternalHostName = "127.0.0.1";
r1.HttpPort = 9001;
r1.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
Scene s = new Scene(new RegionInfo());
s.RegionInfo.RegionID = r1.RegionID;
m_LocalConnector.AddRegion(s);
GridRegion r2 = new GridRegion();
r2.RegionName = "Test Region 2";
r2.RegionID = new UUID(2);
r2.RegionLocX = 1001 * (int)Constants.RegionSize;
r2.RegionLocY = 1000 * (int)Constants.RegionSize;
r2.ExternalHostName = "127.0.0.1";
r2.HttpPort = 9002;
r2.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
s = new Scene(new RegionInfo());
s.RegionInfo.RegionID = r2.RegionID;
m_LocalConnector.AddRegion(s);
GridRegion r3 = new GridRegion();
r3.RegionName = "Test Region 3";
r3.RegionID = new UUID(3);
r3.RegionLocX = 1005 * (int)Constants.RegionSize;
r3.RegionLocY = 1000 * (int)Constants.RegionSize;
r3.ExternalHostName = "127.0.0.1";
r3.HttpPort = 9003;
r3.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
s = new Scene(new RegionInfo());
s.RegionInfo.RegionID = r3.RegionID;
m_LocalConnector.AddRegion(s);
GridRegion r4 = new GridRegion();
r4.RegionName = "Other Region 4";
r4.RegionID = new UUID(4);
r4.RegionLocX = 1004 * (int)Constants.RegionSize;
r4.RegionLocY = 1002 * (int)Constants.RegionSize;
r4.ExternalHostName = "127.0.0.1";
r4.HttpPort = 9004;
r4.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
s = new Scene(new RegionInfo());
s.RegionInfo.RegionID = r4.RegionID;
m_LocalConnector.AddRegion(s);
m_LocalConnector.RegisterRegion(UUID.Zero, r1);
GridRegion result = m_LocalConnector.GetRegionByName(UUID.Zero, "Test");
Assert.IsNull(result, "Retrieved GetRegionByName \"Test\" is not null");
result = m_LocalConnector.GetRegionByName(UUID.Zero, "Test Region 1");
Assert.IsNotNull(result, "Retrieved GetRegionByName is null");
Assert.That(result.RegionName, Is.EqualTo("Test Region 1"), "Retrieved region's name does not match");
m_LocalConnector.RegisterRegion(UUID.Zero, r2);
m_LocalConnector.RegisterRegion(UUID.Zero, r3);
m_LocalConnector.RegisterRegion(UUID.Zero, r4);
result = m_LocalConnector.GetRegionByUUID(UUID.Zero, new UUID(1));
Assert.IsNotNull(result, "Retrieved GetRegionByUUID is null");
Assert.That(result.RegionID, Is.EqualTo(new UUID(1)), "Retrieved region's UUID does not match");
result = m_LocalConnector.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc(1000), (int)Util.RegionToWorldLoc(1000));
Assert.IsNotNull(result, "Retrieved GetRegionByPosition is null");
Assert.That(result.RegionLocX, Is.EqualTo(1000 * (int)Constants.RegionSize), "Retrieved region's position does not match");
List<GridRegion> results = m_LocalConnector.GetNeighbours(UUID.Zero, new UUID(1));
Assert.IsNotNull(results, "Retrieved neighbours list is null");
Assert.That(results.Count, Is.EqualTo(1), "Retrieved neighbour collection is greater than expected");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(2)), "Retrieved region's UUID does not match");
results = m_LocalConnector.GetRegionsByName(UUID.Zero, "Test", 10);
Assert.IsNotNull(results, "Retrieved GetRegionsByName collection is null");
Assert.That(results.Count, Is.EqualTo(3), "Retrieved neighbour collection is less than expected");
results = m_LocalConnector.GetRegionRange(UUID.Zero, 900 * (int)Constants.RegionSize, 1002 * (int)Constants.RegionSize,
900 * (int)Constants.RegionSize, 1100 * (int)Constants.RegionSize);
Assert.IsNotNull(results, "Retrieved GetRegionRange collection is null");
Assert.That(results.Count, Is.EqualTo(2), "Retrieved neighbour collection is not the number expected");
results = m_LocalConnector.GetDefaultRegions(UUID.Zero);
Assert.IsNotNull(results, "Retrieved GetDefaultRegions collection is null");
Assert.That(results.Count, Is.EqualTo(1), "Retrieved default regions collection has not the expected size");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(1)), "Retrieved default region's UUID does not match");
results = m_LocalConnector.GetFallbackRegions(UUID.Zero, r1.RegionLocX, r1.RegionLocY);
Assert.IsNotNull(results, "Retrieved GetFallbackRegions collection for region 1 is null");
Assert.That(results.Count, Is.EqualTo(3), "Retrieved fallback regions collection for region 1 has not the expected size");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(2)), "Retrieved fallback regions for default region are not in the expected order 2-4-3");
Assert.That(results[1].RegionID, Is.EqualTo(new UUID(4)), "Retrieved fallback regions for default region are not in the expected order 2-4-3");
Assert.That(results[2].RegionID, Is.EqualTo(new UUID(3)), "Retrieved fallback regions for default region are not in the expected order 2-4-3");
results = m_LocalConnector.GetFallbackRegions(UUID.Zero, r2.RegionLocX, r2.RegionLocY);
Assert.IsNotNull(results, "Retrieved GetFallbackRegions collection for region 2 is null");
Assert.That(results.Count, Is.EqualTo(3), "Retrieved fallback regions collection for region 2 has not the expected size");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(2)), "Retrieved fallback regions are not in the expected order 2-4-3");
Assert.That(results[1].RegionID, Is.EqualTo(new UUID(4)), "Retrieved fallback regions are not in the expected order 2-4-3");
Assert.That(results[2].RegionID, Is.EqualTo(new UUID(3)), "Retrieved fallback regions are not in the expected order 2-4-3");
results = m_LocalConnector.GetFallbackRegions(UUID.Zero, r3.RegionLocX, r3.RegionLocY);
Assert.IsNotNull(results, "Retrieved GetFallbackRegions collection for region 3 is null");
Assert.That(results.Count, Is.EqualTo(3), "Retrieved fallback regions collection for region 3 has not the expected size");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(3)), "Retrieved fallback regions are not in the expected order 3-4-2");
Assert.That(results[1].RegionID, Is.EqualTo(new UUID(4)), "Retrieved fallback regions are not in the expected order 3-4-2");
Assert.That(results[2].RegionID, Is.EqualTo(new UUID(2)), "Retrieved fallback regions are not in the expected order 3-4-2");
results = m_LocalConnector.GetFallbackRegions(UUID.Zero, r4.RegionLocX, r4.RegionLocY);
Assert.IsNotNull(results, "Retrieved GetFallbackRegions collection for region 4 is null");
Assert.That(results.Count, Is.EqualTo(3), "Retrieved fallback regions collection for region 4 has not the expected size");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(4)), "Retrieved fallback regions are not in the expected order 4-3-2");
Assert.That(results[1].RegionID, Is.EqualTo(new UUID(3)), "Retrieved fallback regions are not in the expected order 4-3-2");
Assert.That(results[2].RegionID, Is.EqualTo(new UUID(2)), "Retrieved fallback regions are not in the expected order 4-3-2");
results = m_LocalConnector.GetHyperlinks(UUID.Zero);
Assert.IsNotNull(results, "Retrieved GetHyperlinks list is null");
Assert.That(results.Count, Is.EqualTo(0), "Retrieved linked regions collection is not the number expected");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------------
//
// Description:
// This is a class for representing a PackageRelationshipCollection. This is an internal
// class for manipulating relationships associated with a part
//
// Details:
// This class handles serialization to/from relationship parts, creation of those parts
// and offers methods to create, delete and enumerate relationships. This code was
// moved from the PackageRelationshipCollection class.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Xml; // for XmlReader/Writer
using System.IO.Packaging;
using System.IO;
using System.Diagnostics;
namespace System.IO.Packaging
{
/// <summary>
/// Collection of all the relationships corresponding to a given source PackagePart
/// </summary>
internal class InternalRelationshipCollection : IEnumerable<PackageRelationship>
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region IEnumerable
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _relationships.GetEnumerator();
}
/// <summary>
/// Returns an enumertor over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
IEnumerator<PackageRelationship> IEnumerable<PackageRelationship>.GetEnumerator()
{
return _relationships.GetEnumerator();
}
/// <summary>
/// Returns an enumertor over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
public List<PackageRelationship>.Enumerator GetEnumerator()
{
return _relationships.GetEnumerator();
}
#endregion
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <summary>
/// Constructor
/// </summary>
/// <remarks>For use by PackagePart</remarks>
internal InternalRelationshipCollection(PackagePart part) : this(part.Package, part)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <remarks>For use by Package</remarks>
internal InternalRelationshipCollection(Package package) : this(package, null)
{
}
/// <summary>
/// Add new relationship
/// </summary>
/// <param name="targetUri">target</param>
/// <param name="targetMode">Enumeration indicating the base uri for the target uri</param>
/// <param name="relationshipType">relationship type that uniquely defines the role of the relationship</param>
/// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's relationships.
/// Null OK (ID will be generated).</param>
internal PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id)
{
return Add(targetUri, targetMode, relationshipType, id, false /*not parsing*/);
}
/// <summary>
/// Return the relationship whose id is 'id', and null if not found.
/// </summary>
internal PackageRelationship GetRelationship(string id)
{
int index = GetRelationshipIndex(id);
if (index == -1)
return null;
return _relationships[index];
}
/// <summary>
/// Delete relationship with ID 'id'
/// </summary>
/// <param name="id">ID of the relationship to remove</param>
internal void Delete(String id)
{
int index = GetRelationshipIndex(id);
if (index == -1)
return;
_relationships.RemoveAt(index);
_dirty = true;
}
/// <summary>
/// Clear all the relationships in this collection
/// Today it is only used when the entire relationship part is being deleted
/// </summary>
internal void Clear()
{
_relationships.Clear();
_dirty = true;
}
/// <summary>
/// Flush to stream (destructive)
/// </summary>
/// <remarks>
/// Flush part.
/// </remarks>
internal void Flush()
{
if (!_dirty)
return;
if (_relationships.Count == 0) // empty?
{
// delete the part
if (_package.PartExists(_uri))
{
_package.DeletePart(_uri);
}
_relationshipPart = null;
}
else
{
EnsureRelationshipPart(); // lazy init
// write xml
WriteRelationshipPart(_relationshipPart);
}
_dirty = false;
}
internal static void ThrowIfInvalidRelationshipType(string relationshipType)
{
// Look for empty string or string with just spaces
if (relationshipType.Trim() == String.Empty)
throw new ArgumentException(SR.InvalidRelationshipType);
}
// If 'id' is not of the xsd type ID, throw an exception.
internal static void ThrowIfInvalidXsdId(string id)
{
Debug.Assert(id != null, "id should not be null");
try
{
// An XSD ID is an NCName that is unique.
XmlConvert.VerifyNCName(id);
}
catch (XmlException exception)
{
var r = SR.NotAValidXmlIdString;
var s = SR.Format(r, id);
throw new XmlException(s, exception);
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="package">package</param>
/// <param name="part">part will be null if package is the source of the relationships</param>
/// <remarks>Shared constructor</remarks>
private InternalRelationshipCollection(Package package, PackagePart part)
{
Debug.Assert(package != null, "package parameter passed should never be null");
_package = package;
_sourcePart = part;
//_sourcePart may be null representing that the relationships are at the package level
_uri = GetRelationshipPartUri(_sourcePart);
_relationships = new List<PackageRelationship>(4);
// Load if available (not applicable to write-only mode).
if ((package.FileOpenAccess == FileAccess.Read ||
package.FileOpenAccess == FileAccess.ReadWrite) && package.PartExists(_uri))
{
_relationshipPart = package.GetPart(_uri);
ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
ParseRelationshipPart(_relationshipPart);
}
//Any initialization in the constructor should not set the dirty flag to true.
_dirty = false;
}
/// <summary>
/// Returns the associated RelationshipPart for this part
/// </summary>
/// <param name="part">may be null</param>
/// <returns>name of relationship part for the given part</returns>
private static Uri GetRelationshipPartUri(PackagePart part)
{
Uri sourceUri;
if (part == null)
sourceUri = PackUriHelper.PackageRootUri;
else
sourceUri = part.Uri;
return PackUriHelper.GetRelationshipPartUri(sourceUri);
}
/// <summary>
/// Parse PackageRelationship Stream
/// </summary>
/// <param name="part">relationship part</param>
/// <exception cref="XmlException">Thrown if XML is malformed</exception>
private void ParseRelationshipPart(PackagePart part)
{
//We can safely open the stream as FileAccess.Read, as this code
//should only be invoked if the Package has been opened in Read or ReadWrite mode.
Debug.Assert(_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite,
"This method should only be called when FileAccess is Read or ReadWrite");
using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))
{
// load from the relationship part associated with the given part
using (XmlReader baseReader = XmlReader.Create(s))
{
using (XmlCompatibilityReader reader = new XmlCompatibilityReader(baseReader, s_relationshipKnownNamespaces))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitailReadAndVerifyEncoding(baseReader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our tag and namespace pair - throw if other elements are encountered
// Make sure that the current node read is an Element
if (reader.NodeType == XmlNodeType.Element
&& (reader.Depth == 0)
&& (String.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0)
&& (String.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
{
ThrowIfXmlBaseAttributeIsPresent(reader);
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Relationships> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
throw new XmlException(SR.RelationshipsTagHasExtraAttributes, null, reader.LineNumber, reader.LinePosition);
// start tag encountered for Relationships
// now parse individual Relationship tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
if (reader.NodeType == XmlNodeType.Element
&& (reader.Depth == 1)
&& (String.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)
&& (String.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
{
ThrowIfXmlBaseAttributeIsPresent(reader);
int expectedAttributesCount = 3;
string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
if (targetModeAttributeValue != null)
expectedAttributesCount++;
//check if there are expected number of attributes.
//Also any other attribute on the <Relationship> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) == expectedAttributesCount)
{
ProcessRelationshipAttributes(reader);
//Skip the EndElement for Relationship
if (!reader.IsEmptyElement)
ProcessEndElementForRelationshipTag(reader);
}
else throw new XmlException(SR.RelationshipTagDoesntMatchSchema, null, reader.LineNumber, reader.LinePosition);
}
else
if (!(String.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0 && (reader.NodeType == XmlNodeType.EndElement)))
throw new XmlException(SR.UnknownTagEncountered, null, reader.LineNumber, reader.LinePosition);
}
}
else throw new XmlException(SR.ExpectedRelationshipsElementTag, null, reader.LineNumber, reader.LinePosition);
}
}
}
}
//This method processes the attributes that are present on the Relationship element
private void ProcessRelationshipAttributes(XmlCompatibilityReader reader)
{
// Attribute : TargetMode
string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
//If the TargetMode attribute is missing in the underlying markup then we assume it to be internal
TargetMode relationshipTargetMode = TargetMode.Internal;
if (targetModeAttributeValue != null)
{
try
{
relationshipTargetMode = (TargetMode)(Enum.Parse(typeof(TargetMode), targetModeAttributeValue, false /* ignore case */));
}
catch (ArgumentNullException argNullEx)
{
ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argNullEx);
}
catch (ArgumentException argEx)
{
//if the targetModeAttributeValue is not Internal|External then Argument Exception will be thrown.
ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argEx);
}
}
// Attribute : Target
// create a new PackageRelationship
string targetAttributeValue = reader.GetAttribute(s_targetAttributeName);
if (targetAttributeValue == null || targetAttributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_targetAttributeName), null, reader.LineNumber, reader.LinePosition);
Uri targetUri = new Uri(targetAttributeValue, UriKind.RelativeOrAbsolute);
// Attribute : Type
string typeAttributeValue = reader.GetAttribute(s_typeAttributeName);
if (typeAttributeValue == null || typeAttributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_typeAttributeName), null, reader.LineNumber, reader.LinePosition);
// Attribute : Id
// Get the Id attribute (required attribute).
string idAttributeValue = reader.GetAttribute(s_idAttributeName);
if (idAttributeValue == null || idAttributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_idAttributeName), null, reader.LineNumber, reader.LinePosition);
// Add the relationship to the collection
Add(targetUri, relationshipTargetMode, typeAttributeValue, idAttributeValue, true /*parsing*/);
}
//If End element is present for Relationship then we process it
private void ProcessEndElementForRelationshipTag(XmlCompatibilityReader reader)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called if the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, s_relationshipTagName), null, reader.LineNumber, reader.LinePosition);
}
/// <summary>
/// Add new relationship to the Collection
/// </summary>
/// <param name="targetUri">target</param>
/// <param name="targetMode">Enumeration indicating the base uri for the target uri</param>
/// <param name="relationshipType">relationship type that uniquely defines the role of the relationship</param>
/// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's relationships.
/// Null OK (ID will be generated).</param>
/// <param name="parsing">Indicates whether the add call is made while parsing existing relationships
/// from a relationship part, or we are adding a new relationship</param>
private PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id, bool parsing)
{
if (targetUri == null)
throw new ArgumentNullException("targetUri");
if (relationshipType == null)
throw new ArgumentNullException("relationshipType");
ThrowIfInvalidRelationshipType(relationshipType);
//Verify if the Enum value is valid
if (targetMode < TargetMode.Internal || targetMode > TargetMode.External)
throw new ArgumentOutOfRangeException("targetMode");
// don't accept absolute Uri's if targetMode is Internal.
if (targetMode == TargetMode.Internal && targetUri.IsAbsoluteUri)
throw new ArgumentException(SR.RelationshipTargetMustBeRelative, "targetUri");
// don't allow relationships to relationships
// This check should be made for following cases
// 1. Uri is absolute and it is pack Uri
// 2. Uri is NOT absolute and its target mode is internal (or NOT external)
// Note: if the target is absolute uri and its not a pack scheme then we cannot determine if it is a rels part
// Note: if the target is relative uri and target mode is external, we cannot determine if it is a rels part
if ((!targetUri.IsAbsoluteUri && targetMode != TargetMode.External)
|| (targetUri.IsAbsoluteUri && targetUri.Scheme == PackUriHelper.UriSchemePack))
{
Uri resolvedUri = GetResolvedTargetUri(targetUri, targetMode);
//GetResolvedTargetUri returns a null if the target mode is external and the
//target Uri is a packUri with no "part" component, so in that case we know that
//its not a relationship part.
if (resolvedUri != null)
{
if (PackUriHelper.IsRelationshipPartUri(resolvedUri))
throw new ArgumentException(SR.RelationshipToRelationshipIllegal, "targetUri");
}
}
// Generate an ID if id is null. Throw exception if neither null nor a valid unique xsd:ID.
if (id == null)
id = GenerateUniqueRelationshipId();
else
ValidateUniqueRelationshipId(id);
//Ensure the relationship part
EnsureRelationshipPart();
// create and add
PackageRelationship relationship = new PackageRelationship(_package, _sourcePart, targetUri, targetMode, relationshipType, id);
_relationships.Add(relationship);
//If we are adding relationships as a part of Parsing the underlying relationship part, we should not set
//the dirty flag to false.
_dirty = !parsing;
return relationship;
}
/// <summary>
/// Write PackageRelationship Stream
/// </summary>
/// <param name="part">part to persist to</param>
private void WriteRelationshipPart(PackagePart part)
{
using (IgnoreFlushAndCloseStream s = new IgnoreFlushAndCloseStream(part.GetStream()))
{
s.SetLength(0); // truncate to resolve PS 954048
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// start outer Relationships tag
writer.WriteStartElement(s_relationshipsTagName, PackagingUtilities.RelationshipNamespaceUri);
// Write Relationship elements.
WriteRelationshipsAsXml(
writer,
_relationships,
false /* do not systematically write target mode */
);
// end of Relationships tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
}
}
}
/// <summary>
/// Write one Relationship element for each member of relationships.
/// This method is used by XmlDigitalSignatureProcessor code as well
/// </summary>
internal static void WriteRelationshipsAsXml(XmlWriter writer, IEnumerable<PackageRelationship> relationships, bool alwaysWriteTargetModeAttribute)
{
foreach (PackageRelationship relationship in relationships)
{
writer.WriteStartElement(s_relationshipTagName);
// Write RelationshipType attribute.
writer.WriteAttributeString(s_typeAttributeName, relationship.RelationshipType);
// Write Target attribute.
// We would like to persist the uri as passed in by the user and so we use the
// OriginalString property. This makes the persisting behavior consistent
// for relative and absolute Uris.
// Since we accpeted the Uri as a string, we are at the minimum guaranteed that
// the string can be converted to a valid Uri.
// Also, we are just using it here to persist the information and we are not
// resolving or fetching a resource based on this Uri.
writer.WriteAttributeString(s_targetAttributeName, relationship.TargetUri.OriginalString);
// TargetMode is optional attribute in the markup and its default value is TargetMode="Internal"
if (alwaysWriteTargetModeAttribute || relationship.TargetMode == TargetMode.External)
writer.WriteAttributeString(s_targetModeAttributeName, relationship.TargetMode.ToString());
// Write Id attribute.
writer.WriteAttributeString(s_idAttributeName, relationship.Id);
writer.WriteEndElement();
}
}
/// <summary>
/// Ensures that the PackageRelationship PackagePart has been created - lazy init
/// </summary>
/// <remarks>
/// </remarks>
private void EnsureRelationshipPart()
{
if (_relationshipPart == null || _relationshipPart.IsDeleted)
{
if (_package.PartExists(_uri))
{
_relationshipPart = _package.GetPart(_uri);
ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
}
else
{
CompressionOption compressionOption = _sourcePart == null ? CompressionOption.NotCompressed : _sourcePart.CompressionOption;
_relationshipPart = _package.CreatePart(_uri, PackagingUtilities.RelationshipPartContentType.ToString(), compressionOption);
}
}
}
/// <summary>
/// Resolves the target uri in the relationship against the source part or the
/// package root. This resolved Uri is then used by the Add method to figure
/// out if a relationship is being created to another relationship part.
/// </summary>
/// <param name="target">PackageRelationship target uri</param>
/// <param name="targetMode"> Enum value specifying the interpretation of the base uri
/// for the relationship target uri</param>
/// <returns>Resolved Uri</returns>
private Uri GetResolvedTargetUri(Uri target, TargetMode targetMode)
{
if (targetMode == TargetMode.Internal)
{
Debug.Assert(!target.IsAbsoluteUri, "Uri should be relative at this stage");
if (_sourcePart == null) //indicates that the source is the package root
return PackUriHelper.ResolvePartUri(PackUriHelper.PackageRootUri, target);
else
return PackUriHelper.ResolvePartUri(_sourcePart.Uri, target);
}
else
{
if (target.IsAbsoluteUri)
{
if (String.CompareOrdinal(target.Scheme, PackUriHelper.UriSchemePack) == 0)
return PackUriHelper.GetPartUri(target);
}
else
Debug.Assert(false, "Uri should not be relative at this stage");
}
// relative to the location of the package.
return target;
}
//Throws an exception if the relationship part does not have the correct content type
private void ThrowIfIncorrectContentType(ContentType contentType)
{
if (!contentType.AreTypeAndSubTypeEqual(PackagingUtilities.RelationshipPartContentType))
throw new FileFormatException(SR.RelationshipPartIncorrectContentType);
}
//Throws an exception if the xml:base attribute is present in the Relationships XML
private void ThrowIfXmlBaseAttributeIsPresent(XmlCompatibilityReader reader)
{
string xmlBaseAttributeValue = reader.GetAttribute(s_xmlBaseAttributeName);
if (xmlBaseAttributeValue != null)
throw new XmlException(SR.Format(SR.InvalidXmlBaseAttributePresent, s_xmlBaseAttributeName), null, reader.LineNumber, reader.LinePosition);
}
//Throws an XML exception if the attribute value is invalid
private void ThrowForInvalidAttributeValue(XmlCompatibilityReader reader, String attributeName, Exception ex)
{
throw new XmlException(SR.Format(SR.InvalidValueForTheAttribute, attributeName), ex, reader.LineNumber, reader.LinePosition);
}
// Generate a unique relation ID.
private string GenerateUniqueRelationshipId()
{
string id;
do
{
id = GenerateRelationshipId();
} while (GetRelationship(id) != null);
return id;
}
// Build an ID string consisting of the letter 'R' followed by an 8-byte GUID timestamp.
// Guid.ToString() outputs the bytes in the big-endian order (higher order byte first)
private string GenerateRelationshipId()
{
// The timestamp consists of the first 8 hex octets of the GUID.
return String.Concat("R", Guid.NewGuid().ToString("N").Substring(0, s_timestampLength));
}
// If 'id' is not of the xsd type ID or is not unique for this collection, throw an exception.
private void ValidateUniqueRelationshipId(string id)
{
// An XSD ID is an NCName that is unique.
ThrowIfInvalidXsdId(id);
// Check for uniqueness.
if (GetRelationshipIndex(id) >= 0)
throw new XmlException(SR.Format(SR.NotAUniqueRelationshipId, id));
}
// Retrieve a relationship's index in _relationships given its id.
// Return a negative value if not found.
private int GetRelationshipIndex(string id)
{
for (int index = 0; index < _relationships.Count; ++index)
if (string.Equals(_relationships[index].Id, id, StringComparison.Ordinal))
return index;
return -1;
}
#endregion
#region Private Properties
#endregion Private Properties
//------------------------------------------------------
//
// Private Members
//
//------------------------------------------------------
#region Private Members
private List<PackageRelationship> _relationships;
private bool _dirty; // true if we have uncommitted changes to _relationships
private Package _package; // our package - in case _sourcePart is null
private PackagePart _sourcePart; // owning part - null if package is the owner
private PackagePart _relationshipPart; // where our relationships are persisted
private Uri _uri; // the URI of our relationship part
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
// segment that indicates a relationship part
private static readonly int s_timestampLength = 16;
private static readonly string s_relationshipsTagName = "Relationships";
private static readonly string s_relationshipTagName = "Relationship";
private static readonly string s_targetAttributeName = "Target";
private static readonly string s_typeAttributeName = "Type";
private static readonly string s_idAttributeName = "Id";
private static readonly string s_xmlBaseAttributeName = "xml:base";
private static readonly string s_targetModeAttributeName = "TargetMode";
private static readonly string[] s_relationshipKnownNamespaces
= new string[] { PackagingUtilities.RelationshipNamespaceUri };
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebFrontEnd.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.
==================================================================== */
namespace NPOI.XWPF.Extractor
{
using System;
using NPOI.XWPF.Model;
using NPOI.XWPF.UserModel;
using NPOI.OpenXml4Net.OPC;
using System.Text;
using System.Collections.Generic;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.IO;
using System.Xml;
/**
* Helper class to extract text from an OOXML Word file
*/
public class XWPFWordExtractor : POIXMLTextExtractor
{
public static XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[] {
XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE,
XWPFRelation.MACRO_DOCUMENT,
XWPFRelation.MACRO_TEMPLATE_DOCUMENT
};
private new XWPFDocument document;
private bool fetchHyperlinks = false;
public XWPFWordExtractor(OPCPackage Container)
: this(new XWPFDocument(Container))
{
}
public XWPFWordExtractor(XWPFDocument document)
: base(document)
{
this.document = document;
}
/**
* Should we also fetch the hyperlinks, when fetching
* the text content? Default is to only output the
* hyperlink label, and not the contents
*/
public void SetFetchHyperlinks(bool fetch)
{
fetchHyperlinks = fetch;
}
public override String Text
{
get
{
StringBuilder text = new StringBuilder();
XWPFHeaderFooterPolicy hfPolicy = document.GetHeaderFooterPolicy();
// Start out with all headers
extractHeaders(text, hfPolicy);
// body elements
foreach (IBodyElement e in document.BodyElements)
{
AppendBodyElementText(text, e);
text.Append('\n');
}
// Finish up with all the footers
extractFooters(text, hfPolicy);
return text.ToString();
}
}
public void AppendBodyElementText(StringBuilder text, IBodyElement e)
{
if (e is XWPFParagraph)
{
AppendParagraphText(text, (XWPFParagraph)e);
}
else if (e is XWPFTable)
{
appendTableText(text, (XWPFTable)e);
}
else if (e is XWPFSDT)
{
text.Append(((XWPFSDT)e).Content.Text);
}
}
public void AppendParagraphText(StringBuilder text, XWPFParagraph paragraph)
{
try
{
CT_SectPr ctSectPr = null;
if (paragraph.GetCTP().pPr != null)
{
ctSectPr = paragraph.GetCTP().pPr.sectPr;
}
XWPFHeaderFooterPolicy headerFooterPolicy = null;
if (ctSectPr != null)
{
headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
extractHeaders(text, headerFooterPolicy);
}
foreach (IRunElement run in paragraph.Runs)
{
text.Append(run.ToString());
if (run is XWPFHyperlinkRun && fetchHyperlinks)
{
XWPFHyperlink link = ((XWPFHyperlinkRun)run).GetHyperlink(document);
if (link != null)
text.Append(" <" + link.URL + ">");
}
}
// Add comments
XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null);
String commentText = decorator.GetCommentText();
if (commentText.Length > 0)
{
text.Append(commentText).Append('\n');
}
// Do endnotes and footnotes
String footnameText = paragraph.FootnoteText;
if (footnameText != null && footnameText.Length > 0)
{
text.Append(footnameText + '\n');
}
if (ctSectPr != null)
{
extractFooters(text, headerFooterPolicy);
}
}
catch (IOException e)
{
throw new POIXMLException(e);
}
catch (XmlException e)
{
throw new POIXMLException(e);
}
}
private void appendTableText(StringBuilder text, XWPFTable table)
{
//this works recursively to pull embedded tables from tables
foreach (XWPFTableRow row in table.Rows)
{
List<ICell> cells = row.GetTableICells();
for (int i = 0; i < cells.Count; i++)
{
ICell cell = cells[(i)];
if (cell is XWPFTableCell)
{
text.Append(((XWPFTableCell)cell).GetTextRecursively());
}
else if (cell is XWPFSDTCell)
{
text.Append(((XWPFSDTCell)cell).Content.Text);
}
if (i < cells.Count - 1)
{
text.Append("\t");
}
}
text.Append('\n');
}
}
private void extractFooters(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy)
{
if (hfPolicy == null) return;
if (hfPolicy.GetFirstPageFooter() != null)
{
text.Append(hfPolicy.GetFirstPageFooter().Text);
}
if (hfPolicy.GetEvenPageFooter() != null)
{
text.Append(hfPolicy.GetEvenPageFooter().Text);
}
if (hfPolicy.GetDefaultFooter() != null)
{
text.Append(hfPolicy.GetDefaultFooter().Text);
}
}
private void extractHeaders(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy)
{
if (hfPolicy == null) return;
if (hfPolicy.GetFirstPageHeader() != null)
{
text.Append(hfPolicy.GetFirstPageHeader().Text);
}
if (hfPolicy.GetEvenPageHeader() != null)
{
text.Append(hfPolicy.GetEvenPageHeader().Text);
}
if (hfPolicy.GetDefaultHeader() != null)
{
text.Append(hfPolicy.GetDefaultHeader().Text);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Utils.Logging;
using Utils.Templates;
namespace Utils.CommandLine
{
public class ArgumentParser<T> where T : new()
{
/// <summary>
/// Result object
/// </summary>
private readonly char[] SplitChars = { ',', ';' };
/// <summary>
/// List of arguments
/// </summary>
private string[] Arguments { get; set; }
/// <summary>
/// Data about the arguments
/// </summary>
private IDictionary<string, ArgumentData> Data { get; set; }
/// <summary>
/// Whether user requested help
/// </summary>
private bool NeedHelp { get; set; }
/// <summary>
/// Current position of the parser
/// </summary>
private int Position { get; set; }
/// <summary>
/// Result object
/// </summary>
private T Result { get; set; }
/// <summary>
/// Creates a new instance of <see cref="ArgumentParser{T}"/>
/// </summary>
/// <param name="arguments">List of command line arguments</param>
/// <param name="data"><see cref="ArgumentData"/></param>
internal ArgumentParser(string[] arguments, IDictionary<string, ArgumentData> data)
{
if (arguments == null)
{
throw new ArgumentNullException("arguments");
}
if (data == null)
{
throw new ArgumentNullException("data");
}
Arguments = arguments;
Data = data;
Result = new T();
Position = -1;
}
/// <summary>
/// Returns an instance of custom parameters class
/// </summary>
/// <param name="arg">List of arguments to parse</param>
/// <returns>Parsed arguments</returns>
public static T Parse(string[] arg)
{
var parser = new ArgumentParser<T>(arg, ArgumentParserUtils.GetArgumentData<T>());
if (!parser.Parse())
{
// TODO: Remove calls to PrintUsage from consumers and uncomment below
//if(parser.NeedHelp)
//{
// PrintUsage();
//}
return default(T);
}
return parser.Result;
}
/// <summary>
/// Prints help text based on custom arguments class
/// </summary>
public static void PrintUsage()
{
Console.Write(Usage());
}
/// <summary>
/// Generates help text based on custom arguments class
/// </summary>
internal static string Usage()
{
IDictionary<string, ArgumentData> data = ArgumentParserUtils.GetArgumentData<T>();
DetailsAttribute detailsAttr = typeof(T).GetCustomAttribute<DetailsAttribute>();
string details = detailsAttr != null ? detailsAttr.Details : string.Empty;
ITemplate template = new CommandLineUsage
{
Name = Process.GetCurrentProcess().ProcessName,
Description = details,
Required = data.Values.Where(x => !x.Optional).Distinct(),
Optional = data.Values.Where(x => x.Optional).Distinct(),
};
return template.Print();
}
/// <summary>
/// Internal helper method for parsing arguments
/// </summary>
/// <returns>True if all arguments were successfully parsed</returns>
internal bool Parse()
{
while (++Position < Arguments.Length)
{
Tuple<string, string> param = ArgumentParserUtils.ParseParam(Arguments[Position]);
if (param == null || !Data.ContainsKey(param.Item1))
{
if (Arguments[Position].Equals("/?"))
{
NeedHelp = true;
return false;
}
LogHelper.LogError("Unrecogized parameter '{0}'.", Arguments[Position]);
return false;
}
if (param.Item1.Equals("h", StringComparison.OrdinalIgnoreCase)
|| param.Item1.Equals("help", StringComparison.OrdinalIgnoreCase))
{
NeedHelp = true;
return false;
}
ArgumentData argumentData = Data[param.Item1];
if (argumentData.Seen)
{
LogHelper.LogError("Argument '{0}' re-defined with value '{1}'.", param.Item1, param.Item2);
return false;
}
argumentData.Seen = true;
if (!HandleArgument(argumentData, param.Item2))
{
return false;
}
}
foreach (ArgumentData argumentData in Data.Values.Where(d => !d.Seen))
{
if (!argumentData.Optional)
{
LogHelper.LogError("Argument [{0}] is required.", argumentData.Name);
return false;
}
if (!HandleDefaultValue(argumentData))
{
return false;
}
}
return true;
}
#region Private methods
/// <summary>
/// Mapping between argument type and it's default value handler
/// </summary>
/// <param name="argumentData">Argument data</param>
/// <returns>True if it was successfully handled</returns>
private bool HandleDefaultValue(ArgumentData argumentData)
{
string value = argumentData.DefaultValue;
if (string.IsNullOrWhiteSpace(value))
{
return true;
}
switch (argumentData.Type)
{
case ArgumentType.Flag:
case ArgumentType.Param:
return Result.TrySetPropertyValue(argumentData.Property, value);
case ArgumentType.ParamArray:
string[] values = value.Split(SplitChars);
return Result.TrySetPropertyValue(argumentData.Property, values);
default:
throw new NotImplementedException(
string.Format("No handler found for ArgumentType '{0}'", argumentData.Type));
}
}
/// <summary>
/// Mapping between argument type and it's handler
/// </summary>
/// <param name="argumentData">Argument data</param>
/// <param name="value">Value for the argument</param>
/// <returns>True if it was successfully handled</returns>
private bool HandleArgument(ArgumentData argumentData, string value)
{
switch (argumentData.Type)
{
case ArgumentType.Flag:
return HandleFlag(argumentData, value);
case ArgumentType.Param:
return HandleParam(argumentData, value);
case ArgumentType.ParamArray:
return HandleParamArray(argumentData, value);
default:
throw new NotImplementedException(
string.Format("No handler found for ArgumentType '{0}'", argumentData.Type));
}
}
/// <summary>
/// Handler for boolean flag arguments
/// </summary>
/// <param name="argument"><see cref="ArgumentData"/></param>
/// <param name="value">Value of argument</param>
/// <returns>True if it was successfully handled</returns>
private bool HandleFlag(ArgumentData argument, string value)
{
bool boolValue = true;
if (!string.IsNullOrWhiteSpace(value))
{
if (!bool.TryParse(value, out boolValue))
{
LogHelper.LogError("Invalid value '{0}' passed for flag parameter '{1}'", value, argument.Key);
return false;
}
}
argument.Property.SetValue(Result, boolValue);
return true;
}
/// <summary>
/// Handler for single param arguments
/// </summary>
/// <param name="argument"><see cref="ArgumentData"/></param>
/// <param name="value">Value of argument</param>
/// <returns>True if it was successfully handled</returns>
private bool HandleParam(ArgumentData argument, string value)
{
// Param is specified as key:value or key=value
if (!string.IsNullOrWhiteSpace(value))
{
return Result.TrySetPropertyValue(argument.Property, value);
}
// Value should be the next argumentKey
if (++Position < Arguments.Length)
{
Tuple<string, string> nextParam = ArgumentParserUtils.ParseParam(Arguments[Position]);
if (nextParam == null)
{
return Result.TrySetPropertyValue(argument.Property, Arguments[Position]);
}
}
Position--;
LogHelper.LogError("Value for parameter '{0}' not specified", argument.Key);
return false;
}
/// <summary>
/// Handler for param array arguments
/// </summary>
/// <param name="argument"><see cref="ArgumentData"/></param>
/// <param name="value">Value of argument</param>
/// <returns>True if it was successfully handled</returns>
private bool HandleParamArray(ArgumentData argument, string value)
{
// Param is specified as key:value or key=value
if (!string.IsNullOrWhiteSpace(value))
{
return Result.TrySetPropertyValue(argument.Property, value.Split(SplitChars));
}
// Value should be the next argumentKey
IList<string> array = new List<string>();
while (++Position < Arguments.Length)
{
Tuple<string, string> nextParam = ArgumentParserUtils.ParseParam(Arguments[Position]);
if (nextParam != null)
{
Position--;
break;
}
array.Add(Arguments[Position]);
}
if (array.Count > 0)
{
return Result.TrySetPropertyValue(argument.Property, array);
}
LogHelper.LogError("No values specified for array '{0}'", argument.Key);
return false;
}
#endregion
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using SharpNeat.Utility;
namespace SharpNeat.Network
{
/// <summary>
/// Static class for reading and writing Network Definitions(s) to and from XML.
/// </summary>
public static class NetworkXmlIO
{
#region Constants [XML Strings]
const string __ElemRoot = "Root";
const string __ElemNetworks = "Networks";
const string __ElemNetwork = "Network";
const string __ElemNodes = "Nodes";
const string __ElemNode = "Node";
const string __ElemConnections = "Connections";
const string __ElemConnection = "Con";
const string __ElemActivationFunctions = "ActivationFunctions";
const string __ElemActivationFn = "Fn";
const string __AttrId = "id";
const string __AttrName = "name";
const string __AttrType = "type";
const string __AttrSourceId = "src";
const string __AttrTargetId = "tgt";
const string __AttrWeight = "wght";
const string __AttrActivationFunctionId = "fnId";
const string __AttrAuxState = "aux";
const string __AttrProbability = "prob";
#endregion
#region Public Static Methods [Save to XmlDocument]
/// <summary>
/// Writes a single NetworkDefinition to XML within a containing 'Root' element and the activation function
/// library that the genome is associated with.
/// The XML is returned as a newly created XmlDocument.
/// </summary>
/// <param name="networkDef">The NetworkDefinition to save.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static XmlDocument SaveComplete(NetworkDefinition networkDef, bool nodeFnIds)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter xw = doc.CreateNavigator().AppendChild())
{
WriteComplete(xw, networkDef, nodeFnIds);
}
return doc;
}
/// <summary>
/// Writes a list of NetworkDefinition(s) to XML within a containing 'Root' element and the activation
/// function library that the genomes are associated with.
/// The XML is returned as a newly created XmlDocument.
/// </summary>
/// <param name="networkDefList">List of genomes to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static XmlDocument SaveComplete(IList<NetworkDefinition> networkDefList, bool nodeFnIds)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter xw = doc.CreateNavigator().AppendChild())
{
WriteComplete(xw, networkDefList, nodeFnIds);
}
return doc;
}
/// <summary>
/// Writes a single NetworkDefinition to XML.
/// The XML is returned as a newly created XmlDocument.
/// </summary>
/// <param name="networkDef">The genome to save.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static XmlDocument Save(NetworkDefinition networkDef, bool nodeFnIds)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter xw = doc.CreateNavigator().AppendChild())
{
Write(xw, networkDef, nodeFnIds);
}
return doc;
}
#endregion
#region Public Static Methods [Load from XmlDocument]
/// <summary>
/// Reads a list of NetworkDefinition(s) from XML that has a containing 'Root' element. The root element
/// also contains the activation function library that the network definitions are associated with.
/// </summary>
/// <param name="xmlNode">The XmlNode to read from. This can be an XmlDocument or XmlElement.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. If false then
/// all node activation function IDs default to 0.</param>
public static List<NetworkDefinition> LoadCompleteGenomeList(XmlNode xmlNode, bool nodeFnIds)
{
using(XmlNodeReader xr = new XmlNodeReader(xmlNode))
{
return ReadCompleteNetworkDefinitionList(xr, nodeFnIds);
}
}
/// <summary>
/// Reads a NetworkDefinition from XML.
/// </summary>
/// <param name="xmlNode">The XmlNode to read from. This can be an XmlDocument or XmlElement.</param>
/// <param name="activationFnLib">The activation function library used to decode node activation function IDs.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. They are required
/// for HyperNEAT genomes but not for NEAT. If false then all node activation function IDs default to 0.</param>
public static NetworkDefinition ReadGenome(XmlNode xmlNode, IActivationFunctionLibrary activationFnLib, bool nodeFnIds)
{
using(XmlNodeReader xr = new XmlNodeReader(xmlNode))
{
return ReadNetworkDefinition(xr, activationFnLib, nodeFnIds);
}
}
#endregion
#region Public Static Methods [Write to XML]
/// <summary>
/// Writes a list of INetworkDefinition(s) to XML within a containing 'Root' element and the activation
/// function library that the genomes are associated with.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="networkDefList">List of network definitions to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void WriteComplete(XmlWriter xw, IList<NetworkDefinition> networkDefList, bool nodeFnIds)
{
int count = networkDefList.Count;
List<INetworkDefinition> tmpList = new List<INetworkDefinition>(count);
foreach(NetworkDefinition networkDef in networkDefList) {
tmpList.Add(networkDef);
}
WriteComplete(xw, tmpList, nodeFnIds);
}
/// <summary>
/// Writes a list of INetworkDefinition(s) to XML within a containing 'Root' element and the activation
/// function library that the genomes are associated with.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="networkDefList">List of network definitions to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void WriteComplete(XmlWriter xw, IList<INetworkDefinition> networkDefList, bool nodeFnIds)
{
if(networkDefList.Count == 0)
{ // Nothing to do.
return;
}
// <Root>
xw.WriteStartElement(__ElemRoot);
// Write activation function library from the first network definition
// (we expect all networks to use the same library).
IActivationFunctionLibrary activationFnLib = networkDefList[0].ActivationFnLibrary;
Write(xw, activationFnLib);
// <Networks>
xw.WriteStartElement(__ElemNetworks);
// Write networks.
foreach(INetworkDefinition networkDef in networkDefList) {
Debug.Assert(networkDef.ActivationFnLibrary == activationFnLib);
Write(xw, networkDef, nodeFnIds);
}
// </Networks>
xw.WriteEndElement();
// </Root>
xw.WriteEndElement();
}
/// <summary>
/// Writes a single INetworkDefinition to XML within a containing 'Root' element and the activation
/// function library that the genome is associated with.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="networkDef">Network definition to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void WriteComplete(XmlWriter xw, INetworkDefinition networkDef, bool nodeFnIds)
{
// <Root>
xw.WriteStartElement(__ElemRoot);
// Write activation function library.
Write(xw, networkDef.ActivationFnLibrary);
// <Networks>
xw.WriteStartElement(__ElemNetworks);
// Write single network.
Write(xw, networkDef, nodeFnIds);
// </Networks>
xw.WriteEndElement();
// </Root>
xw.WriteEndElement();
}
/// <summary>
/// Writes an INetworkDefinition to XML.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="networkDef">Network definition to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void Write(XmlWriter xw, INetworkDefinition networkDef, bool nodeFnIds)
{
xw.WriteStartElement(__ElemNetwork);
// Emit nodes.
xw.WriteStartElement(__ElemNodes);
foreach(INetworkNode node in networkDef.NodeList)
{
xw.WriteStartElement(__ElemNode);
xw.WriteAttributeString(__AttrType, GetNodeTypeString(node.NodeType));
xw.WriteAttributeString(__AttrId, node.Id.ToString(NumberFormatInfo.InvariantInfo));
if(nodeFnIds) {
xw.WriteAttributeString(__AttrActivationFunctionId, node.ActivationFnId.ToString(NumberFormatInfo.InvariantInfo));
}
xw.WriteEndElement();
}
xw.WriteEndElement();
// Emit connections.
xw.WriteStartElement(__ElemConnections);
foreach(INetworkConnection con in networkDef.ConnectionList)
{
xw.WriteStartElement(__ElemConnection);
xw.WriteAttributeString(__AttrSourceId, con.SourceNodeId.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrTargetId, con.TargetNodeId.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrWeight, con.Weight.ToString("R", NumberFormatInfo.InvariantInfo));
xw.WriteEndElement();
}
xw.WriteEndElement();
// </Network>
xw.WriteEndElement();
}
/// <summary>
/// Writes an activation function library to XML. This links activation function names to the
/// integer IDs used by network nodes, which allows us emit just the ID for each node thus
/// resulting in XML that is more compact compared to emitting the activation function name for
/// each node.
/// </summary>
public static void Write(XmlWriter xw, IActivationFunctionLibrary activationFnLib)
{
xw.WriteStartElement(__ElemActivationFunctions);
IList<ActivationFunctionInfo> fnList = activationFnLib.GetFunctionList();
foreach(ActivationFunctionInfo fnInfo in fnList)
{
xw.WriteStartElement(__ElemActivationFn);
xw.WriteAttributeString(__AttrId, fnInfo.Id.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrName, fnInfo.ActivationFunction.FunctionId);
xw.WriteAttributeString(__AttrProbability, fnInfo.SelectionProbability.ToString("R", NumberFormatInfo.InvariantInfo));
xw.WriteEndElement();
}
xw.WriteEndElement();
}
#endregion
#region Public Static Methods [Read from XML]
/// <summary>
/// Reads a list of NetworkDefinition(s) from XML that has a containing 'Root' element. The root
/// element also contains the activation function library that the genomes are associated with.
/// </summary>
/// <param name="xr">The XmlReader to read from.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. They are required
/// for HyperNEAT genomes but not NEAT</param>
public static List<NetworkDefinition> ReadCompleteNetworkDefinitionList(XmlReader xr, bool nodeFnIds)
{
// Find <Root>.
XmlIoUtils.MoveToElement(xr, false, __ElemRoot);
// Read IActivationFunctionLibrray.
XmlIoUtils.MoveToElement(xr, true, __ElemActivationFunctions);
IActivationFunctionLibrary activationFnLib = ReadActivationFunctionLibrary(xr);
XmlIoUtils.MoveToElement(xr, false, __ElemNetworks);
List<NetworkDefinition> networkDefList = new List<NetworkDefinition>();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root <Networks> element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first Network elem.
XmlIoUtils.MoveToElement(xr, true, __ElemNetwork);
// Read Network elements.
do
{
NetworkDefinition networkDef = ReadNetworkDefinition(xr, activationFnLib, nodeFnIds);
networkDefList.Add(networkDef);
}
while(xrSubtree.ReadToNextSibling(__ElemNetwork));
}
return networkDefList;
}
/// <summary>
/// Reads a network definition from XML.
/// An activation function library is required to decode the function ID at each node, typically the
/// library is stored alongside the network definition XML and will have already been read elsewhere and
/// passed in here.
/// </summary>
/// <param name="xr">The XmlReader to read from.</param>
/// <param name="activationFnLib">The activation function library used to decode node activation function IDs.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. They are required
/// for HyperNEAT genomes but not NEAT</param>
public static NetworkDefinition ReadNetworkDefinition(XmlReader xr, IActivationFunctionLibrary activationFnLib, bool nodeFnIds)
{
// Find <Network>.
XmlIoUtils.MoveToElement(xr, false, __ElemNetwork);
int initialDepth = xr.Depth;
// Find <Nodes>.
XmlIoUtils.MoveToElement(xr, true, __ElemNodes);
// Create a reader over the <Nodes> sub-tree.
int inputNodeCount = 0;
int outputNodeCount = 0;
NodeList nodeList = new NodeList();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root <Nodes> element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first node elem.
XmlIoUtils.MoveToElement(xrSubtree, true, __ElemNode);
// Read node elements.
do
{
NodeType nodeType = ReadAttributeAsNodeType(xrSubtree, __AttrType);
uint id = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrId);
int fnId = 0;
double[] auxState = null;
if(nodeFnIds)
{ // Read activation fn ID.
fnId = XmlIoUtils.ReadAttributeAsInt(xrSubtree, __AttrActivationFunctionId);
// Read aux state as comma seperated list of real values.
auxState = XmlIoUtils.ReadAttributeAsDoubleArray(xrSubtree, __AttrAuxState);
}
// TODO: Read node aux state data.
NetworkNode node = new NetworkNode(id, nodeType, fnId, auxState);
nodeList.Add(node);
// Track the number of input and output nodes.
switch(nodeType)
{
case NodeType.Input:
inputNodeCount++;
break;
case NodeType.Output:
outputNodeCount++;
break;
}
}
while(xrSubtree.ReadToNextSibling(__ElemNode));
}
// Find <Connections>.
XmlIoUtils.MoveToElement(xr, false, __ElemConnections);
// Create a reader over the <Connections> sub-tree.
ConnectionList connList = new ConnectionList();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root <Connections> element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first connection elem.
string localName = XmlIoUtils.MoveToElement(xrSubtree, true);
if(localName == __ElemConnection)
{ // We have at least one connection.
// Read connection elements.
do
{
uint srcId = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrSourceId);
uint tgtId = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrTargetId);
double weight = XmlIoUtils.ReadAttributeAsDouble(xrSubtree, __AttrWeight);
NetworkConnection conn = new NetworkConnection(srcId, tgtId, weight);
connList.Add(conn);
}
while(xrSubtree.ReadToNextSibling(__ElemConnection));
}
}
// Move the reader beyond the closing tags </Connections> and </Network>.
do
{
if (xr.Depth <= initialDepth) {
break;
}
}
while(xr.Read());
// Construct and return loaded network definition.
return new NetworkDefinition(inputNodeCount, outputNodeCount, activationFnLib, nodeList, connList);
}
/// <summary>
/// Reads an IActivationFunctionLibrary from the provided XmlReader.
/// </summary>
public static IActivationFunctionLibrary ReadActivationFunctionLibrary(XmlReader xr)
{
XmlIoUtils.MoveToElement(xr, false, __ElemActivationFunctions);
// Create a reader over the sub-tree.
List<ActivationFunctionInfo> fnList = new List<ActivationFunctionInfo>();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first function elem.
XmlIoUtils.MoveToElement(xrSubtree, true, __ElemActivationFn);
// Read function elements.
do
{
int id = XmlIoUtils.ReadAttributeAsInt(xrSubtree, __AttrId);
double selectionProb = XmlIoUtils.ReadAttributeAsDouble(xrSubtree, __AttrProbability);
string fnName = xrSubtree.GetAttribute(__AttrName);
// Lookup function name.
IActivationFunction activationFn = GetActivationFunction(fnName);
// Add new function to our list of functions.
ActivationFunctionInfo fnInfo = new ActivationFunctionInfo(id, selectionProb, activationFn);
fnList.Add(fnInfo);
}
while(xrSubtree.ReadToNextSibling(__ElemActivationFn));
}
// If we have read library items then ensure that their selection probabilities are normalized.
if(fnList.Count != 0) {
NormalizeSelectionProbabilities(fnList);
}
return new DefaultActivationFunctionLibrary(fnList);
}
#endregion
#region Public Static Methods [Low-level XML Parsing]
/// <summary>
/// Read the named attribute and parse its string value as a NodeType.
/// </summary>
public static NodeType ReadAttributeAsNodeType(XmlReader xr, string attrName)
{
string valStr = xr.GetAttribute(attrName);
return GetNodeType(valStr);
}
/// <summary>
/// Gets the NodeType for the specified node type string.
/// Note. we use our own type strings in place of Enum.ToString() to provide more compact XML.
/// </summary>
public static NodeType GetNodeType(string type)
{
switch(type)
{
case "bias":
return NodeType.Bias;
case "in":
return NodeType.Input;
case "out":
return NodeType.Output;
case "hid":
return NodeType.Hidden;
}
throw new InvalidDataException(string.Format("Unknown node type [{0}]", type));
}
/// <summary>
/// Gets the node type string for the specified NodeType.
/// Note. we use our own type strings in place of Enum.ToString() to provide more compact XML.
/// </summary>
public static string GetNodeTypeString(NodeType nodeType)
{
switch(nodeType)
{
case NodeType.Bias:
return "bias";
case NodeType.Input:
return "in";
case NodeType.Output:
return "out";
case NodeType.Hidden:
return "hid";
}
throw new ArgumentException(string.Format("Unexpected NodeType [{0}]", nodeType));
}
/// <summary>
/// Gets an IActivationFunction from its short name.
/// </summary>
public static IActivationFunction GetActivationFunction(string name)
{
switch(name)
{
case "BipolarGaussian":
return BipolarGaussian.__DefaultInstance;
case "BipolarSigmoid":
return BipolarSigmoid.__DefaultInstance;
case "Linear":
return Linear.__DefaultInstance;
case "Sine":
return Sine.__DefaultInstance;
case "Absolute":
return Absolute.__DefaultInstance;
case "AbsoluteRoot":
return AbsoluteRoot.__DefaultInstance;
case "Gaussian":
return Gaussian.__DefaultInstance;
case "InverseAbsoluteSigmoid":
return InverseAbsoluteSigmoid.__DefaultInstance;
case "PlainSigmoid":
return PlainSigmoid.__DefaultInstance;
case "ReducedSigmoid":
return ReducedSigmoid.__DefaultInstance;
case "SteepenedSigmoid":
return SteepenedSigmoid.__DefaultInstance;
case "SteepenedSigmoidApproximation":
return SteepenedSigmoidApproximation.__DefaultInstance;
case "StepFunction":
return StepFunction.__DefaultInstance;
case "RbfGaussian":
return RbfGaussian.__DefaultInstance;
}
throw new ArgumentException(string.Format("Unexpected activation function [{0}]", name));
}
#endregion
#region Private Static Methods
/// <summary>
/// Normalize the selection probabilities of the provided ActivationFunctionInfo items.
/// </summary>
private static void NormalizeSelectionProbabilities(IList<ActivationFunctionInfo> fnList)
{
double total = 0.0;
int count = fnList.Count;
for(int i=0; i<count; i++) {
total += fnList[i].SelectionProbability;
}
if(Math.Abs(total - 1.0) < 0.0001)
{ // Probabilities already normalized to within acceptable limits (from rounding errors).
return;
}
// Normalize the probabilities. Note that ActivationFunctionInfo is immutable therefore
// we replace the existing items.
for(int i=0; i<count; i++)
{
ActivationFunctionInfo item = fnList[i];
fnList[i] = new ActivationFunctionInfo(item.Id, item.SelectionProbability/total, item.ActivationFunction);
}
}
#endregion
}
}
| |
using Bridge.Html5;
using Bridge.Test.NUnit;
using System;
using System.Collections.Generic;
namespace Bridge.ClientTest.Collections.Native
{
[Category(Constants.MODULE_TYPEDARRAYS)]
[TestFixture(TestNameFormat = "Int8ArrayTests - {0}")]
public class Int8ArrayTests
{
private void AssertContent(Int8Array actual, int[] expected, string message)
{
if (actual.Length != expected.Length)
{
Assert.Fail(message + ": Expected length " + expected.Length + ", actual: " + actual.Length);
return;
}
for (int i = 0; i < expected.Length; i++)
{
if (actual[i] != expected[i])
{
Assert.Fail(message + ": Position " + i + ": expected " + expected[i] + ", actual: " + actual[i]);
return;
}
}
Assert.True(true, message);
}
[Test]
public void LengthConstructorWorks()
{
var arr = new Int8Array(13);
Assert.True((object)arr is Int8Array, "is Int8Array");
Assert.AreEqual(13, arr.Length, "Length");
}
[Test]
public void ConstructorFromIntWorks()
{
var source = new sbyte[] { 3, 8, 4 };
var arr = new Int8Array(source);
Assert.True((object)arr != (object)source, "New object");
Assert.True((object)arr is Int8Array, "is Int8Array");
AssertContent(arr, new[] { 3, 8, 4 }, "content");
}
[Test]
public void CopyConstructorWorks()
{
var source = new Int8Array(new sbyte[] { 3, 8, 4 });
var arr = new Int8Array(source);
Assert.True(arr != source, "New object");
Assert.True((object)arr is Int8Array, "is Int8Array");
AssertContent(arr, new[] { 3, 8, 4 }, "content");
}
[Test]
public void ArrayBufferConstructorWorks()
{
var buf = new ArrayBuffer(80);
var arr = new Int8Array(buf);
Assert.True((object)arr is Int8Array);
Assert.True(arr.Buffer == buf, "buffer");
Assert.AreEqual(80, arr.Length, "length");
}
[Test]
public void ArrayBufferWithOffsetConstructorWorks()
{
var buf = new ArrayBuffer(80);
var arr = new Int8Array(buf, 16);
Assert.True((object)arr is Int8Array);
Assert.True(arr.Buffer == buf, "buffer");
Assert.AreEqual(64, arr.Length, "length");
}
[Test]
public void ArrayBufferWithOffsetAndLengthConstructorWorks()
{
var buf = new ArrayBuffer(80);
var arr = new Int8Array(buf, 16, 12);
Assert.True((object)arr is Int8Array);
Assert.True(arr.Buffer == buf, "buffer");
Assert.AreEqual(12, arr.Length, "length");
}
// Not JS API
//[Test]
//public void InstanceBytesPerElementWorks()
//{
// Assert.AreEqual(new Int8Array(0).BytesPerElement, 1);
//}
[Test]
public void StaticBytesPerElementWorks()
{
Assert.AreEqual(1, Int8Array.BYTES_PER_ELEMENT);
}
[Test]
public void LengthWorks()
{
var arr = new Int8Array(13);
Assert.AreEqual(13, arr.Length, "Length");
}
[Test]
public void IndexingWorks()
{
var arr = new Int8Array(3);
arr[1] = 42;
AssertContent(arr, new[] { 0, 42, 0 }, "Content");
Assert.AreEqual(42, arr[1], "[1]");
}
[Test]
public void SetInt8ArrayWorks()
{
var arr = new Int8Array(4);
arr.Set(new Int8Array(new sbyte[] { 3, 6, 7 }));
AssertContent(arr, new[] { 3, 6, 7, 0 }, "Content");
}
[Test]
public void SetInt8ArrayWithOffsetWorks()
{
var arr = new Int8Array(6);
arr.Set(new Int8Array(new sbyte[] { 3, 6, 7 }), 2);
AssertContent(arr, new[] { 0, 0, 3, 6, 7, 0 }, "Content");
}
[Test]
public void SetNormalArrayWorks()
{
var arr = new Int8Array(4);
arr.Set(new sbyte[] { 3, 6, 7 });
AssertContent(arr, new[] { 3, 6, 7, 0 }, "Content");
}
[Test]
public void SetNormalArrayWithOffsetWorks()
{
var arr = new Int8Array(6);
arr.Set(new sbyte[] { 3, 6, 7 }, 2);
AssertContent(arr, new[] { 0, 0, 3, 6, 7, 0 }, "Content");
}
[Test]
public void SubarrayWithBeginWorks()
{
var source = new Int8Array(10);
var arr = source.SubArray(3);
Assert.False(arr == source, "Should be a new array");
Assert.True(arr.Buffer == source.Buffer, "Should be the same buffer");
Assert.AreEqual(3, arr.ByteOffset, "ByteOffset should be correct");
}
[Test]
public void SubarrayWithBeginAndEndWorks()
{
var source = new Int8Array(10);
var arr = source.SubArray(3, 7);
Assert.False(arr == source, "Should be a new array");
Assert.True(arr.Buffer == source.Buffer, "Should be the same buffer");
Assert.AreEqual(3, arr.ByteOffset, "ByteOffset should be correct");
Assert.AreEqual(4, arr.Length, "Length should be correct");
}
[Test]
public void BufferPropertyWorks()
{
var buf = new ArrayBuffer(100);
var arr = new Int8Array(buf);
Assert.True(arr.Buffer == buf, "Should be correct");
}
[Test]
public void ByteOffsetPropertyWorks()
{
var buf = new ArrayBuffer(100);
var arr = new Int8Array(buf, 32);
Assert.AreEqual(32, arr.ByteOffset, "Should be correct");
}
[Test]
public void ByteLengthPropertyWorks()
{
var arr = new Int8Array(23);
Assert.AreEqual(23, arr.ByteLength, "Should be correct");
}
[Test]
public void IndexOfWorks()
{
var arr = new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
Assert.AreEqual(3, arr.IndexOf(9), "9");
Assert.AreEqual(-1, arr.IndexOf(1), "1");
}
// Not JS API
[Test]
public void ContainsWorks()
{
var arr = new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
Assert.True(arr.Contains(9), "9");
Assert.False(arr.Contains(1), "1");
}
// #SPI
[Test]
public void ForeachWorks_SPI_1401()
{
var arr = new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
var l = new List<int>();
// #1401
foreach (var i in arr)
{
l.Add(i);
}
Assert.AreEqual(l.ToArray(), new[] { 3, 6, 2, 9, 5 });
}
// #SPI
[Test]
public void GetEnumeratorWorks_SPI_1401()
{
var arr = new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
var l = new List<int>();
// #1401
var enm = arr.GetEnumerator();
while (enm.MoveNext())
{
l.Add(enm.Current);
}
Assert.AreEqual(l.ToArray(), new[] { 3, 6, 2, 9, 5 });
}
[Test]
public void IEnumerableGetEnumeratorWorks()
{
var arr = (IEnumerable<sbyte>)new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
var l = new List<int>();
var enm = arr.GetEnumerator();
while (enm.MoveNext())
{
l.Add(enm.Current);
}
Assert.AreEqual(new[] { 3, 6, 2, 9, 5 }, l.ToArray());
}
[Test]
public void ICollectionMethodsWork_SPI_1559()
{
// #1559
var coll = (ICollection<sbyte>)new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
Assert.AreEqual(5, coll.Count, "Count");
Assert.True(coll.Contains(6), "Contains(6)");
Assert.False(coll.Contains(1), "Contains(1)");
Assert.Throws<NotSupportedException>(() => coll.Add(2), "Add");
Assert.Throws<NotSupportedException>(() => coll.Clear(), "Clear");
Assert.Throws<NotSupportedException>(() => coll.Remove(2), "Remove");
}
[Test]
public void IListMethodsWork_SPI_1559()
{
// #1559
var list = (IList<sbyte>)new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
Assert.AreEqual(1, list.IndexOf(6), "IndexOf(6)");
Assert.AreEqual(-1, list.IndexOf(1), "IndexOf(1)");
Assert.AreEqual(9, list[3], "Get item");
list[3] = 4;
Assert.AreEqual(4, list[3], "Set item");
Assert.Throws<NotSupportedException>(() => list.Insert(2, 2), "Insert");
Assert.Throws<NotSupportedException>(() => list.RemoveAt(2), "RemoveAt");
}
// Not JS API
//[Test]
//public void IReadOnlyCollectionMethodsWork()
//{
// var coll = (IReadOnlyCollection<sbyte>)new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
// Assert.AreEqual(coll.Count, 5, "Count");
// Assert.True(coll.Contains(6), "Contains(6)");
// Assert.False(coll.Contains(1), "Contains(1)");
//}
// Not JS API
//[Test]
//public void IReadOnlyListMethodsWork()
//{
// var list = (IReadOnlyList<sbyte>)new Int8Array(new sbyte[] { 3, 6, 2, 9, 5 });
// Assert.AreEqual(list[3], 9, "Get item");
//}
[Test]
public void IListIsReadOnlyWorks()
{
var list = (IList<float>)new Int8Array(new float[0]);
Assert.True(list.IsReadOnly);
}
[Test]
public void ICollectionIsReadOnlyWorks()
{
var list = (ICollection<float>)new Int8Array(new float[0]);
Assert.True(list.IsReadOnly);
}
[Test]
public void ICollectionCopyTo()
{
ICollection<sbyte> l = new Int8Array(new sbyte[] { 0, 1, 2 });
var a1 = new sbyte[3];
l.CopyTo(a1, 0);
Assert.AreEqual(0, a1[0], "1.Element 0");
Assert.AreEqual(1, a1[1], "1.Element 1");
Assert.AreEqual(2, a1[2], "1.Element 2");
var a2 = new sbyte[5];
l.CopyTo(a2, 1);
Assert.AreEqual(0, a2[0], "2.Element 0");
Assert.AreEqual(0, a2[1], "2.Element 1");
Assert.AreEqual(1, a2[2], "2.Element 2");
Assert.AreEqual(2, a2[3], "2.Element 3");
Assert.AreEqual(0, a2[4], "2.Element 4");
Assert.Throws<ArgumentNullException>(() => { l.CopyTo(null, 0); }, "3.null");
var a3 = new sbyte[2];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a3, 0); }, "3.Short array");
var a4 = new sbyte[3];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a4, 1); }, "3.Start index 1");
Assert.Throws<ArgumentOutOfRangeException>(() => { l.CopyTo(a4, -1); }, "3.Negative start index");
Assert.Throws<ArgumentException>(() => { l.CopyTo(a4, 3); }, "3.Start index 3");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders);
public class HttpWebRequest : WebRequest, ISerializable
{
private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop.
private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes
private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection();
private Uri _requestUri;
private string _originVerb = HttpMethod.Get.Method;
// We allow getting and setting this (to preserve app-compat). But we don't do anything with it
// as the underlying System.Net.Http API doesn't support it.
private int _continueTimeout = DefaultContinueTimeout;
private bool _allowReadStreamBuffering = false;
private CookieContainer _cookieContainer = null;
private ICredentials _credentials = null;
private IWebProxy _proxy = WebRequest.DefaultWebProxy;
private Task<HttpResponseMessage> _sendRequestTask;
private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _beginGetRequestStreamCalled = 0;
private int _beginGetResponseCalled = 0;
private int _endGetRequestStreamCalled = 0;
private int _endGetResponseCalled = 0;
private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength;
private ServicePoint _servicePoint;
private int _timeout = WebRequest.DefaultTimeoutMilliseconds;
private int _readWriteTimeout = DefaultReadWriteTimeout;
private HttpContinueDelegate _continueDelegate;
// stores the user provided Host header as Uri. If the user specified a default port explicitly we'll lose
// that information when converting the host string to a Uri. _HostHasPort will store that information.
private bool _hostHasPort;
private Uri _hostUri;
private RequestStream _requestStream;
private TaskCompletionSource<Stream> _requestStreamOperation = null;
private TaskCompletionSource<WebResponse> _responseOperation = null;
private AsyncCallback _requestStreamCallback = null;
private AsyncCallback _responseCallback = null;
private int _abortCalled = 0;
private CancellationTokenSource _sendRequestCts;
private X509CertificateCollection _clientCertificates;
private Booleans _booleans = Booleans.Default;
private bool _pipelined = true;
private bool _preAuthenticate;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
//these should be safe.
[Flags]
private enum Booleans : uint
{
AllowAutoRedirect = 0x00000001,
AllowWriteStreamBuffering = 0x00000002,
ExpectContinue = 0x00000004,
ProxySet = 0x00000010,
UnsafeAuthenticatedConnectionSharing = 0x00000040,
IsVersionHttp10 = 0x00000080,
SendChunked = 0x00000100,
EnableDecompression = 0x00000200,
IsTunnelRequest = 0x00000400,
IsWebSocketRequest = 0x00000800,
Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue
}
private const string ContinueHeader = "100-continue";
private const string ChunkedHeader = "chunked";
private const string GZipHeader = "gzip";
private const string DeflateHeader = "deflate";
public HttpWebRequest()
{
}
[Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebRequest(Uri uri)
{
_requestUri = uri;
}
private void SetSpecialHeaders(string HeaderName, string value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
{
_webHeaderCollection[HeaderName] = value;
}
}
public string Accept
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Accept];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Accept, value);
}
}
public virtual bool AllowReadStreamBuffering
{
get
{
return _allowReadStreamBuffering;
}
set
{
_allowReadStreamBuffering = value;
}
}
public int MaximumResponseHeadersLength
{
get => _maximumResponseHeadersLen;
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_toosmall);
}
_maximumResponseHeadersLen = value;
}
}
public int MaximumAutomaticRedirections
{
get
{
return _maximumAllowedRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentException(SR.net_toosmall, nameof(value));
}
_maximumAllowedRedirections = value;
}
}
public override String ContentType
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
public int ContinueTimeout
{
get
{
return _continueTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if ((value < 0) && (value != System.Threading.Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_continueTimeout = value;
}
}
public override int Timeout
{
get
{
return _timeout;
}
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_timeout = value;
}
}
public override long ContentLength
{
get
{
long value;
long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value);
return value;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall);
}
SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString());
}
}
public Uri Address
{
get
{
return _requestUri;
}
}
public string UserAgent
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.UserAgent];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value);
}
}
public string Host
{
get
{
Uri hostUri = _hostUri ?? Address;
return (_hostUri == null || !_hostHasPort) && Address.IsDefaultPort ?
hostUri.Host :
hostUri.Host + ":" + hostUri.Port;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Uri hostUri;
if ((value.IndexOf('/') != -1) || (!TryGetHostUri(value, out hostUri)))
{
throw new ArgumentException(SR.net_invalid_host, nameof(value));
}
_hostUri = hostUri;
// Determine if the user provided string contains a port
if (!_hostUri.IsDefaultPort)
{
_hostHasPort = true;
}
else if (value.IndexOf(':') == -1)
{
_hostHasPort = false;
}
else
{
int endOfIPv6Address = value.IndexOf(']');
_hostHasPort = endOfIPv6Address == -1 || value.LastIndexOf(':') > endOfIPv6Address;
}
}
}
public bool Pipelined
{
get
{
return _pipelined;
}
set
{
_pipelined = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Referer header.
/// </para>
/// </devdoc>
public string Referer
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Referer];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Referer, value);
}
}
/// <devdoc>
/// <para>Sets the media type header</para>
/// </devdoc>
public string MediaType
{
get;
set;
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out.
/// </para>
/// </devdoc>
public string TransferEncoding
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool fChunked;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
//
// if the value is blank, then remove the header
//
_webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding);
return;
}
//
// if not check if the user is trying to set chunked:
//
string newValue = value.ToLower();
fChunked = (newValue.IndexOf(ChunkedHeader) != -1);
//
// prevent them from adding chunked, or from adding an Encoding without
// turning on chunked, the reason is due to the HTTP Spec which prevents
// additional encoding types from being used without chunked
//
if (fChunked)
{
throw new ArgumentException(SR.net_nochunked, nameof(value));
}
else if (!SendChunked)
{
throw new InvalidOperationException(SR.net_needchunked);
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue;
}
#if DEBUG
}
#endif
}
}
public bool KeepAlive { get; set; } = true;
public bool UnsafeAuthenticatedConnectionSharing
{
get
{
return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.UnsafeAuthenticatedConnectionSharing;
}
else
{
_booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing;
}
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
_automaticDecompression = value;
}
}
public virtual bool AllowWriteStreamBuffering
{
get
{
return (_booleans & Booleans.AllowWriteStreamBuffering) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowWriteStreamBuffering;
}
else
{
_booleans &= ~Booleans.AllowWriteStreamBuffering;
}
}
}
/// <devdoc>
/// <para>
/// Enables or disables automatically following redirection responses.
/// </para>
/// </devdoc>
public virtual bool AllowAutoRedirect
{
get
{
return (_booleans & Booleans.AllowAutoRedirect) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowAutoRedirect;
}
else
{
_booleans &= ~Booleans.AllowAutoRedirect;
}
}
}
public override string ConnectionGroupName { get; set; }
public override bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public string Connection
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Connection];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool fKeepAlive;
bool fClose;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Connection);
return;
}
string newValue = value.ToLower();
fKeepAlive = (newValue.IndexOf("keep-alive") != -1);
fClose = (newValue.IndexOf("close") != -1);
//
// Prevent keep-alive and close from being added
//
if (fKeepAlive ||
fClose)
{
throw new ArgumentException(SR.net_connarg, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/*
Accessor: Expect
The property that controls the Expect header
Input:
string Expect, null clears the Expect except for 100-continue value
Returns: The value of the Expect on get.
*/
public string Expect
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Expect];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
// only remove everything other than 100-cont
bool fContinue100;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Expect);
return;
}
//
// Prevent 100-continues from being added
//
string newValue = value.ToLower();
fContinue100 = (newValue.IndexOf(ContinueHeader) != -1);
if (fContinue100)
{
throw new ArgumentException(SR.net_no100, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// Gets or sets the default for the MaximumResponseHeadersLength property.
/// </para>
/// <remarks>
/// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property.
/// </remarks>
/// </devdoc>
public static int DefaultMaximumResponseHeadersLength
{
get
{
return _defaultMaxResponseHeadersLength;
}
set
{
_defaultMaxResponseHeadersLength = value;
}
}
// NOP
public static int DefaultMaximumErrorResponseLength
{
get; set;
}
public static new RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public DateTime IfModifiedSince
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Date header.
/// </para>
/// </devdoc>
public DateTime Date
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.Date);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.Date, value);
}
}
public bool SendChunked
{
get
{
return (_booleans & Booleans.SendChunked) != 0;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value)
{
_booleans |= Booleans.SendChunked;
}
else
{
_booleans &= ~Booleans.SendChunked;
}
}
}
public HttpContinueDelegate ContinueDelegate
{
// Nop since the underlying API do not expose 100 continue.
get
{
return _continueDelegate;
}
set
{
_continueDelegate = value;
}
}
public ServicePoint ServicePoint
{
get
{
if (_servicePoint == null)
{
_servicePoint = ServicePointManager.FindServicePoint(Address, Proxy);
}
return _servicePoint;
}
}
public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }
//
// ClientCertificates - sets our certs for our reqest,
// uses a hash of the collection to create a private connection
// group, to prevent us from using the same Connection as
// non-Client Authenticated requests.
//
public X509CertificateCollection ClientCertificates
{
get
{
if (_clientCertificates == null)
_clientCertificates = new X509CertificateCollection();
return _clientCertificates;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_clientCertificates = value;
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets and sets
/// the HTTP protocol version used in this request.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11;
}
set
{
if (value.Equals(HttpVersion.Version11))
{
IsVersionHttp10 = false;
}
else if (value.Equals(HttpVersion.Version10))
{
IsVersionHttp10 = true;
}
else
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
}
}
public int ReadWriteTimeout
{
get
{
return _readWriteTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
}
_readWriteTimeout = value;
}
}
public virtual CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
public override ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
public virtual bool HaveResponse
{
get
{
return (_sendRequestTask != null) && (_sendRequestTask.IsCompletedSuccessfully);
}
}
public override WebHeaderCollection Headers
{
get
{
return _webHeaderCollection;
}
set
{
// We can't change headers after they've already been sent.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders = new WebHeaderCollection();
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
foreach (String headerName in webHeaders.AllKeys)
{
newWebHeaders[headerName] = webHeaders[headerName];
}
_webHeaderCollection = newWebHeaders;
}
}
public override string Method
{
get
{
return _originVerb;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
_originVerb = value;
}
}
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
public virtual bool SupportsCookieContainer
{
get
{
return true;
}
}
public override bool UseDefaultCredentials
{
get
{
return (_credentials == CredentialCache.DefaultCredentials);
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
// Match Desktop behavior. Changing this property will also
// change the .Credentials property as well.
_credentials = value ? CredentialCache.DefaultCredentials : null;
}
}
public override IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
// We can't change the proxy while the request is already fired.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_proxy = value;
}
}
public override void Abort()
{
if (Interlocked.Exchange(ref _abortCalled, 1) != 0)
{
return;
}
// .NET Desktop behavior requires us to invoke outstanding callbacks
// before returning if used in either the BeginGetRequestStream or
// BeginGetResponse methods.
//
// If we can transition the task to the canceled state, then we invoke
// the callback. If we can't transition the task, it is because it is
// already in the terminal state and the callback has already been invoked
// via the async task continuation.
if (_responseOperation != null)
{
if (_responseOperation.TrySetCanceled() && _responseCallback != null)
{
_responseCallback(_responseOperation.Task);
}
// Cancel the underlying send operation.
Debug.Assert(_sendRequestCts != null);
_sendRequestCts.Cancel();
}
else if (_requestStreamOperation != null)
{
if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null)
{
_requestStreamCallback(_requestStreamOperation.Task);
}
}
}
// HTTP version of the request
private bool IsVersionHttp10
{
get
{
return (_booleans & Booleans.IsVersionHttp10) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.IsVersionHttp10;
}
else
{
_booleans &= ~Booleans.IsVersionHttp10;
}
}
}
public override WebResponse GetResponse()
{
try
{
_sendRequestCts = new CancellationTokenSource();
return SendRequest().GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
}
public override Stream GetRequestStream()
{
return InternalGetRequestStream().Result;
}
private Task<Stream> InternalGetRequestStream()
{
CheckAbort();
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
{
context = null;
return EndGetRequestStream(asyncResult);
}
public Stream GetRequestStream(out TransportContext context)
{
context = null;
return GetRequestStream();
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_requestStreamCallback = callback;
_requestStreamOperation = InternalGetRequestStream().ToApm(callback, state);
return _requestStreamOperation.Task;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<Stream>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream"));
}
Stream stream;
try
{
stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return stream;
}
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var handler = new HttpClientHandler();
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
using (var client = new HttpClient(handler))
{
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
handler.AutomaticDecompression = AutomaticDecompression;
handler.Credentials = _credentials;
handler.AllowAutoRedirect = AllowAutoRedirect;
handler.MaxAutomaticRedirections = MaximumAutomaticRedirections;
handler.MaxResponseHeadersLength = MaximumResponseHeadersLength;
handler.PreAuthenticate = PreAuthenticate;
client.Timeout = Timeout == Threading.Timeout.Infinite ?
Threading.Timeout.InfiniteTimeSpan :
TimeSpan.FromMilliseconds(Timeout);
if (_cookieContainer != null)
{
handler.CookieContainer = _cookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
if (_proxy == null)
{
handler.UseProxy = false;
}
else
{
handler.Proxy = _proxy;
}
handler.ClientCertificates.AddRange(ClientCertificates);
// Set relevant properties from ServicePointManager
handler.SslProtocols = (SslProtocols)ServicePointManager.SecurityProtocol;
handler.CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList;
RemoteCertificateValidationCallback rcvc = ServerCertificateValidationCallback != null ?
ServerCertificateValidationCallback :
ServicePointManager.ServerCertificateValidationCallback;
if (rcvc != null)
{
RemoteCertificateValidationCallback localRcvc = rcvc;
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => localRcvc(this, cert, chain, errors);
}
if (_hostUri != null)
{
request.Headers.Host = _hostUri.Host;
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers collection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content == null)
{
// Create empty content so that we can send the entity-body header.
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
request.Headers.TransferEncodingChunked = SendChunked;
if (KeepAlive)
{
request.Headers.Connection.Add(HttpKnownHeaderNames.KeepAlive);
}
else
{
request.Headers.ConnectionClose = true;
}
request.Version = ProtocolVersion;
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_sendRequestCts = new CancellationTokenSource();
_responseCallback = callback;
_responseOperation = SendRequest().ToApm(callback, state);
return _responseOperation.Task;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<WebResponse>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
WebResponse response;
try
{
response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return response;
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(int from, int to)
{
AddRange("bytes", (long)from, (long)to);
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(long from, long to)
{
AddRange("bytes", from, to);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(int range)
{
AddRange("bytes", (long)range);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(long range)
{
AddRange("bytes", range);
}
public void AddRange(string rangeSpecifier, int from, int to)
{
AddRange(rangeSpecifier, (long)from, (long)to);
}
public void AddRange(string rangeSpecifier, long from, long to)
{
//
// Do some range checking before assembling the header
//
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if ((from < 0) || (to < 0))
{
throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall);
}
if (from > to)
{
throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto);
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo)))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
public void AddRange(string rangeSpecifier, int range)
{
AddRange(rangeSpecifier, (long)range);
}
public void AddRange(string rangeSpecifier, long range)
{
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
private bool AddRange(string rangeSpecifier, string from, string to)
{
string curRange = _webHeaderCollection[HttpKnownHeaderNames.Range];
if ((curRange == null) || (curRange.Length == 0))
{
curRange = rangeSpecifier + "=";
}
else
{
if (String.Compare(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
{
return false;
}
curRange = string.Empty;
}
curRange += from.ToString();
if (to != null)
{
curRange += "-" + to;
}
_webHeaderCollection[HttpKnownHeaderNames.Range] = curRange;
return true;
}
private bool RequestSubmitted
{
get
{
return _sendRequestTask != null;
}
}
private void CheckAbort()
{
if (Volatile.Read(ref _abortCalled) == 1)
{
throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled);
}
}
private static readonly string[] s_wellKnownContentHeaders = {
HttpKnownHeaderNames.ContentDisposition,
HttpKnownHeaderNames.ContentEncoding,
HttpKnownHeaderNames.ContentLanguage,
HttpKnownHeaderNames.ContentLength,
HttpKnownHeaderNames.ContentLocation,
HttpKnownHeaderNames.ContentMD5,
HttpKnownHeaderNames.ContentRange,
HttpKnownHeaderNames.ContentType,
HttpKnownHeaderNames.Expires,
HttpKnownHeaderNames.LastModified
};
private bool IsWellKnownContentHeader(string header)
{
foreach (string contentHeaderName in s_wellKnownContentHeaders)
{
if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private DateTime GetDateHeaderHelper(string headerName)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
string headerValue = _webHeaderCollection[headerName];
if (headerValue == null)
{
return DateTime.MinValue; // MinValue means header is not present
}
return StringToDate(headerValue);
#if DEBUG
}
#endif
}
private void SetDateHeaderHelper(string headerName, DateTime dateTime)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (dateTime == DateTime.MinValue)
SetSpecialHeaders(headerName, null); // remove header
else
SetSpecialHeaders(headerName, DateToString(dateTime));
#if DEBUG
}
#endif
}
// parse String to DateTime format.
private static DateTime StringToDate(String S)
{
DateTime dtOut;
if (HttpDateParse.ParseHttpDate(S, out dtOut))
{
return dtOut;
}
else
{
throw new ProtocolViolationException(SR.net_baddate);
}
}
// convert Date to String using RFC 1123 pattern
private static string DateToString(DateTime D)
{
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo();
return D.ToUniversalTime().ToString("R", dateFormat);
}
private bool TryGetHostUri(string hostName, out Uri hostUri)
{
string s = Address.Scheme + "://" + hostName + Address.PathAndQuery;
return Uri.TryCreate(s, UriKind.Absolute, out hostUri);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Asn1
{
public class DerObjectIdentifier
: Asn1Object
{
private static readonly Regex OidRegex = new Regex(@"\A[0-2](\.[0-9]+)+\z");
private readonly string identifier;
private byte[] body = null;
/**
* return an Oid from the passed in object
*
* @exception ArgumentException if the object cannot be converted.
*/
public static DerObjectIdentifier GetInstance(
object obj)
{
if (obj == null || obj is DerObjectIdentifier)
{
return (DerObjectIdentifier) obj;
}
throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
}
/**
* return an object Identifier from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicitly true if the object is meant to be explicitly
* tagged false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static DerObjectIdentifier GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(obj.GetObject());
}
public DerObjectIdentifier(
string identifier)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
if (!OidRegex.IsMatch(identifier))
throw new FormatException("string " + identifier + " not an OID");
this.identifier = identifier;
}
// TODO Change to ID?
public string Id
{
get { return identifier; }
}
public virtual DerObjectIdentifier Branch(string branchID)
{
return new DerObjectIdentifier(identifier + "." + branchID);
}
/**
* Return true if this oid is an extension of the passed in branch, stem.
* @param stem the arc or branch that is a possible parent.
* @return true if the branch is on the passed in stem, false otherwise.
*/
public virtual bool On(DerObjectIdentifier stem)
{
string id = Id, stemId = stem.Id;
return id.Length > stemId.Length && id[stemId.Length] == '.' && id.StartsWith(stemId);
}
internal DerObjectIdentifier(byte[] bytes)
{
this.identifier = MakeOidStringFromBytes(bytes);
this.body = Arrays.Clone(bytes);
}
private void WriteField(
Stream outputStream,
long fieldValue)
{
byte[] result = new byte[9];
int pos = 8;
result[pos] = (byte)(fieldValue & 0x7f);
while (fieldValue >= (1L << 7))
{
fieldValue >>= 7;
result[--pos] = (byte)((fieldValue & 0x7f) | 0x80);
}
outputStream.Write(result, pos, 9 - pos);
}
private void WriteField(
Stream outputStream,
BigInteger fieldValue)
{
int byteCount = (fieldValue.BitLength + 6) / 7;
if (byteCount == 0)
{
outputStream.WriteByte(0);
}
else
{
BigInteger tmpValue = fieldValue;
byte[] tmp = new byte[byteCount];
for (int i = byteCount-1; i >= 0; i--)
{
tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80);
tmpValue = tmpValue.ShiftRight(7);
}
tmp[byteCount-1] &= 0x7f;
outputStream.Write(tmp, 0, tmp.Length);
}
}
private void DoOutput(MemoryStream bOut)
{
OidTokenizer tok = new OidTokenizer(identifier);
string token = tok.NextToken();
int first = int.Parse(token) * 40;
token = tok.NextToken();
if (token.Length <= 18)
{
WriteField(bOut, first + Int64.Parse(token));
}
else
{
WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first)));
}
while (tok.HasMoreTokens)
{
token = tok.NextToken();
if (token.Length <= 18)
{
WriteField(bOut, Int64.Parse(token));
}
else
{
WriteField(bOut, new BigInteger(token));
}
}
}
internal byte[] GetBody()
{
lock (this)
{
if (body == null)
{
MemoryStream bOut = new MemoryStream();
DoOutput(bOut);
body = bOut.ToArray();
}
}
return body;
}
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, GetBody());
}
protected override int Asn1GetHashCode()
{
return identifier.GetHashCode();
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerObjectIdentifier other = asn1Object as DerObjectIdentifier;
if (other == null)
return false;
return this.identifier.Equals(other.identifier);
}
public override string ToString()
{
return identifier;
}
private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f;
private static string MakeOidStringFromBytes(
byte[] bytes)
{
StringBuilder objId = new StringBuilder();
long value = 0;
BigInteger bigValue = null;
bool first = true;
for (int i = 0; i != bytes.Length; i++)
{
int b = bytes[i];
if (value <= LONG_LIMIT)
{
value += (b & 0x7f);
if ((b & 0x80) == 0) // end of number reached
{
if (first)
{
if (value < 40)
{
objId.Append('0');
}
else if (value < 80)
{
objId.Append('1');
value -= 40;
}
else
{
objId.Append('2');
value -= 80;
}
first = false;
}
objId.Append('.');
objId.Append(value);
value = 0;
}
else
{
value <<= 7;
}
}
else
{
if (bigValue == null)
{
bigValue = BigInteger.ValueOf(value);
}
bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f));
if ((b & 0x80) == 0)
{
if (first)
{
objId.Append('2');
bigValue = bigValue.Subtract(BigInteger.ValueOf(80));
first = false;
}
objId.Append('.');
objId.Append(bigValue);
bigValue = null;
value = 0;
}
else
{
bigValue = bigValue.ShiftLeft(7);
}
}
}
return objId.ToString();
}
private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024];
internal static DerObjectIdentifier FromOctetString(byte[] enc)
{
int hashCode = Arrays.GetHashCode(enc);
int first = hashCode & 1023;
lock (cache)
{
DerObjectIdentifier entry = cache[first];
if (entry != null && Arrays.AreEqual(enc, entry.GetBody()))
{
return entry;
}
return cache[first] = new DerObjectIdentifier(enc);
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.Configuration;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Frapid.NPoco;
using Serilog;
namespace Frapid.Account.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "account.applications".
/// </summary>
public class Application : DbAccess, IApplicationRepository
{
/// <summary>
/// The schema of this table. Returns literal "account".
/// </summary>
public override string _ObjectNamespace => "account";
/// <summary>
/// The schema unqualified name of this table. Returns literal "applications".
/// </summary>
public override string _ObjectName => "applications";
/// <summary>
/// Login id of application user accessing this table.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the table "account.applications".
/// </summary>
/// <returns>Returns the number of rows of the table "account.applications".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"Application\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM account.applications;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.applications" to return all instances of the "Application" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "Application" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.Application> GetAll()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"Application\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications ORDER BY application_id;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.applications" to return all instances of the "Application" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "Application" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<dynamic> Export()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"Application\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications ORDER BY application_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.applications" with a where filter on the column "application_id" to return a single instance of the "Application" class.
/// </summary>
/// <param name="applicationId">The column "application_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "Application" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.Application Get(System.Guid applicationId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get entity \"Application\" filtered by \"ApplicationId\" with value {ApplicationId} was denied to the user with Login ID {_LoginId}", applicationId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications WHERE application_id=@0;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql, applicationId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "account.applications".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "Application" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.Application GetFirst()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the first record of entity \"Application\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications ORDER BY application_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "account.applications" sorted by applicationId.
/// </summary>
/// <param name="applicationId">The column "application_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "Application" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.Application GetPrevious(System.Guid applicationId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the previous entity of \"Application\" by \"ApplicationId\" with value {ApplicationId} was denied to the user with Login ID {_LoginId}", applicationId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications WHERE application_id < @0 ORDER BY application_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql, applicationId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "account.applications" sorted by applicationId.
/// </summary>
/// <param name="applicationId">The column "application_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "Application" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.Application GetNext(System.Guid applicationId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the next entity of \"Application\" by \"ApplicationId\" with value {ApplicationId} was denied to the user with Login ID {_LoginId}", applicationId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications WHERE application_id > @0 ORDER BY application_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql, applicationId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "account.applications".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "Application" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.Application GetLast()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the last record of entity \"Application\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications ORDER BY application_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "account.applications" with a where filter on the column "application_id" to return a multiple instances of the "Application" class.
/// </summary>
/// <param name="applicationIds">Array of column "application_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "Application" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.Application> Get(System.Guid[] applicationIds)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to entity \"Application\" was denied to the user with Login ID {LoginId}. applicationIds: {applicationIds}.", this._LoginId, applicationIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications WHERE application_id IN (@0);";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql, applicationIds);
}
/// <summary>
/// Custom fields are user defined form elements for account.applications.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table account.applications</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get custom fields for entity \"Application\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string sql;
if (string.IsNullOrWhiteSpace(resourceId))
{
sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='account.applications' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('account.applications'::text, @0::text) ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId);
}
/// <summary>
/// Displayfields provide a minimal name/value context for data binding the row collection of account.applications.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table account.applications</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>();
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return displayFields;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get display field for entity \"Application\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT application_id AS key, application_name as value FROM account.applications;";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
{
if (table?.Rows == null || table.Rows.Count == 0)
{
return displayFields;
}
foreach (DataRow row in table.Rows)
{
if (row != null)
{
DisplayField displayField = new DisplayField
{
Key = row["key"].ToString(),
Value = row["value"].ToString()
};
displayFields.Add(displayField);
}
}
}
}
return displayFields;
}
/// <summary>
/// Inserts or updates the instance of Application class on the database table "account.applications".
/// </summary>
/// <param name="application">The instance of "Application" class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object AddOrEdit(dynamic application, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
application.audit_user_id = this._UserId;
application.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = application.application_id;
if (application.application_id != null)
{
this.Update(application, application.application_id);
}
else
{
primaryKeyValue = this.Add(application);
}
string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" +
"SELECT custom_field_setup_id " +
"FROM config.custom_field_setup " +
"WHERE form_name=config.get_custom_field_form_name('account.applications')" +
");";
Factory.NonQuery(this._Catalog, sql);
if (customFields == null)
{
return primaryKeyValue;
}
foreach (var field in customFields)
{
sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " +
"SELECT config.get_custom_field_setup_id_by_table_name('account.applications', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of Application class on the database table "account.applications".
/// </summary>
/// <param name="application">The instance of "Application" class to insert.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object Add(dynamic application)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"Application\" was denied to the user with Login ID {LoginId}. {Application}", this._LoginId, application);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, application, "account.applications", "application_id");
}
/// <summary>
/// Inserts or updates multiple instances of Application class on the database table "account.applications";
/// </summary>
/// <param name="applications">List of "Application" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> applications)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"Application\" was denied to the user with Login ID {LoginId}. {applications}", this._LoginId, applications);
throw new UnauthorizedException("Access is denied.");
}
}
var result = new List<object>();
int line = 0;
try
{
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
foreach (dynamic application in applications)
{
line++;
application.audit_user_id = this._UserId;
application.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = application.application_id;
if (application.application_id != null)
{
result.Add(application.application_id);
db.Update("account.applications", "application_id", application, application.application_id);
}
else
{
result.Add(db.Insert("account.applications", "application_id", application));
}
}
transaction.Complete();
}
return result;
}
}
catch (NpgsqlException ex)
{
string errorMessage = $"Error on line {line} ";
if (ex.Code.StartsWith("P"))
{
errorMessage += Factory.GetDbErrorResource(ex);
throw new DataAccessException(errorMessage, ex);
}
errorMessage += ex.Message;
throw new DataAccessException(errorMessage, ex);
}
catch (System.Exception ex)
{
string errorMessage = $"Error on line {line} ";
throw new DataAccessException(errorMessage, ex);
}
}
/// <summary>
/// Updates the row of the table "account.applications" with an instance of "Application" class against the primary key value.
/// </summary>
/// <param name="application">The instance of "Application" class to update.</param>
/// <param name="applicationId">The value of the column "application_id" which will be updated.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Update(dynamic application, System.Guid applicationId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to edit entity \"Application\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {Application}", applicationId, this._LoginId, application);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, application, applicationId, "account.applications", "application_id");
}
/// <summary>
/// Deletes the row of the table "account.applications" against the primary key value.
/// </summary>
/// <param name="applicationId">The value of the column "application_id" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(System.Guid applicationId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"Application\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", applicationId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM account.applications WHERE application_id=@0;";
Factory.NonQuery(this._Catalog, sql, applicationId);
}
/// <summary>
/// Performs a select statement on table "account.applications" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "Application" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.Application> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"Application\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.applications ORDER BY application_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "account.applications" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "Application" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.Application> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"Application\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM account.applications ORDER BY application_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='account.applications' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "account.applications".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "Application" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"Application\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.applications WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Application(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.applications" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "Application" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.Application> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"Application\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM account.applications WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Application(), filters);
sql.OrderBy("application_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "account.applications".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "Application" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"Application\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.applications WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Application(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.applications" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "Application" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.Application> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"Application\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM account.applications WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Application(), filters);
sql.OrderBy("application_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.Application>(this._Catalog, sql);
}
}
}
| |
//
// Mono.System.Xml.XmlNode
//
// Author:
// Kral Ferch <kral_ferch@hotmail.com>
// Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
//
// (C) 2002 Kral Ferch
// (C) 2002 Atsushi Enomoto
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using Mono.System.Xml.XPath;
using System.Diagnostics;
using Mono.System.Xml.Schema;
namespace Mono.System.Xml
{
public abstract class XmlNode : ICloneable, IEnumerable//, IXPathNavigable
{
static EmptyNodeList emptyList = new EmptyNodeList ();
class EmptyNodeList : XmlNodeList
{
static IEnumerator emptyEnumerator = new object [0].GetEnumerator ();
public override int Count {
get { return 0; }
}
public override IEnumerator GetEnumerator ()
{
return emptyEnumerator;
}
public override XmlNode Item (int index)
{
return null;
}
}
#region Fields
XmlDocument ownerDocument;
XmlNode parentNode;
XmlNodeListChildren childNodes;
#endregion
#region Constructors
internal XmlNode (XmlDocument ownerDocument)
{
this.ownerDocument = ownerDocument;
}
#endregion
#region Properties
public virtual XmlAttributeCollection Attributes {
get { return null; }
}
public virtual string BaseURI {
get {
// Isn't it conformant to W3C XML Base Recommendation?
// As far as I tested, there are not...
return (ParentNode != null) ? ParentNode.ChildrenBaseURI : String.Empty;
}
}
internal virtual string ChildrenBaseURI {
get {
return BaseURI;
}
}
public virtual XmlNodeList ChildNodes {
get {
IHasXmlChildNode l = this as IHasXmlChildNode;
if (l == null)
return emptyList;
if (childNodes == null)
childNodes = new XmlNodeListChildren (l);
return childNodes;
}
}
public virtual XmlNode FirstChild {
get {
IHasXmlChildNode l = this as IHasXmlChildNode;
XmlLinkedNode c = (l == null) ?
null : l.LastLinkedChild;
return c == null ? null : c.NextLinkedSibling;
}
}
public virtual bool HasChildNodes {
get { return LastChild != null; }
}
public virtual string InnerText {
get {
switch (NodeType) {
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
return Value;
}
if (FirstChild == null)
return String.Empty;
if (FirstChild == LastChild)
return FirstChild.NodeType != XmlNodeType.Comment ?
FirstChild.InnerText :
String.Empty;
StringBuilder builder = null;
AppendChildValues (ref builder);
return builder == null ? String.Empty : builder.ToString ();
}
set {
if (! (this is XmlDocumentFragment))
throw new InvalidOperationException ("This node is read only. Cannot be modified.");
RemoveAll ();
AppendChild (OwnerDocument.CreateTextNode (value));
}
}
private void AppendChildValues (ref StringBuilder builder)
{
XmlNode node = FirstChild;
while (node != null) {
switch (node.NodeType) {
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
if (builder == null)
builder = new StringBuilder ();
builder.Append (node.Value);
break;
}
node.AppendChildValues (ref builder);
node = node.NextSibling;
}
}
public virtual string InnerXml {
get {
StringWriter sw = new StringWriter ();
XmlTextWriter xtw = new XmlTextWriter (sw);
WriteContentTo (xtw);
return sw.GetStringBuilder ().ToString ();
}
set {
throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
}
}
public virtual bool IsReadOnly {
get
{
XmlNode curNode = this;
do
{
switch (curNode.NodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
return true;
case XmlNodeType.Attribute:
curNode = ((XmlAttribute)curNode).OwnerElement;
break;
default:
curNode = curNode.ParentNode;
break;
}
}
while (curNode != null) ;
return false;
}
}
[global::System.Runtime.CompilerServices.IndexerName ("Item")]
public virtual XmlElement this [string name] {
get {
for (int i = 0; i < ChildNodes.Count; i++) {
XmlNode node = ChildNodes [i];
if ((node.NodeType == XmlNodeType.Element) &&
(node.Name == name)) {
return (XmlElement) node;
}
}
return null;
}
}
[global::System.Runtime.CompilerServices.IndexerName ("Item")]
public virtual XmlElement this [string localname, string ns] {
get {
for (int i = 0; i < ChildNodes.Count; i++) {
XmlNode node = ChildNodes [i];
if ((node.NodeType == XmlNodeType.Element) &&
(node.LocalName == localname) &&
(node.NamespaceURI == ns)) {
return (XmlElement) node;
}
}
return null;
}
}
public virtual XmlNode LastChild {
get {
IHasXmlChildNode l = this as IHasXmlChildNode;
return l == null ? null : l.LastLinkedChild;
}
}
public abstract string LocalName { get; }
public abstract string Name { get; }
public virtual string NamespaceURI {
get { return String.Empty; }
}
public virtual XmlNode NextSibling {
get { return null; }
}
public abstract XmlNodeType NodeType { get; }
internal virtual XPathNodeType XPathNodeType {
get {
throw new InvalidOperationException ("Can not get XPath node type from " + this.GetType ().ToString ());
}
}
public virtual string OuterXml {
get {
StringWriter sw = new StringWriter ();
XmlTextWriter xtw = new XmlTextWriter (sw);
WriteTo (xtw);
return sw.ToString ();
}
}
public virtual XmlDocument OwnerDocument {
get { return ownerDocument; }
}
public virtual XmlNode ParentNode {
get { return parentNode; }
}
public virtual string Prefix {
get { return String.Empty; }
set {}
}
public virtual XmlNode PreviousSibling {
get { return null; }
}
public virtual string Value {
get { return null; }
set { throw new InvalidOperationException ("This node does not have a value"); }
}
internal virtual string XmlLang {
get {
if(Attributes != null)
for (int i = 0; i < Attributes.Count; i++) {
XmlAttribute attr = Attributes [i];
if(attr.Name == "xml:lang")
return attr.Value;
}
return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
}
}
internal virtual XmlSpace XmlSpace {
get {
if(Attributes != null) {
for (int i = 0; i < Attributes.Count; i++) {
XmlAttribute attr = Attributes [i];
if(attr.Name == "xml:space") {
switch(attr.Value) {
case "preserve": return XmlSpace.Preserve;
case "default": return XmlSpace.Default;
}
break;
}
}
}
return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
}
}
public virtual IXmlSchemaInfo SchemaInfo {
get { return null; }
internal set { }
}
#endregion
#region Methods
public virtual XmlNode AppendChild (XmlNode newChild)
{
// AppendChild(n) is equivalent to InsertBefore(n, null)
return InsertBefore (newChild, null);
}
internal XmlNode AppendChild (XmlNode newChild, bool checkNodeType)
{
return InsertBefore (newChild, null, checkNodeType, true);
}
public virtual XmlNode Clone ()
{
// By MS document, it is equivalent to CloneNode(true).
return this.CloneNode (true);
}
public abstract XmlNode CloneNode (bool deep);
//public virtual XPathNavigator CreateNavigator ()
//{
// // XmlDocument has overriden definition, so it is safe
// // to use OwnerDocument here.
// return OwnerDocument.CreateNavigator (this);
//}
public IEnumerator GetEnumerator ()
{
return ChildNodes.GetEnumerator ();
}
public virtual string GetNamespaceOfPrefix (string prefix)
{
switch (prefix) {
case null:
throw new ArgumentNullException ("prefix");
case "xml":
return XmlNamespaceManager.XmlnsXml;
case "xmlns":
return XmlNamespaceManager.XmlnsXmlns;
}
XmlNode node;
switch (NodeType) {
case XmlNodeType.Attribute:
node = ((XmlAttribute) this).OwnerElement;
if (node == null)
return String.Empty;
break;
case XmlNodeType.Element:
node = this;
break;
default:
node = ParentNode;
break;
}
while (node != null) {
if (node.Prefix == prefix)
return node.NamespaceURI;
if (node.NodeType == XmlNodeType.Element &&
((XmlElement) node).HasAttributes) {
int count = node.Attributes.Count;
for (int i = 0; i < count; i++) {
XmlAttribute attr = node.Attributes [i];
if (prefix == attr.LocalName && attr.Prefix == "xmlns"
|| attr.Name == "xmlns" && prefix == String.Empty)
return attr.Value;
}
}
node = node.ParentNode;
}
return String.Empty;
}
public virtual string GetPrefixOfNamespace (string namespaceURI)
{
switch (namespaceURI) {
case XmlNamespaceManager.XmlnsXml:
return XmlNamespaceManager.PrefixXml;
case XmlNamespaceManager.XmlnsXmlns:
return XmlNamespaceManager.PrefixXmlns;
}
XmlNode node;
switch (NodeType) {
case XmlNodeType.Attribute:
node = ((XmlAttribute) this).OwnerElement;
break;
case XmlNodeType.Element:
node = this;
break;
default:
node = ParentNode;
break;
}
while (node != null) {
if (node.NodeType == XmlNodeType.Element &&
((XmlElement) node).HasAttributes) {
for (int i = 0; i < node.Attributes.Count; i++) {
XmlAttribute attr = node.Attributes [i];
if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
return attr.LocalName;
else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
return String.Empty;
}
}
node = node.ParentNode;
}
return String.Empty;
}
object ICloneable.Clone ()
{
return Clone ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
{
// InsertAfter(n1, n2) is equivalent to InsertBefore(n1, n2.PreviousSibling).
// I took this way because current implementation
// Calling InsertBefore() in this method is faster than
// the counterpart, since NextSibling is faster than
// PreviousSibling (these children are forward-only list).
XmlNode argNode = null;
if (refChild != null)
argNode = refChild.NextSibling;
else if (FirstChild != null)
argNode = FirstChild;
return InsertBefore (newChild, argNode);
}
public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
{
return InsertBefore (newChild, refChild, true, true);
}
// check for the node to be one of node ancestors
internal bool IsAncestor (XmlNode newChild)
{
XmlNode currNode = this.ParentNode;
while(currNode != null)
{
if(currNode == newChild)
return true;
currNode = currNode.ParentNode;
}
return false;
}
internal XmlNode InsertBefore (XmlNode newChild, XmlNode refChild, bool checkNodeType, bool raiseEvent)
{
if (checkNodeType)
CheckNodeInsertion (newChild, refChild);
if (newChild == refChild)
return newChild;
IHasXmlChildNode l = (IHasXmlChildNode) this;
XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
if (raiseEvent)
ownerDoc.onNodeInserting (newChild, this);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild (newChild, checkNodeType);
if (newChild.NodeType == XmlNodeType.DocumentFragment) {
// This recursively invokes events. (It is compatible with MS implementation.)
XmlNode ret = null;
while (newChild.FirstChild != null) {
var c = this.InsertBefore (newChild.FirstChild, refChild);
ret = ret ?? c;
}
return ret;
} else {
XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
newLinkedChild.parentNode = this;
if (refChild == null) {
// newChild is the last child:
// * set newChild as NextSibling of the existing lastchild
// * set LastChild = newChild
// * set NextSibling of newChild as FirstChild
if (l.LastLinkedChild != null) {
XmlLinkedNode formerFirst = (XmlLinkedNode) FirstChild;
l.LastLinkedChild.NextLinkedSibling = newLinkedChild;
l.LastLinkedChild = newLinkedChild;
newLinkedChild.NextLinkedSibling = formerFirst;
} else {
l.LastLinkedChild = newLinkedChild;
l.LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
}
} else {
// newChild is not the last child:
// * if newchild is first, then set next of lastchild is newChild.
// otherwise, set next of previous sibling to newChild
// * set next of newChild to refChild
XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
if (prev == null)
l.LastLinkedChild.NextLinkedSibling = newLinkedChild;
else
prev.NextLinkedSibling = newLinkedChild;
newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
}
switch (newChild.NodeType) {
case XmlNodeType.EntityReference:
((XmlEntityReference) newChild).SetReferencedEntityContent ();
break;
case XmlNodeType.Entity:
break;
case XmlNodeType.DocumentType:
break;
}
if (raiseEvent)
ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
return newChild;
}
}
private void CheckNodeInsertion (XmlNode newChild, XmlNode refChild)
{
XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
if (NodeType != XmlNodeType.Element &&
NodeType != XmlNodeType.Attribute &&
NodeType != XmlNodeType.Document &&
NodeType != XmlNodeType.DocumentFragment)
throw new InvalidOperationException (String.Format ("Node cannot be appended to current node {0}.", NodeType));
switch (NodeType) {
case XmlNodeType.Attribute:
switch (newChild.NodeType) {
case XmlNodeType.Text:
case XmlNodeType.EntityReference:
break;
default:
throw new InvalidOperationException (String.Format (
"Cannot insert specified type of node {0} as a child of this node {1}.",
newChild.NodeType, NodeType));
}
break;
case XmlNodeType.Element:
switch (newChild.NodeType) {
case XmlNodeType.Attribute:
case XmlNodeType.Document:
case XmlNodeType.DocumentType:
case XmlNodeType.Entity:
case XmlNodeType.Notation:
case XmlNodeType.XmlDeclaration:
throw new InvalidOperationException ("Cannot insert specified type of node as a child of this node.");
}
break;
}
if (IsReadOnly)
throw new InvalidOperationException ("The node is readonly.");
if (newChild.OwnerDocument != ownerDoc)
throw new ArgumentException ("Can't append a node created by another document.");
if (refChild != null) {
if (refChild.ParentNode != this)
throw new ArgumentException ("The reference node is not a child of this node.");
}
if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement) && newChild != ownerDoc.DocumentElement)
throw new XmlException ("multiple document element not allowed.");
// checking validity finished. then appending...
if (newChild == this || IsAncestor (newChild))
throw new ArgumentException("Cannot insert a node or any ancestor of that node as a child of itself.");
}
public virtual void Normalize ()
{
StringBuilder tmpBuilder = new StringBuilder ();
int count = this.ChildNodes.Count;
int start = 0;
for (int i = 0; i < count; i++) {
XmlNode c = ChildNodes [i];
switch (c.NodeType) {
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
tmpBuilder.Append (c.Value);
break;
default:
c.Normalize ();
NormalizeRange (start, i, tmpBuilder);
// Continue to normalize from next node.
start = i + 1;
break;
}
}
if (start < count) {
NormalizeRange (start, count, tmpBuilder);
}
}
private void NormalizeRange (int start, int i, StringBuilder tmpBuilder)
{
int keepPos = -1;
// If Texts and Whitespaces are mixed, Text takes precedence to remain.
// i.e. Whitespace should be removed.
for (int j = start; j < i; j++) {
XmlNode keep = ChildNodes [j];
if (keep.NodeType == XmlNodeType.Text) {
keepPos = j;
break;
}
else if (keep.NodeType == XmlNodeType.SignificantWhitespace)
keepPos = j;
// but don't break up to find Text nodes.
}
if (keepPos >= 0) {
for (int del = start; del < keepPos; del++)
RemoveChild (ChildNodes [start]);
int rest = i - keepPos - 1;
for (int del = 0; del < rest; del++) {
RemoveChild (ChildNodes [start + 1]);
}
}
if (keepPos >= 0)
ChildNodes [start].Value = tmpBuilder.ToString ();
// otherwise nothing to be normalized
tmpBuilder.Length = 0;
}
public virtual XmlNode PrependChild (XmlNode newChild)
{
return InsertAfter (newChild, null);
}
public virtual void RemoveAll ()
{
if (Attributes != null)
Attributes.RemoveAll ();
XmlNode next = null;
for (XmlNode node = FirstChild; node != null; node = next) {
next = node.NextSibling;
RemoveChild (node);
}
}
public virtual XmlNode RemoveChild (XmlNode oldChild)
{
return RemoveChild (oldChild, true);
}
private void CheckNodeRemoval ()
{
if (NodeType != XmlNodeType.Attribute &&
NodeType != XmlNodeType.Element &&
NodeType != XmlNodeType.Document &&
NodeType != XmlNodeType.DocumentFragment)
throw new ArgumentException (String.Format ("This {0} node cannot remove its child.", NodeType));
if (IsReadOnly)
throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
}
internal XmlNode RemoveChild (XmlNode oldChild, bool checkNodeType)
{
if (oldChild == null)
throw new NullReferenceException ();
XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
if(oldChild.ParentNode != this)
throw new ArgumentException ("The node to be removed is not a child of this node.");
if (checkNodeType)
ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
if (checkNodeType)
CheckNodeRemoval ();
IHasXmlChildNode l = (IHasXmlChildNode) this;
if (Object.ReferenceEquals (l.LastLinkedChild, l.LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (l.LastLinkedChild, oldChild))
// If there is only one children, simply clear.
l.LastLinkedChild = null;
else {
XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
XmlLinkedNode beforeLinkedChild = l.LastLinkedChild;
XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, l.LastLinkedChild) == false &&
Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
throw new ArgumentException ();
beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
// Each derived class may have its own l.LastLinkedChild, so we must set it explicitly.
if (oldLinkedChild.NextLinkedSibling == firstChild)
l.LastLinkedChild = beforeLinkedChild;
oldLinkedChild.NextLinkedSibling = null;
}
if (checkNodeType)
ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
oldChild.parentNode = null; // clear parent 'after' above logic.
return oldChild;
}
public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
{
if(oldChild.ParentNode != this)
throw new ArgumentException ("The node to be removed is not a child of this node.");
if (newChild == this || IsAncestor (newChild))
throw new InvalidOperationException("Cannot insert a node or any ancestor of that node as a child of itself.");
XmlNode next = oldChild.NextSibling;
RemoveChild (oldChild);
InsertBefore (newChild, next);
return oldChild;
}
// WARNING: don't use this member outside XmlAttribute nodes.
internal XmlElement AttributeOwnerElement {
get { return (XmlElement) parentNode; }
set { parentNode = value; }
}
internal void SearchDescendantElements (string name, bool matchAll, ArrayList list)
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
if (n.NodeType != XmlNodeType.Element)
continue;
if (matchAll || n.Name == name)
list.Add (n);
n.SearchDescendantElements (name, matchAll, list);
}
}
internal void SearchDescendantElements (string name, bool matchAllName, string ns, bool matchAllNS, ArrayList list)
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
if (n.NodeType != XmlNodeType.Element)
continue;
if ((matchAllName || n.LocalName == name)
&& (matchAllNS || n.NamespaceURI == ns))
list.Add (n);
n.SearchDescendantElements (name, matchAllName, ns, matchAllNS, list);
}
}
//public XmlNodeList SelectNodes (string xpath)
//{
// return SelectNodes (xpath, null);
//}
//public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
//{
// XPathNavigator nav = CreateNavigator ();
// XPathExpression expr = nav.Compile (xpath);
// if (nsmgr != null)
// expr.SetContext (nsmgr);
// XPathNodeIterator iter = nav.Select (expr);
// /*
// ArrayList rgNodes = new ArrayList ();
// while (iter.MoveNext ())
// {
// rgNodes.Add (((IHasXmlNode) iter.Current).GetNode ());
// }
// return new XmlNodeArrayList (rgNodes);
// */
// return new XmlIteratorNodeList (this as XmlDocument ?? ownerDocument, iter);
//}
//public XmlNode SelectSingleNode (string xpath)
//{
// return SelectSingleNode (xpath, null);
//}
//
//public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
//{
// XPathNavigator nav = CreateNavigator ();
// XPathExpression expr = nav.Compile (xpath);
// if (nsmgr != null)
// expr.SetContext (nsmgr);
// XPathNodeIterator iter = nav.Select (expr);
// if (!iter.MoveNext ())
// return null;
// return (iter.Current as IHasXmlNode).GetNode ();
//}
public virtual bool Supports (string feature, string version)
{
if (String.Compare (feature, "xml", true, CultureInfo.InvariantCulture) == 0 // not case-sensitive
&& (String.Compare (version, "1.0", true, CultureInfo.InvariantCulture) == 0
|| String.Compare (version, "2.0", true, CultureInfo.InvariantCulture) == 0))
return true;
else
return false;
}
public abstract void WriteContentTo (XmlWriter w);
public abstract void WriteTo (XmlWriter w);
// It parses this and all the ancestor elements,
// find 'xmlns' declarations, stores and then return them.
internal XmlNamespaceManager ConstructNamespaceManager ()
{
XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
XmlElement el = null;
switch(this.NodeType) {
case XmlNodeType.Attribute:
el = ((XmlAttribute)this).OwnerElement;
break;
case XmlNodeType.Element:
el = this as XmlElement;
break;
default:
el = this.ParentNode as XmlElement;
break;
}
while (el != null) {
for (int i = 0; i < el.Attributes.Count; i++) {
XmlAttribute attr = el.Attributes [i];
if(attr.Prefix == "xmlns") {
if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
nsmgr.AddNamespace (attr.LocalName, attr.Value);
} else if(attr.Name == "xmlns") {
if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
nsmgr.AddNamespace (String.Empty, attr.Value);
}
}
// When reached to document, then it will set null value :)
el = el.ParentNode as XmlElement;
}
return nsmgr;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SwaggerToTypeScriptClientCommand.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System.Threading.Tasks;
using NConsole;
using Newtonsoft.Json;
using NJsonSchema.CodeGeneration.TypeScript;
using NJsonSchema.Infrastructure;
using NSwag.CodeGeneration.CodeGenerators;
using NSwag.CodeGeneration.CodeGenerators.TypeScript;
using NSwag.Commands.Base;
#pragma warning disable 1591
namespace NSwag.Commands
{
[Command(Name = "swagger2tsclient", Description = "Generates TypeScript client code from a Swagger specification.")]
public class SwaggerToTypeScriptClientCommand : InputOutputCommandBase
{
public SwaggerToTypeScriptClientCommand()
{
Settings = new SwaggerToTypeScriptClientGeneratorSettings();
}
[JsonIgnore]
public SwaggerToTypeScriptClientGeneratorSettings Settings { get; set; }
[Argument(Name = "ClassName", IsRequired = false, Description = "The class name of the generated client.")]
public string ClassName
{
get { return Settings.ClassName; }
set { Settings.ClassName = value; }
}
[Argument(Name = "ModuleName", IsRequired = false, Description = "The TypeScript module name (default: '', no module).")]
public string ModuleName
{
get { return Settings.TypeScriptGeneratorSettings.ModuleName; }
set { Settings.TypeScriptGeneratorSettings.ModuleName = value; }
}
[Argument(Name = "Namespace", IsRequired = false, Description = "The TypeScript namespace (default: '', no namespace).")]
public string Namespace
{
get { return Settings.TypeScriptGeneratorSettings.Namespace; }
set { Settings.TypeScriptGeneratorSettings.Namespace = value; }
}
[Argument(Name = "TypeScriptVersion", IsRequired = false, Description = "The target TypeScript version (default: 1.8).")]
public decimal TypeScriptVersion
{
get { return Settings.TypeScriptGeneratorSettings.TypeScriptVersion; }
set { Settings.TypeScriptGeneratorSettings.TypeScriptVersion = value; }
}
[Argument(Name = "Template", IsRequired = false, Description = "The type of the asynchronism handling " +
"('JQueryCallbacks', 'JQueryPromises', 'AngularJS', 'Angular2', 'Fetch', 'Aurelia').")]
public TypeScriptTemplate Template
{
get { return Settings.Template; }
set { Settings.Template = value; }
}
[Argument(Name = "PromiseType", IsRequired = false, Description = "The promise type ('Promise' or 'QPromise').")]
public PromiseType PromiseType
{
get { return Settings.PromiseType; }
set { Settings.PromiseType = value; }
}
[Argument(Name = "DateTimeType", IsRequired = false, Description = "The date time type ('Date', 'MomentJS', 'string').")]
public TypeScriptDateTimeType DateTimeType
{
get { return Settings.TypeScriptGeneratorSettings.DateTimeType; }
set { Settings.TypeScriptGeneratorSettings.DateTimeType = value; }
}
[Argument(Name = "GenerateClientClasses", IsRequired = false, Description = "Specifies whether generate client classes.")]
public bool GenerateClientClasses
{
get { return Settings.GenerateClientClasses; }
set { Settings.GenerateClientClasses = value; }
}
[Argument(Name = "GenerateClientInterfaces", IsRequired = false, Description = "Specifies whether generate interfaces for the client classes (default: false).")]
public bool GenerateClientInterfaces
{
get { return Settings.GenerateClientInterfaces; }
set { Settings.GenerateClientInterfaces = value; }
}
[Argument(Name = "WrapDtoExceptions", IsRequired = false, Description = "Specifies whether DTO exceptions are wrapped in a SwaggerException instance (default: false).")]
public bool WrapDtoExceptions
{
get { return Settings.WrapDtoExceptions; }
set { Settings.WrapDtoExceptions = value; }
}
[Argument(Name = "ClientBaseClass", IsRequired = false, Description = "The base class of the generated client classes (optional, must be imported or implemented in the extension code).")]
public string ClientBaseClass
{
get { return Settings.ClientBaseClass; }
set { Settings.ClientBaseClass = value; }
}
[Argument(Name = "UseTransformOptionsMethod", IsRequired = false, Description = "Call 'transformOptions' on the base class or extension class (default: false).")]
public bool UseTransformOptionsMethod
{
get { return Settings.UseTransformOptionsMethod; }
set { Settings.UseTransformOptionsMethod = value; }
}
[Argument(Name = "UseTransformResultMethod", IsRequired = false, Description = "Call 'transformResult' on the base class or extension class (default: false).")]
public bool UseTransformResultMethod
{
get { return Settings.UseTransformResultMethod; }
set { Settings.UseTransformResultMethod = value; }
}
[Argument(Name = "GenerateDtoTypes", IsRequired = false, Description = "Specifies whether to generate DTO classes.")]
public bool GenerateDtoTypes
{
get { return Settings.GenerateDtoTypes; }
set { Settings.GenerateDtoTypes = value; }
}
[Argument(Name = "OperationGenerationMode", IsRequired = false, Description = "The operation generation mode ('SingleClientFromOperationId' or 'MultipleClientsFromPathSegments').")]
public OperationGenerationMode OperationGenerationMode
{
get { return Settings.OperationGenerationMode; }
set { Settings.OperationGenerationMode = value; }
}
[Argument(Name = "MarkOptionalProperties", IsRequired = false, Description = "Specifies whether to mark optional properties with ? (default: false).")]
public bool MarkOptionalProperties
{
get { return Settings.TypeScriptGeneratorSettings.MarkOptionalProperties; }
set { Settings.TypeScriptGeneratorSettings.MarkOptionalProperties = value; }
}
[Argument(Name = "TypeStyle", IsRequired = false, Description = "The type style (default: Class).")]
public TypeScriptTypeStyle TypeStyle
{
get { return Settings.TypeScriptGeneratorSettings.TypeStyle; }
set { Settings.TypeScriptGeneratorSettings.TypeStyle = value; }
}
[Argument(Name = "ClassTypes", IsRequired = false, Description = "The type names which always generate plain TypeScript classes.")]
public string[] ClassTypes
{
get { return Settings.TypeScriptGeneratorSettings.ClassTypes; }
set { Settings.TypeScriptGeneratorSettings.ClassTypes = value; }
}
[Argument(Name = "ExtendedClasses", IsRequired = false, Description = "The list of extended classes.")]
public string[] ExtendedClasses
{
get { return Settings.TypeScriptGeneratorSettings.ExtendedClasses; }
set { Settings.TypeScriptGeneratorSettings.ExtendedClasses = value; }
}
[Argument(Name = "ExtensionCode", IsRequired = false, Description = "The extension code (string or file path).")]
public string ExtensionCode { get; set; }
[Argument(Name = "GenerateDefaultValues", IsRequired = false, Description = "Specifies whether to generate default values for properties (default: true).")]
public bool GenerateDefaultValues
{
get { return Settings.TypeScriptGeneratorSettings.GenerateDefaultValues; }
set { Settings.TypeScriptGeneratorSettings.GenerateDefaultValues = value; }
}
[Argument(Name = "ExcludedTypeNames", IsRequired = false, Description = "The excluded DTO type names (must be defined in an import or other namespace).")]
public string[] ExcludedTypeNames
{
get { return Settings.TypeScriptGeneratorSettings.ExcludedTypeNames; }
set { Settings.TypeScriptGeneratorSettings.ExcludedTypeNames = value; }
}
public override async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
{
var code = await RunAsync();
if (await TryWriteFileOutputAsync(host, () => code).ConfigureAwait(false) == false)
return code;
return null;
}
public async Task<string> RunAsync()
{
return await Task.Run(async () =>
{
var additionalCode = ExtensionCode ?? string.Empty;
if (await DynamicApis.FileExistsAsync(additionalCode).ConfigureAwait(false))
additionalCode = await DynamicApis.FileReadAllTextAsync(additionalCode).ConfigureAwait(false);
Settings.TypeScriptGeneratorSettings.ExtensionCode = additionalCode;
var document = await GetInputSwaggerDocument().ConfigureAwait(false);
var clientGenerator = new SwaggerToTypeScriptClientGenerator(document, Settings);
return clientGenerator.GenerateFile();
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Newtonsoft.Json;
using Orleans.Configuration;
using Orleans.Persistence.DynamoDB;
using Orleans.Runtime;
using Orleans.Serialization;
namespace Orleans.Storage
{
/// <summary>
/// Dynamo DB storage Provider.
/// Persist Grain State in a DynamoDB table either in Json or Binary format.
/// </summary>
public class DynamoDBGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle>
{
private const int MAX_DATA_SIZE = 400 * 1024;
private const string GRAIN_REFERENCE_PROPERTY_NAME = "GrainReference";
private const string STRING_STATE_PROPERTY_NAME = "StringState";
private const string BINARY_STATE_PROPERTY_NAME = "BinaryState";
private const string GRAIN_TYPE_PROPERTY_NAME = "GrainType";
private const string ETAG_PROPERTY_NAME = "ETag";
private const string GRAIN_TTL_PROPERTY_NAME = "GrainTtl";
private const string CURRENT_ETAG_ALIAS = ":currentETag";
private readonly DynamoDBStorageOptions options;
private readonly SerializationManager serializationManager;
private readonly ILogger logger;
private readonly IServiceProvider serviceProvider;
private readonly GrainReferenceKeyStringConverter grainReferenceConverter;
private readonly string name;
private DynamoDBStorage storage;
private JsonSerializerSettings jsonSettings;
/// <summary>
/// Default Constructor
/// </summary>
public DynamoDBGrainStorage(
string name,
DynamoDBStorageOptions options,
SerializationManager serializationManager,
IServiceProvider serviceProvider,
GrainReferenceKeyStringConverter grainReferenceConverter,
ILogger<DynamoDBGrainStorage> logger)
{
this.name = name;
this.logger = logger;
this.options = options;
this.serializationManager = serializationManager;
this.serviceProvider = serviceProvider;
this.grainReferenceConverter = grainReferenceConverter;
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(OptionFormattingUtilities.Name<DynamoDBGrainStorage>(this.name), this.options.InitStage, Init, Close);
}
/// <summary> Initialization function for this storage provider. </summary>
public async Task Init(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
try
{
var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}",
this.name, this.options.ServiceId, this.options.TableName, this.options.DeleteStateOnClear);
this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(
OrleansJsonSerializer.GetDefaultSerializerSettings(this.serviceProvider),
this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);
this.options.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);
this.logger.LogInformation((int)ErrorCode.StorageProviderBase, $"AWS DynamoDB Grain Storage {this.name} is initializing: {initMsg}");
this.storage = new DynamoDBStorage(this.logger, this.options.Service, this.options.AccessKey, this.options.SecretKey,
this.options.ReadCapacityUnits, this.options.WriteCapacityUnits, this.options.UseProvisionedThroughput);
await storage.InitializeTable(this.options.TableName,
new List<KeySchemaElement>
{
new KeySchemaElement { AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, KeyType = KeyType.HASH },
new KeySchemaElement { AttributeName = GRAIN_TYPE_PROPERTY_NAME, KeyType = KeyType.RANGE }
},
new List<AttributeDefinition>
{
new AttributeDefinition { AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S },
new AttributeDefinition { AttributeName = GRAIN_TYPE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S }
},
secondaryIndexes: null,
ttlAttributeName: this.options.TimeToLive.HasValue ? GRAIN_TTL_PROPERTY_NAME : null);
stopWatch.Stop();
this.logger.LogInformation((int)ErrorCode.StorageProviderBase,
$"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
}
catch (Exception exc)
{
stopWatch.Stop();
this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", exc);
throw;
}
}
/// <summary> Shutdown this storage provider. </summary>
public Task Close(CancellationToken ct) => Task.CompletedTask;
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
if (this.storage == null) throw new ArgumentException("GrainState-Table property not initialized");
string partitionKey = GetKeyString(grainReference);
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace(ErrorCode.StorageProviderBase,
"Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}",
grainType, partitionKey, grainReference, this.options.TableName);
string rowKey = AWSUtils.ValidateDynamoDBRowKey(grainType);
var record = await this.storage.ReadSingleEntryAsync(this.options.TableName,
new Dictionary<string, AttributeValue>
{
{ GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(partitionKey) },
{ GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(rowKey) }
},
(fields) =>
{
return new GrainStateRecord
{
GrainType = fields[GRAIN_TYPE_PROPERTY_NAME].S,
GrainReference = fields[GRAIN_REFERENCE_PROPERTY_NAME].S,
ETag = int.Parse(fields[ETAG_PROPERTY_NAME].N),
BinaryState = fields.ContainsKey(BINARY_STATE_PROPERTY_NAME) ? fields[BINARY_STATE_PROPERTY_NAME].B.ToArray() : null,
StringState = fields.ContainsKey(STRING_STATE_PROPERTY_NAME) ? fields[STRING_STATE_PROPERTY_NAME].S : string.Empty
};
}).ConfigureAwait(false);
if (record != null)
{
var loadedState = ConvertFromStorageFormat(record, grainState.Type);
grainState.RecordExists = loadedState != null;
grainState.State = loadedState ?? Activator.CreateInstance(grainState.Type);
grainState.ETag = record.ETag.ToString();
}
// Else leave grainState in previous default condition
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
if (this.storage == null) throw new ArgumentException("GrainState-Table property not initialized");
string partitionKey = GetKeyString(grainReference);
string rowKey = AWSUtils.ValidateDynamoDBRowKey(grainType);
var record = new GrainStateRecord { GrainReference = partitionKey, GrainType = rowKey };
try
{
ConvertToStorageFormat(grainState.State, record);
await WriteStateInternal(grainState, record);
}
catch (ConditionalCheckFailedException exc)
{
throw new InconsistentStateException("Invalid grain state", exc);
}
catch (Exception exc)
{
this.logger.Error(ErrorCode.StorageProviderBase,
string.Format("Error Writing: GrainType={0} Grainid={1} ETag={2} to Table={3} Exception={4}",
grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc);
throw;
}
}
private async Task WriteStateInternal(IGrainState grainState, GrainStateRecord record, bool clear = false)
{
var fields = new Dictionary<string, AttributeValue>();
if (this.options.TimeToLive.HasValue)
{
fields.Add(GRAIN_TTL_PROPERTY_NAME, new AttributeValue { N = ((DateTimeOffset)DateTime.UtcNow.Add(this.options.TimeToLive.Value)).ToUnixTimeSeconds().ToString() });
}
if (record.BinaryState != null && record.BinaryState.Length > 0)
{
fields.Add(BINARY_STATE_PROPERTY_NAME, new AttributeValue { B = new MemoryStream(record.BinaryState) });
}
else if (!string.IsNullOrWhiteSpace(record.StringState))
{
fields.Add(STRING_STATE_PROPERTY_NAME, new AttributeValue(record.StringState));
}
int newEtag = 0;
if (clear)
{
fields.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference));
fields.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType));
int currentEtag = 0;
int.TryParse(grainState.ETag, out currentEtag);
newEtag = currentEtag;
fields.Add(ETAG_PROPERTY_NAME, new AttributeValue { N = newEtag++.ToString() });
await this.storage.PutEntryAsync(this.options.TableName, fields).ConfigureAwait(false);
}
else if (string.IsNullOrWhiteSpace(grainState.ETag))
{
fields.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference));
fields.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType));
fields.Add(ETAG_PROPERTY_NAME, new AttributeValue { N = "0" });
var expression = $"attribute_not_exists({GRAIN_REFERENCE_PROPERTY_NAME}) AND attribute_not_exists({GRAIN_TYPE_PROPERTY_NAME})";
await this.storage.PutEntryAsync(this.options.TableName, fields, expression).ConfigureAwait(false);
}
else
{
var keys = new Dictionary<string, AttributeValue>();
keys.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference));
keys.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType));
int currentEtag = 0;
int.TryParse(grainState.ETag, out currentEtag);
newEtag = currentEtag;
newEtag++;
fields.Add(ETAG_PROPERTY_NAME, new AttributeValue { N = newEtag.ToString() });
var conditionalValues = new Dictionary<string, AttributeValue> { { CURRENT_ETAG_ALIAS, new AttributeValue { N = currentEtag.ToString() } } };
var expression = $"{ETAG_PROPERTY_NAME} = {CURRENT_ETAG_ALIAS}";
await this.storage.UpsertEntryAsync(this.options.TableName, keys, fields, expression, conditionalValues).ConfigureAwait(false);
}
grainState.ETag = newEtag.ToString();
grainState.RecordExists = !clear;
}
/// <summary> Clear / Delete state data function for this storage provider. </summary>
/// <remarks>
/// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row
/// for this grain will be deleted / removed, otherwise the table row will be
/// cleared by overwriting with default / null values.
/// </remarks>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
if (this.storage == null) throw new ArgumentException("GrainState-Table property not initialized");
string partitionKey = GetKeyString(grainReference);
if (this.logger.IsEnabled(LogLevel.Trace))
{
this.logger.Trace(ErrorCode.StorageProviderBase,
"Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}",
grainType, partitionKey, grainReference, grainState.ETag, this.options.DeleteStateOnClear, this.options.TableName);
}
string rowKey = AWSUtils.ValidateDynamoDBRowKey(grainType);
var record = new GrainStateRecord { GrainReference = partitionKey, ETag = string.IsNullOrWhiteSpace(grainState.ETag) ? 0 : int.Parse(grainState.ETag), GrainType = rowKey };
var operation = "Clearing";
try
{
if (this.options.DeleteStateOnClear)
{
operation = "Deleting";
var keys = new Dictionary<string, AttributeValue>();
keys.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference));
keys.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType));
await this.storage.DeleteEntryAsync(this.options.TableName, keys).ConfigureAwait(false);
grainState.ETag = string.Empty;
}
else
{
await WriteStateInternal(grainState, record, true);
}
}
catch (Exception exc)
{
this.logger.Error(ErrorCode.StorageProviderBase, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}",
operation, grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc);
throw;
}
}
internal class GrainStateRecord
{
public string GrainReference { get; set; } = "";
public string GrainType { get; set; } = "";
public byte[] BinaryState { get; set; }
public string StringState { get; set; }
public int ETag { get; set; }
}
private string GetKeyString(GrainReference grainReference)
{
var key = string.Format("{0}_{1}", this.options.ServiceId, this.grainReferenceConverter.ToKeyString(grainReference));
return AWSUtils.ValidateDynamoDBPartitionKey(key);
}
internal object ConvertFromStorageFormat(GrainStateRecord entity, Type stateType)
{
var binaryData = entity.BinaryState;
var stringData = entity.StringState;
object dataValue = null;
try
{
if (binaryData?.Length > 0)
{
// Rehydrate
dataValue = this.serializationManager.DeserializeFromByteArray<object>(binaryData);
}
else if (!string.IsNullOrEmpty(stringData))
{
dataValue = JsonConvert.DeserializeObject(stringData, stateType, this.jsonSettings);
}
// Else, no data found
}
catch (Exception exc)
{
var sb = new StringBuilder();
if (binaryData?.Length > 0)
{
sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData);
}
else if (!string.IsNullOrEmpty(stringData))
{
sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData);
}
if (dataValue != null)
{
sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType());
}
this.logger.Error(0, sb.ToString(), exc);
throw new AggregateException(sb.ToString(), exc);
}
return dataValue;
}
internal void ConvertToStorageFormat(object grainState, GrainStateRecord entity)
{
int dataSize;
if (this.options.UseJson)
{
// http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm
entity.StringState = JsonConvert.SerializeObject(grainState, this.jsonSettings);
dataSize = STRING_STATE_PROPERTY_NAME.Length + entity.StringState.Length;
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}",
dataSize, entity.GrainReference, entity.GrainType);
}
else
{
// Convert to binary format
entity.BinaryState = this.serializationManager.SerializeToByteArray(grainState);
dataSize = BINARY_STATE_PROPERTY_NAME.Length + entity.BinaryState.Length;
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("Writing binary data size = {0} for grain id = Partition={1} / Row={2}",
dataSize, entity.GrainReference, entity.GrainType);
}
var pkSize = GRAIN_REFERENCE_PROPERTY_NAME.Length + entity.GrainReference.Length;
var rkSize = GRAIN_TYPE_PROPERTY_NAME.Length + entity.GrainType.Length;
var versionSize = ETAG_PROPERTY_NAME.Length + entity.ETag.ToString().Length;
if ((pkSize + rkSize + versionSize + dataSize) > MAX_DATA_SIZE)
{
var msg = string.Format("Data too large to write to DynamoDB table. Size={0} MaxSize={1}", dataSize, MAX_DATA_SIZE);
throw new ArgumentOutOfRangeException("GrainState.Size", msg);
}
}
}
public static class DynamoDBGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<DynamoDBStorageOptions>>();
return ActivatorUtilities.CreateInstance<DynamoDBGrainStorage>(services, optionsMonitor.Get(name), name);
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org 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.IO;
using System.Collections.Generic;
using System.Reflection;
// The common elements shared between rendering plugins are defined here
namespace OpenMetaverse.Rendering
{
#region Enums
public enum FaceType : ushort
{
PathBegin = 0x1 << 0,
PathEnd = 0x1 << 1,
InnerSide = 0x1 << 2,
ProfileBegin = 0x1 << 3,
ProfileEnd = 0x1 << 4,
OuterSide0 = 0x1 << 5,
OuterSide1 = 0x1 << 6,
OuterSide2 = 0x1 << 7,
OuterSide3 = 0x1 << 8
}
[Flags]
public enum FaceMask
{
Single = 0x0001,
Cap = 0x0002,
End = 0x0004,
Side = 0x0008,
Inner = 0x0010,
Outer = 0x0020,
Hollow = 0x0040,
Open = 0x0080,
Flat = 0x0100,
Top = 0x0200,
Bottom = 0x0400
}
public enum DetailLevel
{
Low = 0,
Medium = 1,
High = 2,
Highest = 3
}
#endregion Enums
#region Structs
public struct Vertex
{
public Vector3 Position;
public Vector3 Normal;
public Vector3 Binormal;
public Vector2 TexCoord;
public override string ToString()
{
return String.Format("P: {0} N: {1} B: {2} T: {3}", Position, Normal, Binormal, TexCoord);
}
}
public struct ProfileFace
{
public int Index;
public int Count;
public float ScaleU;
public bool Cap;
public bool Flat;
public FaceType Type;
public override string ToString()
{
return Type.ToString();
}
};
public struct Profile
{
public float MinX;
public float MaxX;
public bool Open;
public bool Concave;
public int TotalOutsidePoints;
public List<Vector3> Positions;
public List<ProfileFace> Faces;
}
public struct PathPoint
{
public Vector3 Position;
public Vector2 Scale;
public Quaternion Rotation;
public float TexT;
}
public struct Path
{
public List<PathPoint> Points;
public bool Open;
}
public struct Face
{
// Only used for Inner/Outer faces
public int BeginS;
public int BeginT;
public int NumS;
public int NumT;
public int ID;
public Vector3 Center;
public Vector3 MinExtent;
public Vector3 MaxExtent;
public List<Vertex> Vertices;
public List<ushort> Indices;
public List<int> Edge;
public FaceMask Mask;
public Primitive.TextureEntryFace TextureFace;
public object UserData;
public override string ToString()
{
return Mask.ToString();
}
}
#endregion Structs
#region Exceptions
public class RenderingException : Exception
{
public RenderingException(string message)
: base(message)
{
}
public RenderingException(string message, Exception innerException)
: base(message, innerException)
{
}
}
#endregion Exceptions
#region Mesh Classes
public class Mesh
{
public Primitive Prim;
public Path Path;
public Profile Profile;
public override string ToString()
{
if (!String.IsNullOrEmpty(Prim.Properties.Name))
{
return Prim.Properties.Name;
}
else
{
return String.Format("{0} ({1})", Prim.LocalID, Prim.PrimData);
}
}
}
public class FacetedMesh : Mesh
{
public List<Face> Faces;
}
public class SimpleMesh : Mesh
{
public List<Vertex> Vertices;
public List<ushort> Indices;
}
#endregion Mesh Classes
#region Plugin Loading
public static class RenderingLoader
{
public static List<string> ListRenderers(string path)
{
List<string> plugins = new List<string>();
string[] files = Directory.GetFiles(path, "OpenMetaverse.Rendering.*.dll");
foreach (string f in files)
{
try
{
Assembly a = Assembly.LoadFrom(f);
System.Type[] types = a.GetTypes();
foreach (System.Type type in types)
{
if (type.GetInterface("IRendering") != null)
{
if (type.GetCustomAttributes(typeof(RendererNameAttribute), false).Length == 1)
{
plugins.Add(f);
}
else
{
Logger.Log("Rendering plugin does not support the [RendererName] attribute: " + f,
Helpers.LogLevel.Warning);
}
break;
}
}
}
catch (Exception e)
{
Logger.Log(String.Format("Unrecognized rendering plugin {0}: {1}", f, e.Message),
Helpers.LogLevel.Warning, e);
}
}
return plugins;
}
public static IRendering LoadRenderer(string filename)
{
try
{
Assembly a = Assembly.LoadFrom(filename);
System.Type[] types = a.GetTypes();
foreach (System.Type type in types)
{
if (type.GetInterface("IRendering") != null)
{
if (type.GetCustomAttributes(typeof(RendererNameAttribute), false).Length == 1)
{
return (IRendering)Activator.CreateInstance(type);
}
else
{
throw new RenderingException(
"Rendering plugin does not support the [RendererName] attribute");
}
}
}
throw new RenderingException(
"Rendering plugin does not support the IRendering interface");
}
catch (Exception e)
{
throw new RenderingException("Failed loading rendering plugin: " + e.Message, e);
}
}
}
#endregion Plugin Loading
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.BackEnd.SdkResolution;
using Microsoft.Build.Collections;
using Microsoft.Build.Engine.UnitTests.BackEnd;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Xunit;
using ElementLocation = Microsoft.Build.Construction.ElementLocation;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// Test for the TargetEntry class used by the TargetBuilder. This class does most of the
/// actual work to build a target.
/// </summary>
public class TargetEntry_Tests : ITargetBuilderCallback, IDisposable
{
/// <summary>
/// The component host.
/// </summary>
private MockHost _host;
/// <summary>
/// The node request id counter
/// </summary>
private int _nodeRequestId;
#pragma warning disable xUnit1013
/// <summary>
/// Handles exceptions from the logging system.
/// </summary>
/// <param name="e">The exception</param>
public void LoggingException(Exception e)
{
}
#pragma warning restore xUnit1013
/// <summary>
/// Called prior to each test.
/// </summary>
public TargetEntry_Tests()
{
_nodeRequestId = 1;
_host = new MockHost();
_host.OnLoggingThreadException += this.LoggingException;
}
/// <summary>
/// Called after each test is run.
/// </summary>
public void Dispose()
{
File.Delete("testProject.proj");
_host = null;
}
/// <summary>
/// Tests a constructor with a null target.
/// </summary>
[Fact]
public void TestConstructorNullTarget()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance project = CreateTestProject(true /* Returns enabled */);
BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null), "2.0");
BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config);
Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(project.Items), new PropertyDictionary<ProjectPropertyInstance>(project.Properties));
TargetEntry entry = new TargetEntry(requestEntry, this, null, lookup, null, TargetBuiltReason.None, _host, false);
}
);
}
/// <summary>
/// Tests a constructor with a null lookup.
/// </summary>
[Fact]
public void TestConstructorNullLookup()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance project = CreateTestProject(true /* Returns enabled */);
BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null), "2.0");
BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config);
TargetEntry entry = new TargetEntry(requestEntry, this, new TargetSpecification("Empty", null), null, null, TargetBuiltReason.None, _host, false);
}
);
}
/// <summary>
/// Tests a constructor with a null host.
/// </summary>
[Fact]
public void TestConstructorNullHost()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectInstance project = CreateTestProject(true /* Returns enabled */);
BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null), "2.0");
BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config);
Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(project.Items), new PropertyDictionary<ProjectPropertyInstance>(project.Properties));
TargetEntry entry = new TargetEntry(requestEntry, this, new TargetSpecification("Empty", null), lookup, null, TargetBuiltReason.None, null, false);
}
);
}
/// <summary>
/// Tests a valid constructor call.
/// </summary>
[Fact]
public void TestConstructorValid()
{
ProjectInstance project = CreateTestProject(true /* Returns enabled */);
TargetEntry entry = CreateStandardTargetEntry(project, "Empty");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
}
/// <summary>
/// Tests incorrect invocation of ExecuteTarget
/// </summary>
[Fact]
public void TestInvalidState_Execution()
{
Assert.Throws<InternalErrorException>(() =>
{
ProjectInstance project = CreateTestProject(true /* Returns enabled */);
TargetEntry entry = CreateStandardTargetEntry(project, "Empty");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
ExecuteEntry(project, entry);
}
);
}
/// <summary>
/// Tests incorrect invocation of GatherResults.
/// </summary>
[Fact]
public void TestInvalidState_Completed()
{
Assert.Throws<InternalErrorException>(() =>
{
ProjectInstance project = CreateTestProject(true /* Returns enabled */);
TargetEntry entry = CreateStandardTargetEntry(project, "Empty");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
entry.GatherResults();
}
);
}
/// <summary>
/// Verifies that the dependencies specified for a target are returned by the GetDependencies call.
/// </summary>
[Fact]
public void TestDependencies()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
TargetEntry entry = CreateStandardTargetEntry(project, "Empty");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
Assert.Empty(deps);
entry = CreateStandardTargetEntry(project, "Baz");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
Assert.Single(deps);
IEnumerator<TargetSpecification> depsEnum = deps.GetEnumerator();
depsEnum.MoveNext();
Assert.Equal("Bar", depsEnum.Current.TargetName);
entry = CreateStandardTargetEntry(project, "Baz2");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
Assert.Equal(2, deps.Count);
depsEnum = deps.GetEnumerator();
depsEnum.MoveNext();
Assert.Equal("Bar", depsEnum.Current.TargetName);
depsEnum.MoveNext();
Assert.Equal("Foo", depsEnum.Current.TargetName);
}
}
/// <summary>
/// Tests normal target execution and verifies the tasks expected to be executed are.
/// </summary>
[Fact]
public void TestExecution()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
taskBuilder.Reset();
TargetEntry entry = CreateStandardTargetEntry(project, "Empty");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
ExecuteEntry(project, entry);
Assert.Empty(taskBuilder.ExecutedTasks);
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Baz");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
ExecuteEntry(project, entry);
Assert.Equal(2, taskBuilder.ExecutedTasks.Count);
Assert.Equal("BazTask1", taskBuilder.ExecutedTasks[0].Name);
Assert.Equal("BazTask2", taskBuilder.ExecutedTasks[1].Name);
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Baz2");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
ExecuteEntry(project, entry);
Assert.Equal(3, taskBuilder.ExecutedTasks.Count);
Assert.Equal("Baz2Task1", taskBuilder.ExecutedTasks[0].Name);
Assert.Equal("Baz2Task2", taskBuilder.ExecutedTasks[1].Name);
Assert.Equal("Baz2Task3", taskBuilder.ExecutedTasks[2].Name);
}
}
/// <summary>
/// Executes various cases where tasks cause an error. Verifies that the expected tasks
/// executed.
/// </summary>
[Fact]
public void TestExecutionWithErrors()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
taskBuilder.Reset();
TargetEntry entry = CreateStandardTargetEntry(project, "Error");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
taskBuilder.FailTaskNumber = 1;
ExecuteEntry(project, entry);
Assert.Equal(3, taskBuilder.ExecutedTasks.Count);
Assert.Equal("ErrorTask1", taskBuilder.ExecutedTasks[0].Name);
Assert.Equal("ErrorTask2", taskBuilder.ExecutedTasks[1].Name);
Assert.Equal("ErrorTask3", taskBuilder.ExecutedTasks[2].Name);
Assert.Equal(TargetEntryState.Completed, entry.State);
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Error");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
taskBuilder.FailTaskNumber = 2;
ExecuteEntry(project, entry);
Assert.Equal(2, taskBuilder.ExecutedTasks.Count);
Assert.Equal("ErrorTask1", taskBuilder.ExecutedTasks[0].Name);
Assert.Equal("ErrorTask2", taskBuilder.ExecutedTasks[1].Name);
Assert.Equal(TargetEntryState.ErrorExecution, entry.State);
Assert.Equal(2, entry.GetErrorTargets(GetProjectLoggingContext(entry.RequestEntry)).Count);
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Error");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
taskBuilder.FailTaskNumber = 3;
ExecuteEntry(project, entry);
Assert.Equal(3, taskBuilder.ExecutedTasks.Count);
Assert.Equal("ErrorTask1", taskBuilder.ExecutedTasks[0].Name);
Assert.Equal("ErrorTask2", taskBuilder.ExecutedTasks[1].Name);
Assert.Equal("ErrorTask3", taskBuilder.ExecutedTasks[2].Name);
Assert.Equal(TargetEntryState.ErrorExecution, entry.State);
Assert.Equal(2, entry.GetErrorTargets(GetProjectLoggingContext(entry.RequestEntry)).Count);
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Error");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
ExecuteEntry(project, entry);
Assert.Equal(3, taskBuilder.ExecutedTasks.Count);
Assert.Equal("ErrorTask1", taskBuilder.ExecutedTasks[0].Name);
Assert.Equal("ErrorTask2", taskBuilder.ExecutedTasks[1].Name);
Assert.Equal("ErrorTask3", taskBuilder.ExecutedTasks[2].Name);
Assert.Equal(TargetEntryState.Completed, entry.State);
}
}
/// <summary>
/// Tests that the dependencies returned can also be built and that their entries in the lookup
/// are appropriately aggregated into the parent target entry.
/// </summary>
[Fact]
public void TestBuildDependencies()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
// Empty target doesn't produce any items of its own, the Compile items should be in it.
TargetEntry entry = CreateStandardTargetEntry(project, "Baz2");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
foreach (TargetSpecification target in deps)
{
TargetEntry depEntry = CreateStandardTargetEntry(project, target.TargetName, entry);
depEntry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, depEntry);
depEntry.GatherResults();
}
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.Completed, entry.State);
Assert.Equal(2, entry.Lookup.GetItems("Compile").Count);
Assert.Single(entry.Lookup.GetItems("FooTask1_Item"));
Assert.Single(entry.Lookup.GetItems("BarTask1_Item"));
}
}
/// <summary>
/// Tests a variety of situations returning various results
/// </summary>
[Fact]
public void TestGatherResults()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
// Empty target doesn't produce any items of its own, the Compile items should be in it.
// This target has no outputs.
TargetEntry entry = CreateStandardTargetEntry(project, "Empty");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.Completed, entry.State);
TargetResult results = entry.GatherResults();
Assert.Equal(2, entry.Lookup.GetItems("Compile").Count);
Assert.Empty(results.Items);
Assert.Equal(TargetResultCode.Success, results.ResultCode);
// Foo produces one item of its own and has an output
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Foo");
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.Completed, entry.State);
results = entry.GatherResults();
Assert.Equal(2, entry.Lookup.GetItems("Compile").Count);
Assert.Single(entry.Lookup.GetItems("FooTask1_Item"));
if (returnsEnabledForThisProject)
{
// If returns are enabled, since this is a target with "Outputs", they won't
// be returned.
Assert.Empty(results.Items);
}
else
{
Assert.Single(results.Items);
Assert.Equal("foo.o", results.Items[0].ItemSpec);
}
Assert.Equal(TargetResultCode.Success, results.ResultCode);
// Skip produces outputs but is up to date, so should record success
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Skip");
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.Completed, entry.State);
results = entry.GatherResults();
if (returnsEnabledForThisProject)
{
Assert.Empty(results.Items);
}
else
{
Assert.Single(results.Items);
Assert.Equal("testProject.proj", results.Items[0].ItemSpec);
}
Assert.Equal(TargetResultCode.Success, results.ResultCode);
// SkipCondition is skipped due to condition.
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "SkipCondition");
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Completed, entry.State);
results = entry.GatherResults();
Assert.Equal(TargetResultCode.Skipped, results.ResultCode);
// DepSkip produces no outputs and calls Empty and Skip. The result should be success
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "DepSkip");
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.Completed, entry.State);
results = entry.GatherResults();
Assert.Equal(TargetResultCode.Success, results.ResultCode);
// DepSkip2 calls Skip. The result should be success because both DepSkip and Skip are up-to-date.
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "DepSkip2");
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.Completed, entry.State);
results = entry.GatherResults();
Assert.Equal(TargetResultCode.Success, results.ResultCode);
// Error target should produce error results
taskBuilder.Reset();
entry = CreateStandardTargetEntry(project, "Error");
Assert.Equal(TargetEntryState.Dependencies, entry.State);
deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
Assert.Equal(TargetEntryState.Execution, entry.State);
taskBuilder.FailTaskNumber = 2;
ExecuteEntry(project, entry);
Assert.Equal(TargetEntryState.ErrorExecution, entry.State);
entry.GetErrorTargets(GetProjectLoggingContext(entry.RequestEntry));
results = entry.GatherResults();
Assert.Equal(TargetResultCode.Failure, results.ResultCode);
}
}
/// <summary>
/// Tests that multiple outputs are allowed
/// </summary>
[Fact]
public void TestMultipleOutputs()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "MultipleOutputsNoReturns");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
if (returnsEnabledForThisProject)
{
// If returns are enabled, since this is a target with "Outputs", they won't
// be returned.
Assert.Empty(results.Items);
}
else
{
Assert.Equal(2, results.Items.Length);
}
}
}
/// <summary>
/// Tests that multiple return values are still passed through, even when there is no Outputs specified.
/// </summary>
[Fact]
public void TestMultipleReturnsNoOutputs()
{
ProjectInstance project = CreateTestProject(true /* returns are enabled */);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "MultipleReturnsNoOutputs");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Equal(3, results.Items.Length);
}
/// <summary>
/// Tests that multiple return values are still passed through, and verifies that when both Outputs and Returns
/// are specified, Returns is what controls the return value of the target.
/// </summary>
[Fact]
public void TestMultipleReturnsWithOutputs()
{
ProjectInstance project = CreateTestProject(true /* returns are enabled */);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "MultipleReturnsWithOutputs");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Equal(3, results.Items.Length);
}
/// <summary>
/// Tests that duplicate outputs are allowed
/// </summary>
[Fact]
public void TestDuplicateOutputs()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "DupeOutputs");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Single(results.Items);
}
}
/// <summary>
/// Tests that duplicate outputs are not trimmed under the false trim condition
/// </summary>
[Fact]
public void TestKeepDuplicateOutputsTrue()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "DupeOutputsKeep");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Equal(2, results.Items.Length);
}
}
/// <summary>
/// Tests that duplicate outputs are trimmed under the false keep condition
/// </summary>
[Fact]
public void TestKeepDuplicateOutputsFalse()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "DupeOutputsNoKeep");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Single(results.Items);
}
}
/// <summary>
/// Tests that duplicate outputs are trimmed if they have the same metadata
/// </summary>
[Fact]
public void TestKeepDuplicateOutputsSameMetadata()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "DupeOutputsSameMetadata");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Single(results.Items);
}
}
/// <summary>
/// Tests that duplicate outputs are not trimmed if they have different metadata
/// </summary>
[Fact]
public void TestKeepDuplicateOutputsDiffMetadata()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
ProjectInstance project = CreateTestProject(returnsEnabledForThisProject);
MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder);
TargetEntry entry = CreateStandardTargetEntry(project, "DupeOutputsDiffMetadata");
ICollection<TargetSpecification> deps = entry.GetDependencies(GetProjectLoggingContext(entry.RequestEntry));
ExecuteEntry(project, entry);
TargetResult results = entry.GatherResults();
Assert.Equal(4, results.Items.Length);
}
}
/// <summary>
/// Tests that metadata references in target outputs are correctly expanded
/// </summary>
[Fact]
public void TestMetadataReferenceInTargetOutputs()
{
bool[] returnsEnabled = new bool[] { true, false };
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
string content = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<SomeItem1 Include=`item1.cs`/>
<SomeItem2 Include=`item2.cs`/>
</ItemGroup>
<Target Name=`a`>
<CallTarget Targets=`b;c`>
<Output TaskParameter=`TargetOutputs` PropertyName=`foo`/>
</CallTarget>
<Message Text=`[$(foo)]`/>
</Target>
<Target Name=`b` Outputs=`%(SomeItem1.Filename)`/>
<Target Name=`c` " + (returnsEnabledForThisProject ? "Returns" : "Outputs") + @"=`%(SomeItem2.Filename)`/>
</Project>
";
MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content);
if (returnsEnabledForThisProject)
{
log.AssertLogContains("item2");
log.AssertLogDoesntContain("item1;item2");
}
else
{
log.AssertLogContains("item1;item2");
}
}
}
/// <summary>
/// Tests that we get the target outputs correctly.
/// </summary>
[Fact]
public void TestTargetOutputsOnFinishedEvent()
{
bool[] returnsEnabled = new bool[] { false, true };
string loggingVariable = Environment.GetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING");
Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", "1");
try
{
TargetLoggingContext.EnableTargetOutputLogging = true;
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
string content = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<SomeItem1 Include=`item1.cs`/>
<SomeItem2 Include=`item2.cs`/>
</ItemGroup>
<Target Name=`a`>
<CallTarget Targets=`b;c`>
<Output TaskParameter=`TargetOutputs` PropertyName=`foo`/>
</CallTarget>
<Message Text=`[$(foo)]`/>
</Target>
<Target Name=`b` " + (returnsEnabledForThisProject ? "Returns" : "Outputs") + @"=`%(SomeItem1.Filename)`/>
<Target Name=`c` Outputs=`%(SomeItem2.Filename)`/>
</Project>
";
// Only log critical event is false by default
MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content);
Assert.Equal(3, log.TargetFinishedEvents.Count);
TargetFinishedEventArgs targeta = log.TargetFinishedEvents[2];
TargetFinishedEventArgs targetb = log.TargetFinishedEvents[0];
TargetFinishedEventArgs targetc = log.TargetFinishedEvents[1];
Assert.NotNull(targeta);
Assert.NotNull(targetb);
Assert.NotNull(targetc);
Assert.Equal("a", targeta.TargetName);
Assert.Equal("b", targetb.TargetName);
Assert.Equal("c", targetc.TargetName);
IEnumerable targetOutputsA = targeta.TargetOutputs;
IEnumerable targetOutputsB = targetb.TargetOutputs;
IEnumerable targetOutputsC = targetc.TargetOutputs;
Assert.Null(targetOutputsA);
Assert.NotNull(targetOutputsB);
if (returnsEnabledForThisProject)
{
Assert.Null(targetOutputsC);
}
else
{
Assert.NotNull(targetOutputsC);
}
List<ITaskItem> outputListB = new List<ITaskItem>();
foreach (ITaskItem item in targetOutputsB)
{
outputListB.Add(item);
}
Assert.Single(outputListB);
Assert.Equal("item1", outputListB[0].ItemSpec);
if (!returnsEnabledForThisProject)
{
List<ITaskItem> outputListC = new List<ITaskItem>();
foreach (ITaskItem item in targetOutputsC)
{
outputListC.Add(item);
}
Assert.Single(outputListC);
Assert.Equal("item2", outputListC[0].ItemSpec);
}
}
}
finally
{
TargetLoggingContext.EnableTargetOutputLogging = false;
Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", loggingVariable);
}
}
/// <summary>
/// Tests that we get no target outputs when the environment variable is not set
/// </summary>
[Fact]
public void TestTargetOutputsOnFinishedEventNoVariableSet()
{
bool[] returnsEnabled = new bool[] { true, false };
string loggingVariable = Environment.GetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING");
Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", null);
bool originalTargetOutputLoggingValue = TargetLoggingContext.EnableTargetOutputLogging;
TargetLoggingContext.EnableTargetOutputLogging = false;
try
{
foreach (bool returnsEnabledForThisProject in returnsEnabled)
{
string content = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<SomeItem1 Include=`item1.cs`/>
<SomeItem2 Include=`item2.cs`/>
</ItemGroup>
<Target Name=`a`>
<CallTarget Targets=`b;c`>
<Output TaskParameter=`TargetOutputs` PropertyName=`foo`/>
</CallTarget>
<Message Text=`[$(foo)]`/>
</Target>
<Target Name=`b` Outputs=`%(SomeItem1.Filename)`/>
<Target Name=`c` " + (returnsEnabledForThisProject ? "Returns" : "Outputs") + @"=`%(SomeItem2.Filename)`/>
</Project>
";
// Only log critical event is false by default
MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content);
Assert.Equal(3, log.TargetFinishedEvents.Count);
TargetFinishedEventArgs targeta = log.TargetFinishedEvents[2];
TargetFinishedEventArgs targetb = log.TargetFinishedEvents[0];
TargetFinishedEventArgs targetc = log.TargetFinishedEvents[1];
Assert.NotNull(targeta);
Assert.NotNull(targetb);
Assert.NotNull(targetc);
Assert.Equal("a", targeta.TargetName);
Assert.Equal("b", targetb.TargetName);
Assert.Equal("c", targetc.TargetName);
IEnumerable targetOutputsA = targeta.TargetOutputs;
IEnumerable targetOutputsB = targetb.TargetOutputs;
IEnumerable targetOutputsC = targetc.TargetOutputs;
Assert.Null(targetOutputsA);
Assert.Null(targetOutputsB);
Assert.Null(targetOutputsC);
}
}
finally
{
TargetLoggingContext.EnableTargetOutputLogging = originalTargetOutputLoggingValue;
Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", loggingVariable);
}
}
/// <summary>
/// Make sure that if an after target fails that the build result is reported as failed.
/// </summary>
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")]
public void AfterTargetsShouldReportFailedBuild()
{
// Since we're creating our own BuildManager, we need to make sure that the default
// one has properly relinquished the inproc node
NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)BuildManager.DefaultBuildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc;
if (nodeProviderInProc != null)
{
nodeProviderInProc.Dispose();
}
string content = @"
<Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='Build'>
<Message Text='Hello'/>
</Target>
<Target Name='Boo' AfterTargets='build'>
<Error Text='Hi in Boo'/>
</Target>
</Project>
";
BuildManager manager = null;
try
{
MockLogger logger = new MockLogger();
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
ProjectCollection collection = new ProjectCollection();
Project project = new Project(
XmlReader.Create(new StringReader(content)),
(IDictionary<string, string>)null,
ObjectModelHelpers.MSBuildDefaultToolsVersion,
collection)
{ FullPath = FileUtilities.GetTemporaryFile() };
project.Save();
File.Delete(project.FullPath);
BuildParameters parameters = new BuildParameters(collection)
{
Loggers = loggers,
ShutdownInProcNodeOnBuildFinish = true
};
BuildRequestData data = new BuildRequestData(
project.FullPath,
new Dictionary<string, string>(),
ObjectModelHelpers.MSBuildDefaultToolsVersion,
new string[] { },
null);
manager = new BuildManager();
BuildResult result = manager.Build(parameters, data);
// Make sure the overall result is failed
Assert.Equal(BuildResultCode.Failure, result.OverallResult);
// Expect the build target to pass
Assert.Equal(TargetResultCode.Success, result.ResultsByTarget["Build"].ResultCode);
}
finally
{
// and we should clean up after ourselves, too.
if (manager != null)
{
NodeProviderInProc inProcNodeProvider = ((IBuildComponentHost)manager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc;
if (inProcNodeProvider != null)
{
inProcNodeProvider.Dispose();
}
}
}
}
/// <summary>
/// Tests that with an invalid target specification (inputs but no outputs) we
/// still raise the TargetFinished event.
/// </summary>
[Fact]
public void TestTargetFinishedRaisedOnInvalidTarget()
{
string content = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`OnlyInputs` Inputs=`foo`>
<Message Text=`This is an invalid target -- this text should never show.` />
</Target>
</Project>
";
// Only log critical event is false by default
MockLogger log = Helpers.BuildProjectWithNewOMExpectFailure(content, allowTaskCrash: true);
Assert.Single(log.TargetFinishedEvents);
}
#region ITargetBuilderCallback Members
/// <summary>
/// Empty impl
/// </summary>
Task<ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation referenceLocation)
{
throw new NotImplementedException();
}
#endregion
#region IRequestBuilderCallback Members
/// <summary>
/// Empty impl
/// </summary>
Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets)
{
throw new NotImplementedException();
}
/// <summary>
/// Not implemented.
/// </summary>
Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult)
{
throw new NotImplementedException();
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.Yield()
{
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.Reacquire()
{
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.EnterMSBuildCallbackState()
{
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.ExitMSBuildCallbackState()
{
}
#endregion
/// <summary>
/// Executes the specified entry with the specified project.
/// </summary>
private void ExecuteEntry(ProjectInstance project, TargetEntry entry)
{
ITaskBuilder taskBuilder = _host.GetComponent(BuildComponentType.TaskBuilder) as ITaskBuilder;
// GetAwaiter().GetResult() will flatten any AggregateException throw by the task.
entry.ExecuteTarget(taskBuilder, entry.RequestEntry, GetProjectLoggingContext(entry.RequestEntry), CancellationToken.None).GetAwaiter().GetResult();
((IBuildComponent)taskBuilder).ShutdownComponent();
}
/// <summary>
/// Creates a new build request
/// </summary>
private BuildRequest CreateNewBuildRequest(int configurationId, string[] targets)
{
return new BuildRequest(1 /* submissionId */, _nodeRequestId++, configurationId, targets, null, BuildEventContext.Invalid, null);
}
/// <summary>
/// Creates a TargetEntry from a project and the specified target name.
/// </summary>
/// <param name="project">The project object.</param>
/// <param name="targetName">The name of a target within the specified project.</param>
/// <returns>The new target entry</returns>
private TargetEntry CreateStandardTargetEntry(ProjectInstance project, string targetName)
{
BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null), "2.0");
config.Project = project;
BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config);
Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(project.Items), new PropertyDictionary<ProjectPropertyInstance>(project.Properties));
TargetEntry entry = new TargetEntry(requestEntry, this, new TargetSpecification(targetName, project.Targets[targetName].Location), lookup, null, TargetBuiltReason.None, _host, false);
return entry;
}
/// <summary>
/// Creates a target entry object.
/// </summary>
/// <param name="project">The project object</param>
/// <param name="target">The target object</param>
/// <param name="baseEntry">The parent entry.</param>
/// <returns>The new target entry</returns>
private TargetEntry CreateStandardTargetEntry(ProjectInstance project, string target, TargetEntry baseEntry)
{
BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null), "2.0");
config.Project = project;
BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[1] { "foo" }), config);
TargetEntry entry = new TargetEntry(requestEntry, this, new TargetSpecification(target, project.Targets[target].Location), baseEntry.Lookup, baseEntry, TargetBuiltReason.None, _host, false);
return entry;
}
/// <summary>
/// Creates the test project
/// </summary>
/// <returns>The project object.</returns>
private ProjectInstance CreateTestProject(bool returnsAttributeEnabled)
{
string returnsAttributeName = returnsAttributeEnabled ? "Returns" : "Outputs";
string projectFileContents = @"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
<Compile Include='b.cs' />
<Compile Include='c.cs' />
</ItemGroup>
<ItemGroup>
<Reference Include='System' />
</ItemGroup>
<ItemGroup>
<DupeOutput Include='foo.cs'/>
<DupeOutput Include='foo.cs'/>
</ItemGroup>
<ItemGroup>
<DupeOutputDiffMetadata Include='foo.cs'>
<x>1</x>
</DupeOutputDiffMetadata>
<DupeOutputDiffMetadata Include='foo.cs'>
<x>2</x>
</DupeOutputDiffMetadata>
<DupeOutputDiffMetadata Include='foo.cs'>
<y>1</y>
</DupeOutputDiffMetadata>
<DupeOutputDiffMetadata Include='foo.cs'>
<y>2</y>
</DupeOutputDiffMetadata>
</ItemGroup>
<ItemGroup>
<DupeOutputsameMetadata Include='foo.cs'>
<x>1</x>
</DupeOutputsameMetadata>
<DupeOutputsameMetadata Include='foo.cs'>
<x>1</x>
</DupeOutputsameMetadata>
</ItemGroup>
<PropertyGroup>
<FalseProp>false</FalseProp>
<TrueProp>true</TrueProp>
</PropertyGroup>
<Target Name='Empty' />
<Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' />
<Target Name='SkipCondition' Condition=""'true' == 'false'"" />
<Target Name='Error' >
<ErrorTask1 ContinueOnError='True'/>
<ErrorTask2 ContinueOnError='False'/>
<ErrorTask3 />
<OnError ExecuteTargets='Foo'/>
<OnError ExecuteTargets='Bar'/>
</Target>
<Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'>
<FooTask1/>
</Target>
<Target Name='Bar'>
<BarTask1/>
</Target>
<Target Name='Baz' DependsOnTargets='Bar'>
<BazTask1/>
<BazTask2/>
</Target>
<Target Name='Baz2' DependsOnTargets='Bar;Foo'>
<Baz2Task1/>
<Baz2Task2/>
<Baz2Task3/>
</Target>
<Target Name='DepSkip' DependsOnTargets='Skip'>
<DepSkipTask1/>
<DepSkipTask2/>
<DepSkipTask3/>
</Target>
<Target Name='DepSkip2' DependsOnTargets='Skip' Inputs='testProject.proj' Outputs='testProject.proj'>
<DepSkipTask1/>
<DepSkipTask2/>
<DepSkipTask3/>
</Target>
<Target Name='MultipleOutputsNoReturns' Inputs='testProject.proj' Outputs='@(Compile)'>
</Target>";
if (returnsAttributeEnabled)
{
projectFileContents += @"
<Target Name='MultipleReturnsWithOutputs' Inputs='testProject.proj' Outputs='@(Compile)' Returns='@(Compile);@(Reference)' />
<Target Name='MultipleReturnsNoOutputs' Returns='@(Compile);@(Reference)' />";
}
projectFileContents += @"
<Target Name='DupeOutputs' " + returnsAttributeName + @"='@(DupeOutput)'>
</Target>
<Target Name='DupeOutputsKeep' KeepDuplicateOutputs='$(TrueProp)' " + returnsAttributeName + @"='@(DupeOutput)'>
</Target>
<Target Name='DupeOutputsNoKeep' KeepDuplicateOutputs='$(FalseProp)' " + returnsAttributeName + @"='@(DupeOutput)'>
</Target>
<Target Name='DupeOutputsSameMetadata' KeepDuplicateOutputs='$(FalseProp)' " + returnsAttributeName + @"='@(DupeOutputsameMetadata)'>
</Target>
<Target Name='DupeOutputsDiffMetadata' KeepDuplicateOutputs='$(FalseProp)' " + returnsAttributeName + @"='@(DupeOutputDiffMetadata)'>
</Target>
</Project>
";
FileStream stream = File.Create("testProject.proj");
stream.Dispose();
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
return project.CreateProjectInstance();
}
/// <summary>
/// Returns a project logging context.
/// </summary>
/// <param name="entry">The build request entry.</param>
/// <returns>The project logging context.</returns>
private ProjectLoggingContext GetProjectLoggingContext(BuildRequestEntry entry)
{
return new ProjectLoggingContext(new NodeLoggingContext(_host, 1, false), entry, null);
}
/// <summary>
/// The mock component host.
/// </summary>
private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent
{
#region IBuildComponentHost Members
/// <summary>
/// The configuration cache.
/// </summary>
private IConfigCache _configCache;
/// <summary>
/// The logging service.
/// </summary>
private ILoggingService _loggingService;
/// <summary>
/// The results cache.
/// </summary>
private IResultsCache _resultsCache;
/// <summary>
/// The request builder.
/// </summary>
private IRequestBuilder _requestBuilder;
/// <summary>
/// The mock task builder
/// </summary>
private ITaskBuilder _taskBuilder;
/// <summary>
/// The build parameters.
/// </summary>
private BuildParameters _buildParameters;
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
private LegacyThreadingData _legacyThreadingData;
private ISdkResolverService _sdkResolverService;
/// <summary>
/// Constructor
/// </summary>
public MockHost()
{
_buildParameters = new BuildParameters();
_legacyThreadingData = new LegacyThreadingData();
_configCache = new ConfigCache();
((IBuildComponent)_configCache).InitializeComponent(this);
_loggingService = this;
_resultsCache = new ResultsCache();
((IBuildComponent)_resultsCache).InitializeComponent(this);
_requestBuilder = new RequestBuilder();
((IBuildComponent)_requestBuilder).InitializeComponent(this);
_taskBuilder = new MockTaskBuilder();
((IBuildComponent)_taskBuilder).InitializeComponent(this);
_sdkResolverService = new MockSdkResolverService();
((IBuildComponent)_sdkResolverService).InitializeComponent(this);
}
/// <summary>
/// Gets the build-specific logging service.
/// </summary>
/// <returns>The logging service</returns>
public ILoggingService LoggingService
{
get
{
return _loggingService;
}
}
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
LegacyThreadingData IBuildComponentHost.LegacyThreadingData
{
get
{
return _legacyThreadingData;
}
}
/// <summary>
/// Retrieves the name of the host.
/// </summary>
public string Name
{
get
{
return "TargetEntry_Tests.MockHost";
}
}
/// <summary>
/// Gets the build parameters.
/// </summary>
public BuildParameters BuildParameters
{
get
{
return _buildParameters;
}
}
/// <summary>
/// Gets the component of the specified type.
/// </summary>
/// <param name="type">The type of component to return.</param>
/// <returns>The component</returns>
public IBuildComponent GetComponent(BuildComponentType type)
{
switch (type)
{
case BuildComponentType.ConfigCache:
return (IBuildComponent)_configCache;
case BuildComponentType.LoggingService:
return (IBuildComponent)_loggingService;
case BuildComponentType.ResultsCache:
return (IBuildComponent)_resultsCache;
case BuildComponentType.RequestBuilder:
return (IBuildComponent)_requestBuilder;
case BuildComponentType.TaskBuilder:
return (IBuildComponent)_taskBuilder;
case BuildComponentType.SdkResolverService:
return (IBuildComponent)_sdkResolverService;
default:
throw new ArgumentException("Unexpected type " + type);
}
}
/// <summary>
/// Register a component factory.
/// </summary>
public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory)
{
}
#endregion
#region IBuildComponent Members
/// <summary>
/// Sets the component host
/// </summary>
/// <param name="host">The component host</param>
public void InitializeComponent(IBuildComponentHost host)
{
throw new NotImplementedException();
}
/// <summary>
/// Shuts down the component
/// </summary>
public void ShutdownComponent()
{
throw new NotImplementedException();
}
#endregion
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for node reports. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
internal partial class DscNodeReportsOperations : IServiceOperations<AutomationManagementClient>, IDscNodeReportsOperations
{
/// <summary>
/// Initializes a new instance of the DscNodeReportsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DscNodeReportsOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieve the Dsc node report data by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The Dsc node id.
/// </param>
/// <param name='reportId'>
/// Required. The report id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get dsc node report operation.
/// </returns>
public async Task<DscNodeReportGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeId", nodeId);
tracingParameters.Add("reportId", reportId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(nodeId.ToString());
url = url + "/reports/";
url = url + Uri.EscapeDataString(reportId.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-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
DscNodeReportGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeReportGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNodeReport nodeReportInstance = new DscNodeReport();
result.NodeReport = nodeReportInstance;
JToken endTimeValue = responseDoc["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
nodeReportInstance.EndTime = endTimeInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
nodeReportInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
nodeReportInstance.StartTime = startTimeInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
nodeReportInstance.Type = typeInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
Guid idInstance = Guid.Parse(((string)idValue));
nodeReportInstance.Id = idInstance;
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
nodeReportInstance.Status = statusInstance;
}
JToken refreshModeValue = responseDoc["refreshMode"];
if (refreshModeValue != null && refreshModeValue.Type != JTokenType.Null)
{
string refreshModeInstance = ((string)refreshModeValue);
nodeReportInstance.RefreshMode = refreshModeInstance;
}
JToken rebootRequestedValue = responseDoc["rebootRequested"];
if (rebootRequestedValue != null && rebootRequestedValue.Type != JTokenType.Null)
{
string rebootRequestedInstance = ((string)rebootRequestedValue);
nodeReportInstance.RebootRequested = rebootRequestedInstance;
}
JToken reportFormatVersionValue = responseDoc["reportFormatVersion"];
if (reportFormatVersionValue != null && reportFormatVersionValue.Type != JTokenType.Null)
{
string reportFormatVersionInstance = ((string)reportFormatVersionValue);
nodeReportInstance.ReportFormatVersion = reportFormatVersionInstance;
}
JToken configurationVersionValue = responseDoc["configurationVersion"];
if (configurationVersionValue != null && configurationVersionValue.Type != JTokenType.Null)
{
string configurationVersionInstance = ((string)configurationVersionValue);
nodeReportInstance.ConfigurationVersion = configurationVersionInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the Dsc node reports by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The Dsc node id.
/// </param>
/// <param name='reportId'>
/// Required. The report id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get node report content operation.
/// </returns>
public async Task<DscNodeReportGetContentResponse> GetContentAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeId", nodeId);
tracingParameters.Add("reportId", reportId);
TracingAdapter.Enter(invocationId, this, "GetContentAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(nodeId.ToString());
url = url + "/reports/";
url = url + Uri.EscapeDataString(reportId.ToString());
url = url + "/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-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
DscNodeReportGetContentResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeReportGetContentResponse();
result.Content = responseContent;
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the Dsc node report list by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public async Task<DscNodeReportListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeReportListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
if (parameters != null && parameters.NodeId != null)
{
url = url + Uri.EscapeDataString(parameters.NodeId.ToString());
}
url = url + "/reports";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.StartTime != null)
{
odataFilter.Add("endTime ge " + Uri.EscapeDataString(parameters.StartTime));
}
if (parameters != null && parameters.EndTime != null)
{
odataFilter.Add("endTime le " + Uri.EscapeDataString(parameters.EndTime));
}
if (parameters != null && parameters.Type != null)
{
odataFilter.Add("type eq '" + Uri.EscapeDataString(parameters.Type) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-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
DscNodeReportListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeReportListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNodeReport dscNodeReportInstance = new DscNodeReport();
result.NodeReports.Add(dscNodeReportInstance);
JToken endTimeValue = valueValue["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
dscNodeReportInstance.EndTime = endTimeInstance;
}
JToken lastModifiedTimeValue = valueValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
dscNodeReportInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken startTimeValue = valueValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
dscNodeReportInstance.StartTime = startTimeInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dscNodeReportInstance.Type = typeInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
Guid idInstance = Guid.Parse(((string)idValue));
dscNodeReportInstance.Id = idInstance;
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
dscNodeReportInstance.Status = statusInstance;
}
JToken refreshModeValue = valueValue["refreshMode"];
if (refreshModeValue != null && refreshModeValue.Type != JTokenType.Null)
{
string refreshModeInstance = ((string)refreshModeValue);
dscNodeReportInstance.RefreshMode = refreshModeInstance;
}
JToken rebootRequestedValue = valueValue["rebootRequested"];
if (rebootRequestedValue != null && rebootRequestedValue.Type != JTokenType.Null)
{
string rebootRequestedInstance = ((string)rebootRequestedValue);
dscNodeReportInstance.RebootRequested = rebootRequestedInstance;
}
JToken reportFormatVersionValue = valueValue["reportFormatVersion"];
if (reportFormatVersionValue != null && reportFormatVersionValue.Type != JTokenType.Null)
{
string reportFormatVersionInstance = ((string)reportFormatVersionValue);
dscNodeReportInstance.ReportFormatVersion = reportFormatVersionInstance;
}
JToken configurationVersionValue = valueValue["configurationVersion"];
if (configurationVersionValue != null && configurationVersionValue.Type != JTokenType.Null)
{
string configurationVersionInstance = ((string)configurationVersionValue);
dscNodeReportInstance.ConfigurationVersion = configurationVersionInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the Dsc node report list by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public async Task<DscNodeReportListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-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
DscNodeReportListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeReportListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNodeReport dscNodeReportInstance = new DscNodeReport();
result.NodeReports.Add(dscNodeReportInstance);
JToken endTimeValue = valueValue["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
dscNodeReportInstance.EndTime = endTimeInstance;
}
JToken lastModifiedTimeValue = valueValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
dscNodeReportInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken startTimeValue = valueValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
dscNodeReportInstance.StartTime = startTimeInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dscNodeReportInstance.Type = typeInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
Guid idInstance = Guid.Parse(((string)idValue));
dscNodeReportInstance.Id = idInstance;
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
dscNodeReportInstance.Status = statusInstance;
}
JToken refreshModeValue = valueValue["refreshMode"];
if (refreshModeValue != null && refreshModeValue.Type != JTokenType.Null)
{
string refreshModeInstance = ((string)refreshModeValue);
dscNodeReportInstance.RefreshMode = refreshModeInstance;
}
JToken rebootRequestedValue = valueValue["rebootRequested"];
if (rebootRequestedValue != null && rebootRequestedValue.Type != JTokenType.Null)
{
string rebootRequestedInstance = ((string)rebootRequestedValue);
dscNodeReportInstance.RebootRequested = rebootRequestedInstance;
}
JToken reportFormatVersionValue = valueValue["reportFormatVersion"];
if (reportFormatVersionValue != null && reportFormatVersionValue.Type != JTokenType.Null)
{
string reportFormatVersionInstance = ((string)reportFormatVersionValue);
dscNodeReportInstance.ReportFormatVersion = reportFormatVersionInstance;
}
JToken configurationVersionValue = valueValue["configurationVersion"];
if (configurationVersionValue != null && configurationVersionValue.Type != JTokenType.Null)
{
string configurationVersionInstance = ((string)configurationVersionValue);
dscNodeReportInstance.ConfigurationVersion = configurationVersionInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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();
}
}
}
}
}
| |
// CodeContracts
//
// 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.
// File System.Linq.ParallelEnumerable.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Linq
{
static public partial class ParallelEnumerable
{
#region Methods and constructors
public static TResult Aggregate<TSource, TAccumulate, TResult>(ParallelQuery<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
return default(TResult);
}
public static TResult Aggregate<TSource, TAccumulate, TResult>(ParallelQuery<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector)
{
return default(TResult);
}
public static TResult Aggregate<TSource, TAccumulate, TResult>(ParallelQuery<TSource> source, Func<TAccumulate> seedFactory, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector)
{
return default(TResult);
}
public static TSource Aggregate<TSource>(ParallelQuery<TSource> source, Func<TSource, TSource, TSource> func)
{
return default(TSource);
}
public static TAccumulate Aggregate<TSource, TAccumulate>(ParallelQuery<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
{
return default(TAccumulate);
}
public static bool All<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(bool);
}
public static bool Any<TSource>(ParallelQuery<TSource> source)
{
return default(bool);
}
public static bool Any<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(bool);
}
public static IEnumerable<TSource> AsEnumerable<TSource>(ParallelQuery<TSource> source)
{
return default(IEnumerable<TSource>);
}
public static ParallelQuery<TSource> AsOrdered<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery AsOrdered(ParallelQuery source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery>() != null);
return default(ParallelQuery);
}
public static ParallelQuery<TSource> AsParallel<TSource>(IEnumerable<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery AsParallel(System.Collections.IEnumerable source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery>() != null);
return default(ParallelQuery);
}
public static ParallelQuery<TSource> AsParallel<TSource>(System.Collections.Concurrent.Partitioner<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static IEnumerable<TSource> AsSequential<TSource>(ParallelQuery<TSource> source)
{
return default(IEnumerable<TSource>);
}
public static ParallelQuery<TSource> AsUnordered<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static Decimal Average(ParallelQuery<Decimal> source)
{
return default(Decimal);
}
public static Nullable<double> Average(ParallelQuery<Nullable<double>> source)
{
return default(Nullable<double>);
}
public static double Average(ParallelQuery<double> source)
{
return default(double);
}
public static Nullable<double> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
return default(Nullable<double>);
}
public static double Average<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
return default(double);
}
public static Nullable<Decimal> Average(ParallelQuery<Nullable<Decimal>> source)
{
return default(Nullable<Decimal>);
}
public static double Average(ParallelQuery<long> source)
{
return default(double);
}
public static Nullable<double> Average(ParallelQuery<Nullable<int>> source)
{
return default(Nullable<double>);
}
public static double Average(ParallelQuery<int> source)
{
return default(double);
}
public static Nullable<float> Average(ParallelQuery<Nullable<float>> source)
{
return default(Nullable<float>);
}
public static float Average(ParallelQuery<float> source)
{
return default(float);
}
public static Nullable<double> Average(ParallelQuery<Nullable<long>> source)
{
return default(Nullable<double>);
}
public static double Average<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
return default(double);
}
public static Nullable<double> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
return default(Nullable<double>);
}
public static Decimal Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
return default(Decimal);
}
public static Nullable<Decimal> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
return default(Nullable<Decimal>);
}
public static double Average<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
return default(double);
}
public static Nullable<double> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
return default(Nullable<double>);
}
public static float Average<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
return default(float);
}
public static Nullable<float> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
return default(Nullable<float>);
}
public static ParallelQuery<TResult> Cast<TResult>(ParallelQuery source)
{
Contract.Requires(source != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TSource> Concat<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Concat<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static bool Contains<TSource>(ParallelQuery<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
{
return default(bool);
}
public static bool Contains<TSource>(ParallelQuery<TSource> source, TSource value)
{
return default(bool);
}
public static int Count<TSource>(ParallelQuery<TSource> source)
{
return default(int);
}
public static int Count<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(int);
}
public static ParallelQuery<TSource> DefaultIfEmpty<TSource>(ParallelQuery<TSource> source, TSource defaultValue)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> DefaultIfEmpty<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Distinct<TSource>(ParallelQuery<TSource> source, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Distinct<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static TSource ElementAt<TSource>(ParallelQuery<TSource> source, int index)
{
return default(TSource);
}
public static TSource ElementAtOrDefault<TSource>(ParallelQuery<TSource> source, int index)
{
return default(TSource);
}
public static ParallelQuery<TResult> Empty<TResult>()
{
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static TSource First<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static TSource First<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(TSource);
}
public static TSource FirstOrDefault<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static TSource FirstOrDefault<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(TSource);
}
public static void ForAll<TSource>(ParallelQuery<TSource> source, Action<TSource> action)
{
}
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TElement, TResult>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TSource>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TSource>>);
}
public static ParallelQuery<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TSource>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TSource>>);
}
public static ParallelQuery<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TElement>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TElement>>);
}
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TResult>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TElement, TResult>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TElement>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TElement>>);
}
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TResult>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, ParallelQuery<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, ParallelQuery<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TSource> Intersect<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Intersect<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Intersect<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Intersect<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, ParallelQuery<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, ParallelQuery<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static TSource Last<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(TSource);
}
public static TSource Last<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static TSource LastOrDefault<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(TSource);
}
public static TSource LastOrDefault<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static long LongCount<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(-9223372036854775808 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long LongCount<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(long);
}
public static TSource Max<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static Nullable<Decimal> Max(ParallelQuery<Nullable<Decimal>> source)
{
return default(Nullable<Decimal>);
}
public static int Max<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
return default(int);
}
public static Nullable<int> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
return default(Nullable<int>);
}
public static Decimal Max(ParallelQuery<Decimal> source)
{
return default(Decimal);
}
public static Nullable<float> Max(ParallelQuery<Nullable<float>> source)
{
return default(Nullable<float>);
}
public static float Max(ParallelQuery<float> source)
{
return default(float);
}
public static Nullable<double> Max(ParallelQuery<Nullable<double>> source)
{
return default(Nullable<double>);
}
public static double Max(ParallelQuery<double> source)
{
return default(double);
}
public static Decimal Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
return default(Decimal);
}
public static Nullable<double> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
return default(Nullable<double>);
}
public static Nullable<Decimal> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
return default(Nullable<Decimal>);
}
public static Nullable<int> Max(ParallelQuery<Nullable<int>> source)
{
return default(Nullable<int>);
}
public static TResult Max<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
return default(TResult);
}
public static Nullable<long> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
return default(Nullable<long>);
}
public static long Max<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
return default(long);
}
public static float Max<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
return default(float);
}
public static double Max<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
return default(double);
}
public static Nullable<float> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
return default(Nullable<float>);
}
public static int Max(ParallelQuery<int> source)
{
return default(int);
}
public static long Max(ParallelQuery<long> source)
{
return default(long);
}
public static Nullable<long> Max(ParallelQuery<Nullable<long>> source)
{
return default(Nullable<long>);
}
public static Nullable<double> Min(ParallelQuery<Nullable<double>> source)
{
return default(Nullable<double>);
}
public static double Min(ParallelQuery<double> source)
{
return default(double);
}
public static Decimal Min(ParallelQuery<Decimal> source)
{
return default(Decimal);
}
public static TSource Min<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static Nullable<Decimal> Min(ParallelQuery<Nullable<Decimal>> source)
{
return default(Nullable<Decimal>);
}
public static int Min(ParallelQuery<int> source)
{
return default(int);
}
public static float Min(ParallelQuery<float> source)
{
return default(float);
}
public static Nullable<long> Min(ParallelQuery<Nullable<long>> source)
{
return default(Nullable<long>);
}
public static Nullable<float> Min(ParallelQuery<Nullable<float>> source)
{
return default(Nullable<float>);
}
public static Nullable<int> Min(ParallelQuery<Nullable<int>> source)
{
return default(Nullable<int>);
}
public static long Min(ParallelQuery<long> source)
{
return default(long);
}
public static Nullable<float> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
return default(Nullable<float>);
}
public static TResult Min<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
return default(TResult);
}
public static float Min<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
return default(float);
}
public static double Min<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
return default(double);
}
public static Nullable<Decimal> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
return default(Nullable<Decimal>);
}
public static Decimal Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
return default(Decimal);
}
public static Nullable<double> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
return default(Nullable<double>);
}
public static Nullable<long> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
return default(Nullable<long>);
}
public static int Min<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
return default(int);
}
public static Nullable<int> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
return default(Nullable<int>);
}
public static long Min<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
return default(long);
}
public static ParallelQuery<TResult> OfType<TResult>(ParallelQuery source)
{
return default(ParallelQuery<TResult>);
}
public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> OrderByDescending<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> OrderByDescending<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static ParallelQuery<int> Range(int start, int count)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<int>>() != null);
return default(ParallelQuery<int>);
}
public static ParallelQuery<TResult> Repeat<TResult>(TResult element, int count)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TSource> Reverse<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TResult> Select<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Select<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, int, TResult> selector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> SelectMany<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> SelectMany<TSource, TCollection, TResult>(ParallelQuery<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> SelectMany<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> SelectMany<TSource, TCollection, TResult>(ParallelQuery<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
return default(bool);
}
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(bool);
}
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
return default(bool);
}
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(bool);
}
public static TSource Single<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(TSource);
}
public static TSource Single<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static TSource SingleOrDefault<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
return default(TSource);
}
public static TSource SingleOrDefault<TSource>(ParallelQuery<TSource> source)
{
return default(TSource);
}
public static ParallelQuery<TSource> Skip<TSource>(ParallelQuery<TSource> source, int count)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> SkipWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> SkipWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static Nullable<long> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
return default(Nullable<long>);
}
public static Nullable<float> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
return default(Nullable<float>);
}
public static float Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
return default(float);
}
public static double Sum(ParallelQuery<double> source)
{
return default(double);
}
public static long Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
return default(long);
}
public static Decimal Sum(ParallelQuery<Decimal> source)
{
return default(Decimal);
}
public static Nullable<double> Sum(ParallelQuery<Nullable<double>> source)
{
return default(Nullable<double>);
}
public static Nullable<Decimal> Sum(ParallelQuery<Nullable<Decimal>> source)
{
return default(Nullable<Decimal>);
}
public static Nullable<int> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
return default(Nullable<int>);
}
public static int Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
return default(int);
}
public static Nullable<int> Sum(ParallelQuery<Nullable<int>> source)
{
return default(Nullable<int>);
}
public static int Sum(ParallelQuery<int> source)
{
return default(int);
}
public static Nullable<double> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
return default(Nullable<double>);
}
public static Nullable<long> Sum(ParallelQuery<Nullable<long>> source)
{
return default(Nullable<long>);
}
public static long Sum(ParallelQuery<long> source)
{
return default(long);
}
public static float Sum(ParallelQuery<float> source)
{
return default(float);
}
public static Nullable<float> Sum(ParallelQuery<Nullable<float>> source)
{
return default(Nullable<float>);
}
public static Nullable<Decimal> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
return default(Nullable<Decimal>);
}
public static Decimal Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
return default(Decimal);
}
public static double Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
return default(double);
}
public static ParallelQuery<TSource> Take<TSource>(ParallelQuery<TSource> source, int count)
{
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> TakeWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> TakeWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> ThenBy<TSource, TKey>(OrderedParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> ThenBy<TSource, TKey>(OrderedParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> ThenByDescending<TSource, TKey>(OrderedParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static OrderedParallelQuery<TSource> ThenByDescending<TSource, TKey>(OrderedParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
public static TSource[] ToArray<TSource>(ParallelQuery<TSource> source)
{
return default(TSource[]);
}
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TSource>>() != null);
return default(Dictionary<TKey, TSource>);
}
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TSource>>() != null);
return default(Dictionary<TKey, TSource>);
}
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
{
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TElement>>() != null);
return default(Dictionary<TKey, TElement>);
}
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TElement>>() != null);
return default(Dictionary<TKey, TElement>);
}
public static List<TSource> ToList<TSource>(ParallelQuery<TSource> source)
{
Contract.Ensures(Contract.Result<System.Collections.Generic.List<TSource>>() != null);
return default(List<TSource>);
}
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TElement>>() != null);
return default(ILookup<TKey, TElement>);
}
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TElement>>() != null);
return default(ILookup<TKey, TElement>);
}
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TSource>>() != null);
return default(ILookup<TKey, TSource>);
}
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(ParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TSource>>() != null);
return default(ILookup<TKey, TSource>);
}
public static ParallelQuery<TSource> Union<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Union<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Union<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Union<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Where<TSource>(ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> Where<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> WithCancellation<TSource>(ParallelQuery<TSource> source, System.Threading.CancellationToken cancellationToken)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> WithDegreeOfParallelism<TSource>(ParallelQuery<TSource> source, int degreeOfParallelism)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> WithExecutionMode<TSource>(ParallelQuery<TSource> source, ParallelExecutionMode executionMode)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TSource> WithMergeOptions<TSource>(ParallelQuery<TSource> source, ParallelMergeOptions mergeOptions)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
public static ParallelQuery<TResult> Zip<TFirst, TSecond, TResult>(ParallelQuery<TFirst> first, ParallelQuery<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Zip<TFirst, TSecond, TResult>(ParallelQuery<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using FlatRedBall.Utilities;
using System.Globalization;
using FlatRedBall.IO;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace FlatRedBall.Instructions.Reflection
{
public struct PropertyValuePair
{
static Type stringType = typeof(string);
public string Property;
public object Value;
static Dictionary<string, Type> mUnqualifiedTypeDictionary = new Dictionary<string, Type>();
#if WINDOWS_8 || UWP
/// <summary>
/// Stores a reference to the current assembly. This is the
/// assembly of your game. This must be explicitly set.
/// </summary>
public static Assembly TopLevelAssembly
{
get;
set;
}
#endif
public static List<Assembly> AdditionalAssemblies
{
get;
private set;
}
static PropertyValuePair()
{
AdditionalAssemblies = new List<Assembly>();
}
public PropertyValuePair(string property, object value)
{
Property = property;
Value = value;
}
public static string ConvertTypeToString(object value)
{
if (value == null) return string.Empty;
// Get the type
Type typeToConvertTo = value.GetType();
// Do the conversion
#region Convert To String
if (typeToConvertTo == typeof(bool))
{
return ((bool)value).ToString();
}
if (typeToConvertTo == typeof(int) || typeToConvertTo == typeof(Int32) || typeToConvertTo == typeof(Int16))
{
return ((int)value).ToString();
}
if (typeToConvertTo == typeof(float) || typeToConvertTo == typeof(Single))
{
return ((float)value).ToString();
}
if (typeToConvertTo == typeof(double))
{
return ((double)value).ToString();
}
if (typeToConvertTo == typeof(string))
{
return (string)value;
}
#if !FRB_RAW
if (typeToConvertTo == typeof(Texture2D))
{
return ((Texture2D)value).Name;
}
if (typeToConvertTo == typeof(Matrix))
{
Matrix m = (Matrix)value;
float[] values = new float[16];
values[0] = m.M11;
values[1] = m.M12;
values[2] = m.M13;
values[3] = m.M14;
values[4] = m.M21;
values[5] = m.M22;
values[6] = m.M23;
values[7] = m.M24;
values[8] = m.M31;
values[9] = m.M32;
values[10] = m.M33;
values[11] = m.M34;
values[12] = m.M41;
values[13] = m.M42;
values[14] = m.M43;
values[15] = m.M44;
string outputString = string.Empty;
// output values in comma-delimited form
for (int i = 0; i < values.Length; i++)
{
outputString += ((i == 0) ? string.Empty : ",") +
ConvertTypeToString(values[i]);
}
return outputString;
}
if (typeToConvertTo == typeof(Vector2))
{
Vector2 v = (Vector2)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y);
}
if (typeToConvertTo == typeof(Vector3))
{
Vector3 v = (Vector3)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y) + "," +
ConvertTypeToString(v.Z);
}
if (typeToConvertTo == typeof(Vector4))
{
Vector4 v = (Vector4)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y) + "," +
ConvertTypeToString(v.Z) + "," +
ConvertTypeToString(v.W);
}
#endif
#if WINDOWS_8 || UWP
if (typeToConvertTo.IsEnum())
#else
if (typeToConvertTo.IsEnum)
#endif
{
return value.ToString();
}
#endregion
// No cases matched, return empty string
return String.Empty;
}
public static T ConvertStringToType<T>(string value)
{
return (T)ConvertStringToType(value, typeof(T));
}
public static object ConvertStringToType(string value, Type typeToConvertTo)
{
#if FRB_RAW
return ConvertStringToType(value, typeToConvertTo, "Global");
#else
return ConvertStringToType(value, typeToConvertTo, FlatRedBallServices.GlobalContentManager);
#endif
}
public static object ConvertStringToType(string value, Type typeToConvertTo, string contentManagerName)
{
return ConvertStringToType(value, typeToConvertTo, contentManagerName, false);
}
public static object ConvertStringToType(string value, Type typeToConvertTo, string contentManagerName, bool trimQuotes)
{
if (IsGenericList(typeToConvertTo))
{
return CreateGenericListFrom(value, typeToConvertTo, contentManagerName);
}
else
{
return ConvertStringValueToValueOfType(value, typeToConvertTo.FullName, contentManagerName, trimQuotes);
}
}
public static object ConvertStringValueToValueOfType(string value, string desiredType, string contentManagerName, bool trimQuotes)
{
value = value.Trim(); // this is in case there is a space in front - I don't think we need it.
//Fix any exported CSV bugs (such as quotes around a boolean)
if (trimQuotes ||
(value != null && (desiredType != typeof(string).FullName && desiredType != typeof(char).FullName)
&& value.Contains("\"") == false) // If it has a quote, then we don't want to trim.
)
{
if (!value.StartsWith("new ") && desiredType != typeof(string).FullName)
{
value = FlatRedBall.Utilities.StringFunctions.RemoveWhitespace(value);
}
value = value.Replace("\"", "");
}
// Do the conversion
#region Convert To Object
// String needs to be first because it could contain equals and
// we don't want to cause problems
bool handled = false;
object toReturn = null;
if (desiredType == typeof(string).FullName)
{
toReturn = value;
handled = true;
}
if (!handled)
{
TryHandleComplexType(value, desiredType, out handled, out toReturn);
}
if (!handled)
{
#region bool
if (desiredType == typeof(bool).FullName)
{
if (string.IsNullOrEmpty(value))
{
return false;
}
// value could be upper case like "TRUE" or "True". Make it lower
value = value.ToLower();
toReturn = bool.Parse(value);
handled = true;
}
#endregion
#region int, Int32, Int16, uint, long
else if (desiredType == typeof(int).FullName || desiredType == typeof(Int32).FullName || desiredType == typeof(Int16).FullName ||
desiredType == typeof(uint).FullName || desiredType == typeof(long).FullName || desiredType == typeof(byte).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0;
}
int indexOfDecimal = value.IndexOf('.');
if (value.IndexOf(",") != -1)
{
value = value.Replace(",", "");
}
#region uint
if (desiredType == typeof(uint).FullName)
{
if (indexOfDecimal == -1)
{
return uint.Parse(value);
}
else
{
return (uint)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
#region byte
if (desiredType == typeof(byte).FullName)
{
if (indexOfDecimal == -1)
{
return byte.Parse(value);
}
else
{
return (byte)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
#region long
if (desiredType == typeof(long).FullName)
{
if (indexOfDecimal == -1)
{
return long.Parse(value);
}
else
{
return (long)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
#region regular int
else
{
if (indexOfDecimal == -1)
{
return int.Parse(value);
}
else
{
return (int)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
}
#endregion
#region float, Single
else if (desiredType == typeof(float).FullName || desiredType == typeof(Single).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0f;
}
return float.Parse(value, CultureInfo.InvariantCulture);
}
#endregion
#region double
else if (desiredType == typeof(double).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0.0;
}
return double.Parse(value, CultureInfo.InvariantCulture);
}
#endregion
#if !FRB_RAW
#region Texture2D
else if (desiredType == typeof(Texture2D).FullName)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
#if !SILVERLIGHT && !ZUNE
if (FileManager.IsRelative(value))
{
// Vic says: This used to throw an exception on relative values. I'm not quite
// sure why this is the case...why don't we just make it relative to the relative
// directory? Maybe there's a reason to have this exception, but I can't think of
// what it is, and I'm writing a tutorial on how to load Texture2Ds from CSVs right
// now and it totally makes sense that the user would want to use a relative directory.
// In fact, the user will want to always use a relative directory so that their project is
// portable.
//throw new ArgumentException("Texture path must be absolute to load texture. Path: " + value);
value = FileManager.RelativeDirectory + value;
}
// Try to load a compiled asset first
if (FileManager.FileExists(FileManager.RemoveExtension(value) + @".xnb"))
{
Texture2D texture =
FlatRedBallServices.Load<Texture2D>(FileManager.RemoveExtension(value), contentManagerName);
// Vic asks: Why did we have to set the name? This is redundant and gets
// rid of the standardized file name which causes caching to not work properly.
// texture.Name = FileManager.RemoveExtension(value);
return texture;
}
else
{
Texture2D texture =
FlatRedBallServices.Load<Texture2D>(value, contentManagerName);
// Vic asks: Why did we have to set the name? This is redundant and gets
// rid of the standardized file name which causes caching to not work properly.
// texture.Name = value;
return texture;
}
#else
return null;
#endif
}
#endregion
#region Matrix
else if (desiredType == typeof(Matrix).FullName)
{
if (string.IsNullOrEmpty(value))
{
return Matrix.Identity;
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 16)
{
throw new ArgumentException("String to Matrix conversion requires 16 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[16];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
// Parse to matrix
Matrix m = new Matrix(
values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]
);
return m;
}
#endregion
#region Vector2
else if (desiredType == typeof(Vector2).FullName)
{
if (string.IsNullOrEmpty(value))
{
return new Vector2(0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 2)
{
throw new ArgumentException("String to Vector2 conversion requires 2 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[2];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector2(values[0], values[1]);
}
#endregion
#region Vector3
else if (desiredType == typeof(Vector3).FullName)
{
if (string.IsNullOrEmpty(value))
{
return new Vector3(0, 0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 3)
{
throw new ArgumentException("String to Vector3 conversion requires 3 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[3];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector3(values[0], values[1], values[2]);
}
#endregion
#region Vector4
else if (desiredType == typeof(Vector4).FullName)
{
if (string.IsNullOrEmpty(value))
{
return new Vector4(0, 0, 0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 4)
{
throw new ArgumentException("String to Vector4 conversion requires 4 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector4(values[0], values[1], values[2], values[3]);
}
#endregion
#endif
#region enum
else if (IsEnum(desiredType))
{
#if DEBUG
if (string.IsNullOrEmpty(value))
{
throw new InvalidOperationException("Error trying to create enum value for empty string. Enum type: " + desiredType);
}
#endif
bool ignoreCase = true; // 3rd arugment needed for 360
Type foundType;
if (mUnqualifiedTypeDictionary.ContainsKey(desiredType))
{
foundType = mUnqualifiedTypeDictionary[desiredType];
}
else
{
foundType = TryToGetTypeFromAssemblies(desiredType);
}
return Enum.Parse(foundType, value, ignoreCase); // built-in .NET version
//return StringEnum.Parse(typeToConvertTo, value);
}
#endregion
#region Color
else if (desiredType == typeof(Color).FullName)
{
#if WINDOWS_8 || UWP
PropertyInfo info = typeof(Color).GetProperty(value);
#else
PropertyInfo info = typeof(Color).GetProperty(value, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
#endif
if (info == null)
{
if (value.StartsWith("Color."))
{
throw new Exception("Could not parse the value " + value + ". Remove \"Color.\" and instead " +
"use " + value.Substring("Color.".Length));
}
else
{
throw new Exception("Could not parse " + value + " as a Color");
}
}
toReturn = info.GetValue(null, null);
handled = true;
}
#endregion
#endregion
// Why do we catch exceptions here? That seems baaaad
//catch (Exception)
//{
// //int m = 3;
//}
if (!handled)
{
throw new NotImplementedException("Cannot convert the value " + value + " to the type " +
desiredType.ToString());
}
}
return toReturn;
}
private static bool IsEnum(string typeAsString)
{
Type foundType = null;
if (mUnqualifiedTypeDictionary.ContainsKey(typeAsString))
{
foundType = mUnqualifiedTypeDictionary[typeAsString];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeAsString);
}
return foundType != null &&
#if WINDOWS_8 || UWP
foundType.IsEnum();
#else
foundType.IsEnum;
#endif
}
private static void TryHandleComplexType(string value, string typeToConvertTo, out bool handled, out object toReturn)
{
handled = false;
toReturn = null;
if (value.StartsWith("new "))
{
string typeAfterNewString = value.Substring("new ".Length, value.IndexOf('(') - "new ".Length);
Type foundType = null;
if (mUnqualifiedTypeDictionary.ContainsKey(typeAfterNewString))
{
foundType = mUnqualifiedTypeDictionary[typeAfterNewString];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeAfterNewString);
}
if (foundType != null)
{
int openingParen = value.IndexOf('(');
// Make sure to get the last parenthesis, in case one of the inner properties is a complex type
int closingParen = value.LastIndexOf(')');
// Make sure valid parenthesis were found
if (openingParen < 0 || closingParen < 0)
throw new InvalidOperationException("Type definition did not have a matching pair of opening and closing parenthesis");
if (openingParen > closingParen)
throw new InvalidOperationException("Type definition has parenthesis in the incorrect order");
string valueInsideParens = value.Substring(openingParen + 1, closingParen - (openingParen + 1));
toReturn = CreateInstanceFromNamedAssignment(foundType, valueInsideParens);
}
else
{
throw new InvalidOperationException("Could not find a type in the assemblies for " + foundType);
}
handled = true;
}
else if (value.Contains("="))
{
// They're using the "x=0,y=0,z=0" syntax
handled = true;
Type foundType = null;
if (mUnqualifiedTypeDictionary.ContainsKey(typeToConvertTo))
{
foundType = mUnqualifiedTypeDictionary[typeToConvertTo];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeToConvertTo);
}
toReturn = CreateInstanceFromNamedAssignment(foundType, value);
}
}
public static List<string> SplitProperties(string value)
{
var splitOnComma = value.Split(',');
List<string> toReturn = new List<string>();
// We may have a List declaration, or a string with commas in it, so we need to account for that
// For now I'm going to handle the list declaration because that's what I need for Baron, but will
// eventually return to this and make it more robust to handle strings with commas too.
int parenCount = 0;
int quoteCount = 0;
foreach (string entryInSplit in splitOnComma)
{
bool shouldCombine = parenCount != 0 || quoteCount != 0;
parenCount += entryInSplit.CountOf("(");
parenCount -= entryInSplit.CountOf(")");
quoteCount += entryInSplit.CountOf("\"");
quoteCount = (quoteCount % 2);
if (shouldCombine)
{
toReturn[toReturn.Count - 1] = toReturn[toReturn.Count - 1] + ',' + entryInSplit;
}
else
{
toReturn.Add(entryInSplit);
}
}
return toReturn;
}
private static object CreateGenericListFrom(string value, Type listType, string contentManagerName)
{
object newObject = Activator.CreateInstance(listType);
Type genericType = listType.GetGenericArguments()[0];
MethodInfo add = listType.GetMethod("Add");
int start = value.IndexOf("(") + 1;
int end = value.IndexOf(")");
if (end > 0)
{
string insideOfParens = value.Substring(start, end - start);
// Cheat for now, make it more robust later
var values = SplitProperties(insideOfParens);
object[] arguments = new object[1];
foreach (var itemInList in values)
{
object converted = ConvertStringToType(itemInList, genericType, contentManagerName, true);
arguments[0] = converted;
add.Invoke(newObject, arguments);
}
}
return newObject;
}
private static Type TryToGetTypeFromAssemblies(string typeAfterNewString)
{
Type foundType = null;
#if WINDOWS_8 || UWP
foundType = TryToGetTypeFromAssembly(typeAfterNewString, FlatRedBallServices.Game.GetType().GetTypeInfo().Assembly);
if (foundType == null)
{
#if DEBUG
if (TopLevelAssembly == null)
{
throw new Exception("The TopLevelAssembly member must be set before it is used. It is currently null");
}
#endif
foundType = TryToGetTypeFromAssembly(typeAfterNewString, TopLevelAssembly);
}
if (foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(Vector3).GetTypeInfo().Assembly);
}
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(FlatRedBall.Sprite).GetTypeInfo().Assembly);
}
#else
// This may be run from a tool. If so
// then there is no Game class, so we shouldn't
// try to use it.
if (FlatRedBallServices.Game != null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, FlatRedBallServices.Game.GetType().Assembly);
}
if (foundType == null)
{
foreach (var assembly in AdditionalAssemblies)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, assembly);
if (foundType != null)
{
break;
}
}
}
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, Assembly.GetExecutingAssembly());
}
if (foundType == null)
{
#if WINDOWS
foundType = TryToGetTypeFromAssembly(typeAfterNewString, Assembly.GetEntryAssembly());
#endif
}
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(Vector3).Assembly);
}
#endif
if (foundType == null)
{
throw new ArgumentException("Could not find the type for " + typeAfterNewString);
}
else
{
mUnqualifiedTypeDictionary.Add(typeAfterNewString, foundType);
}
return foundType;
}
private static Type TryToGetTypeFromAssembly(string typeAfterNewString, Assembly assembly)
{
Type foundType = null;
// Make sure the type isn't null, and the type string is trimmed to make the compare valid
if (typeAfterNewString == null)
return null;
typeAfterNewString = typeAfterNewString.Trim();
// Is this slow? Do we want to cache off the Type[]?
#if WINDOWS_8
IEnumerable<Type> types = assembly.ExportedTypes;
#else
IEnumerable<Type> types = assembly.GetTypes();
#endif
foreach (Type type in types)
{
if (type.Name == typeAfterNewString || type.FullName == typeAfterNewString)
{
foundType = type;
break;
}
}
return foundType;
}
private static object CreateInstanceFromNamedAssignment(Type type, string value)
{
object returnObject = null;
value = value.Trim();
returnObject = Activator.CreateInstance(type);
if (!string.IsNullOrEmpty(value))
{
var split = SplitProperties(value);
foreach (string assignment in split)
{
int indexOfEqual = assignment.IndexOf('=');
// If the assignment is not in the proper Name=Value format, ignore it
// Update - November 6, 2015
// This can hide syntax errors
// in the CSV. It allows cells to
// do things like: new Vectore(1,2,3)
// We want an error to be thrown so the
// user knows what to do to fix the CSV:
if (indexOfEqual < 0)
{
string message =
"Invalid value " + assignment + " in " + value + $". Expected a variable assignment like \"X={assignment}\" when creating an instance of {type.Name}";
throw new Exception(message);
}
// Make sure the = sign isn't the last character in the assignment
if (indexOfEqual >= assignment.Length - 1)
continue;
string variableName = assignment.Substring(0, indexOfEqual).Trim();
string whatToassignTo = assignment.Substring(indexOfEqual + 1, assignment.Length - (indexOfEqual + 1));
FieldInfo fieldInfo = type.GetField(variableName);
if (fieldInfo != null)
{
Type fieldType = fieldInfo.FieldType;
StripQuotesIfNecessary(ref whatToassignTo);
object assignValue = ConvertStringToType(whatToassignTo, fieldType);
fieldInfo.SetValue(returnObject, assignValue);
}
else
{
PropertyInfo propertyInfo = type.GetProperty(variableName);
#if DEBUG
if (propertyInfo == null)
{
throw new ArgumentException("Could not find the field/property " + variableName + " in the type " + type.Name);
}
#endif
Type propertyType = propertyInfo.PropertyType;
StripQuotesIfNecessary(ref whatToassignTo);
object assignValue = ConvertStringToType(whatToassignTo, propertyType);
propertyInfo.SetValue(returnObject, assignValue, null);
}
}
}
return returnObject;
}
public static bool IsGenericList(Type type)
{
bool isGenericList = false;
#if WINDOWS_8 || UWP
// Not sure why we check the declaring type. I think declaring
// type is for when a class is inside of another class
//if (type.DeclaringType.IsGenericParameter && (type.GetGenericTypeDefinition() == typeof(List<>)))
if (type.GetGenericTypeDefinition() == typeof(List<>))
#else
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>)))
#endif
{
isGenericList = true;
}
return isGenericList;
}
private static void StripQuotesIfNecessary(ref string whatToassignTo)
{
if (whatToassignTo != null)
{
string trimmed = whatToassignTo.Trim();
if (trimmed.StartsWith("\"") &&
trimmed.EndsWith("\"") && trimmed.Length > 1)
{
whatToassignTo = trimmed.Substring(1, trimmed.Length - 2);
}
}
}
//Remove any parenthesis at the start and end of the string.
private static string StripParenthesis(string value)
{
string result = value;
if (result.StartsWith("("))
{
int startIndex = 1;
int endIndex = result.Length - 1;
if (result.EndsWith(")"))
endIndex -= 1;
result = result.Substring(startIndex, endIndex);
}
return result;
}
public override string ToString()
{
return Property + " = " + Value;
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using AllReady.Models;
namespace AllReady.Migrations
{
[DbContext(typeof(AllReadyContext))]
partial class AllReadyContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CampaignId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("AdditionalInfo");
b.Property<DateTime?>("CheckinDateTime");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<DateTime>("SignupDateTime");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.Property<int>("ActivityId");
b.Property<int>("SkillId");
b.HasKey("ActivityId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("Description");
b.Property<DateTimeOffset?>("EndDateTime");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<int?>("OrganizationId");
b.Property<DateTimeOffset?>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("Name");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<int?>("OrganizationId");
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<string>("TimeZoneId")
.IsRequired();
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignImpactId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("FullDescription");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<int>("ManagingOrganizationId");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.Property<string>("TimeZoneId")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.Property<int>("CampaignId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("CampaignId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.CampaignImpact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CurrentImpactLevel");
b.Property<bool>("Display");
b.Property<int>("ImpactType");
b.Property<int>("NumericImpactGoal");
b.Property<string>("TextualImpactGoal");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignId");
b.Property<int?>("OrganizationId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<string>("PhoneNumber");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address1");
b.Property<string>("Address2");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Name");
b.Property<string>("PhoneNumber");
b.Property<string>("PostalCodePostalCode");
b.Property<string>("State");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Organization", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("LocationId");
b.Property<string>("LogoUrl");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("WebUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
{
b.Property<int>("OrganizationId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("OrganizationId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.Resource", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CategoryTag");
b.Property<string>("Description");
b.Property<string>("MediaUrl");
b.Property<string>("Name");
b.Property<DateTime>("PublishDateBegin");
b.Property<DateTime>("PublishDateEnd");
b.Property<string>("ResourceUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name")
.IsRequired();
b.Property<int?>("OwningOrganizationId");
b.Property<int?>("ParentSkillId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Status");
b.Property<DateTime>("StatusDateTimeUtc");
b.Property<string>("StatusDescription");
b.Property<int?>("TaskId");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.Property<int>("TaskId");
b.Property<int>("SkillId");
b.HasKey("TaskId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.Property<string>("UserId");
b.Property<int>("SkillId");
b.HasKey("UserId", "SkillId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.HasOne("AllReady.Models.CampaignImpact")
.WithMany()
.HasForeignKey("CampaignImpactId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("ManagingOrganizationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.HasOne("AllReady.Models.PostalCodeGeo")
.WithMany()
.HasForeignKey("PostalCodePostalCode");
});
modelBuilder.Entity("AllReady.Models.Organization", b =>
{
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
});
modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
{
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OwningOrganizationId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("ParentSkillId");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.BackupServices;
using Microsoft.Azure.Management.BackupServices.Models;
namespace Microsoft.Azure.Management.BackupServices
{
public static partial class ContainerOperationsExtensions
{
/// <summary>
/// Enable the container reregistration.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='enableReregistrationRequest'>
/// Required. Enable Reregistration Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public static OperationResponse EnableMarsContainerReregistration(this IContainerOperations operations, string containerId, EnableReregistrationRequest enableReregistrationRequest, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).EnableMarsContainerReregistrationAsync(containerId, enableReregistrationRequest, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Enable the container reregistration.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='enableReregistrationRequest'>
/// Required. Enable Reregistration Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public static Task<OperationResponse> EnableMarsContainerReregistrationAsync(this IContainerOperations operations, string containerId, EnableReregistrationRequest enableReregistrationRequest, CustomRequestHeaders customRequestHeaders)
{
return operations.EnableMarsContainerReregistrationAsync(containerId, enableReregistrationRequest, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public static ListMarsContainerOperationResponse ListMarsContainersByType(this IContainerOperations operations, MarsContainerType containerType, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).ListMarsContainersByTypeAsync(containerType, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public static Task<ListMarsContainerOperationResponse> ListMarsContainersByTypeAsync(this IContainerOperations operations, MarsContainerType containerType, CustomRequestHeaders customRequestHeaders)
{
return operations.ListMarsContainersByTypeAsync(containerType, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='friendlyName'>
/// Required. Friendly name of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public static ListMarsContainerOperationResponse ListMarsContainersByTypeAndFriendlyName(this IContainerOperations operations, MarsContainerType containerType, string friendlyName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).ListMarsContainersByTypeAndFriendlyNameAsync(containerType, friendlyName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='friendlyName'>
/// Required. Friendly name of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public static Task<ListMarsContainerOperationResponse> ListMarsContainersByTypeAndFriendlyNameAsync(this IContainerOperations operations, MarsContainerType containerType, string friendlyName, CustomRequestHeaders customRequestHeaders)
{
return operations.ListMarsContainersByTypeAndFriendlyNameAsync(containerType, friendlyName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Unregister the container.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public static OperationResponse UnregisterMarsContainer(this IContainerOperations operations, string containerId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).UnregisterMarsContainerAsync(containerId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Unregister the container.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.BackupServices.IContainerOperations.
/// </param>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public static Task<OperationResponse> UnregisterMarsContainerAsync(this IContainerOperations operations, string containerId, CustomRequestHeaders customRequestHeaders)
{
return operations.UnregisterMarsContainerAsync(containerId, customRequestHeaders, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
namespace Zenject
{
public abstract class ProviderBindingFinalizer : IBindingFinalizer
{
public ProviderBindingFinalizer(BindInfo bindInfo)
{
BindInfo = bindInfo;
}
public bool CopyIntoAllSubContainers
{
get { return BindInfo.CopyIntoAllSubContainers; }
}
protected BindInfo BindInfo
{
get;
private set;
}
protected ScopeTypes GetScope()
{
if (BindInfo.Scope == ScopeTypes.Unset)
{
// If condition is set then it's probably fine to allow the default of transient
Assert.That(!BindInfo.RequireExplicitScope || BindInfo.Condition != null,
"Scope must be set for the previous binding! Please either specify AsTransient, AsCached, or AsSingle. Last binding: Contract: {0}, Identifier: {1} {2}",
BindInfo.ContractTypes.Select(x => x.ToString()).Join(", "), BindInfo.Identifier,
BindInfo.ContextInfo != null ? "Context: '{0}'".Fmt(BindInfo.ContextInfo) : "");
return ScopeTypes.Transient;
}
return BindInfo.Scope;
}
public void FinalizeBinding(DiContainer container)
{
if (BindInfo.ContractTypes.IsEmpty())
{
// We could assert her instead but it is nice when used with things like
// BindInterfaces() (and there aren't any interfaces) to allow
// interfaces to be added later
return;
}
OnFinalizeBinding(container);
if (BindInfo.NonLazy)
{
// Note that we can't simply use container.BindRootResolve here because
// binding finalizers must only use RegisterProvider to allow cloning / bind
// inheritance to work properly
var bindingId = new BindingId(
typeof(object), DiContainer.DependencyRootIdentifier);
foreach (var contractType in BindInfo.ContractTypes)
{
container.RegisterProvider(
bindingId, null, new ResolveProvider(
contractType, container, BindInfo.Identifier, false,
// We always want to only use local here so that we can use
// NonLazy() inside subcontainers
InjectSources.Local));
}
}
}
protected abstract void OnFinalizeBinding(DiContainer container);
protected void RegisterProvider<TContract>(
DiContainer container, IProvider provider)
{
RegisterProvider(container, typeof(TContract), provider);
}
protected void RegisterProvider(
DiContainer container, Type contractType, IProvider provider)
{
container.RegisterProvider(
new BindingId(contractType, BindInfo.Identifier),
BindInfo.Condition,
provider);
if (contractType.IsValueType())
{
var nullableType = typeof(Nullable<>).MakeGenericType(contractType);
// Also bind to nullable primitives
// this is useful so that we can have optional primitive dependencies
container.RegisterProvider(
new BindingId(nullableType, BindInfo.Identifier),
BindInfo.Condition,
provider);
}
}
protected void RegisterProviderPerContract(
DiContainer container, Func<DiContainer, Type, IProvider> providerFunc)
{
foreach (var contractType in BindInfo.ContractTypes)
{
RegisterProvider(container, contractType, providerFunc(container, contractType));
}
}
protected void RegisterProviderForAllContracts(
DiContainer container, IProvider provider)
{
foreach (var contractType in BindInfo.ContractTypes)
{
RegisterProvider(container, contractType, provider);
}
}
protected void RegisterProvidersPerContractAndConcreteType(
DiContainer container,
List<Type> concreteTypes,
Func<Type, Type, IProvider> providerFunc)
{
Assert.That(!BindInfo.ContractTypes.IsEmpty());
Assert.That(!concreteTypes.IsEmpty());
foreach (var contractType in BindInfo.ContractTypes)
{
foreach (var concreteType in concreteTypes)
{
if (ValidateBindTypes(concreteType, contractType))
{
RegisterProvider(
container, contractType, providerFunc(contractType, concreteType));
}
}
}
}
// Returns true if the bind should continue, false to skip
bool ValidateBindTypes(Type concreteType, Type contractType)
{
if (concreteType.IsOpenGenericType() != contractType.IsOpenGenericType())
{
return false;
}
#if !(UNITY_WSA && ENABLE_DOTNET)
// TODO: Is it possible to do this on WSA?
if (contractType.IsOpenGenericType())
{
Assert.That(concreteType.IsOpenGenericType());
if (TypeExtensions.IsAssignableToGenericType(concreteType, contractType))
{
return true;
}
}
else if (concreteType.DerivesFromOrEqual(contractType))
{
return true;
}
#else
if (concreteType.DerivesFromOrEqual(contractType))
{
return true;
}
#endif
if (BindInfo.InvalidBindResponse == InvalidBindResponses.Assert)
{
throw Assert.CreateException(
"Expected type '{0}' to derive from or be equal to '{1}'", concreteType, contractType);
}
Assert.IsEqual(BindInfo.InvalidBindResponse, InvalidBindResponses.Skip);
return false;
}
// Note that if multiple contract types are provided per concrete type,
// it will re-use the same provider for each contract type
// (each concrete type will have its own provider though)
protected void RegisterProvidersForAllContractsPerConcreteType(
DiContainer container,
List<Type> concreteTypes,
Func<DiContainer, Type, IProvider> providerFunc)
{
Assert.That(!BindInfo.ContractTypes.IsEmpty());
Assert.That(!concreteTypes.IsEmpty());
var providerMap = concreteTypes.ToDictionary(x => x, x => providerFunc(container, x));
foreach (var contractType in BindInfo.ContractTypes)
{
foreach (var concreteType in concreteTypes)
{
if (ValidateBindTypes(concreteType, contractType))
{
RegisterProvider(container, contractType, providerMap[concreteType]);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
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 Models;
/// <summary>
/// HttpFailure operations.
/// </summary>
public partial class HttpFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpFailure
{
/// <summary>
/// Initializes a new instance of the HttpFailure class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public HttpFailure(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Get empty error form server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetEmptyErrorWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetEmptyError", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/emptybody/error").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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;
// 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_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 HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_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;
}
/// <summary>
/// Get empty error form server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNoModelErrorWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetNoModelError", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/error").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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;
// 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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 HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_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;
}
/// <summary>
/// Get empty response from server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNoModelEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetNoModelEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/empty").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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;
// 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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 HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.ComponentModel.Composition;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Dom;
using Sce.Sled.Lua.Dom;
using Sce.Sled.Lua.Resources;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Services;
namespace Sce.Sled.Lua
{
[Export(typeof(SledLuaEnvironmentVariableService))]
[PartCreationPolicy(CreationPolicy.Shared)]
sealed class SledLuaEnvironmentVariableService : SledLuaBaseVariableService<SledLuaVarEnvListType, SledLuaVarEnvType>
{
#region SledLuaBaseVariableService Overrides
protected override void Initialize()
{
m_luaCallStackService = SledServiceInstance.Get<ISledLuaCallStackService>();
m_luaCallStackService.Clearing += LuaCallStackServiceClearing;
m_luaCallStackService.LevelAdding += LuaCallStackServiceLevelAdding;
m_luaCallStackService.StackLevelChanging += LuaCallStackServiceStackLevelChanging;
m_luaCallStackService.StackLevelChanged += LuaCallStackServiceStackLevelChanged;
}
protected override string ShortName
{
get { return Localization.SledLuaEnvironmentTitleShort; }
}
protected override string PopupPrefix
{
get { return "[E]"; }
}
protected override SledLuaTreeListViewEditor Editor
{
get { return m_editor; }
}
protected override DomNodeType NodeType
{
get { return SledLuaSchema.SledLuaVarEnvType.Type; }
}
protected override void OnDebugServiceDataReady(object sender, SledDebugServiceEventArgs e)
{
var typeCode = (Scmp.LuaTypeCodes)e.Scmp.TypeCode;
switch (typeCode)
{
//case Scmp.LuaTypeCodes.LuaVarEnvVarBegin:
// break;
case Scmp.LuaTypeCodes.LuaVarEnvVar:
{
if (!LuaWatchedVariableService.ReceivingWatchedVariables)
{
var envVar = LuaVarScmpService.GetScmpBlobAsLuaEnvironmentVar();
RemoteTargetCallStackEnvVar(envVar);
}
}
break;
//case Scmp.LuaTypeCodes.LuaVarEnvVarEnd:
// break;
case Scmp.LuaTypeCodes.LuaVarEnvVarLookupBegin:
OnDebugServiceLookupBegin();
break;
case Scmp.LuaTypeCodes.LuaVarEnvVarLookupEnd:
OnDebugServiceLookupEnd();
break;
}
}
protected override void OnLuaVariableFilterServiceFiltered(object sender, SledLuaVariableFilterService.FilteredEventArgs e)
{
if (e.NodeType != NodeType)
return;
if (m_luaCallStackService.CurrentStackLevel >= Collection.Count)
return;
m_editor.View = Collection[m_luaCallStackService.CurrentStackLevel];
}
#endregion
#region ISledLuaCallStackService Events
private void LuaCallStackServiceClearing(object sender, EventArgs e)
{
m_editor.View = null;
if (m_luaCallStackService.CurrentStackLevel != 0)
{
if (Collection.Count > 0)
Collection[0].ResetExpandedStates();
}
foreach (var collection in Collection)
collection.Variables.Clear();
}
private void LuaCallStackServiceLevelAdding(object sender, SledLuaCallStackServiceEventArgs e)
{
if ((e.NewLevel + 1) > Collection.Count)
{
var root =
new DomNode(
SledLuaSchema.SledLuaVarEnvListType.Type,
SledLuaSchema.SledLuaVarEnvListRootElement);
var envVars = root.As<SledLuaVarEnvListType>();
envVars.Name =
string.Format(
"{0}{1}{2}{3}",
ProjectService.ProjectName,
Resource.Space,
Resource.LuaEnvironmentVariables,
e.NewLevel);
envVars.DomNode.AttributeChanged += DomNodeAttributeChanged;
Collection.Add(envVars);
}
if ((e.NewLevel == 0) && (Collection.Count > 0))
m_editor.View = Collection[0];
}
private void LuaCallStackServiceStackLevelChanging(object sender, SledLuaCallStackServiceEventArgs e)
{
foreach (var collection in Collection)
collection.ValidationBeginning();
m_editor.View = null;
Collection[e.OldLevel].SaveExpandedStates();
m_editor.View = Collection[e.NewLevel];
}
private void LuaCallStackServiceStackLevelChanged(object sender, SledLuaCallStackServiceEventArgs e)
{
foreach (var collection in Collection)
collection.ValidationEnded();
}
#endregion
#region Member Methods
private void RemoteTargetCallStackEnvVar(SledLuaVarEnvType variable)
{
var iCount = Collection.Count;
if (iCount <= variable.Level)
return;
Collection[variable.Level].ValidationBeginning();
// Add any locations
LuaVarLocationService.AddLocations(variable);
// Do any filtering
variable.Visible = !LuaVariableFilterService.IsVariableFiltered(variable);
// Figure out where to insert
if (!LookingUp)
{
Collection[variable.Level].Variables.Add(variable);
}
else
{
if (ListInsert.Count > 0)
ListInsert[0].EnvVars.Add(variable);
else
{
SledOutDevice.OutLine(
SledMessageType.Error,
"[SledLuaEnvironmentVariableService] " +
"Failed to add environment variable: {0}",
variable.Name);
}
}
}
#endregion
private ISledLuaCallStackService m_luaCallStackService;
#pragma warning disable 649 // Field is never assigned
[Import]
private SledLuaEnvVarsEditor m_editor;
#pragma warning restore 649
#region Private Classes
[Export(typeof(SledLuaEnvVarsEditor))]
[PartCreationPolicy(CreationPolicy.Shared)]
private class SledLuaEnvVarsEditor : SledLuaTreeListViewEditor
{
[ImportingConstructor]
public SledLuaEnvVarsEditor()
: base(
Localization.SledLuaEnvironmentTitle,
null,
SledLuaVarBaseType.ColumnNames,
StandardControlGroup.Right)
{
}
}
#endregion
}
}
| |
namespace FileDialogs
{
partial class FileDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FileDialog));
this.lookInLabel = new System.Windows.Forms.Label();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.backToolStripSplitButton = new System.Windows.Forms.ToolStripSplitButton();
this.upOneLevelToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.searchTheWebToolStripButton = new System.Windows.Forms.ToolStripButton();
this.deleteToolStripButton = new System.Windows.Forms.ToolStripButton();
this.createNewFolderToolStripButton = new System.Windows.Forms.ToolStripButton();
this.viewsToolStripSplitButton = new System.Windows.Forms.ToolStripSplitButton();
this.thumbnailsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sideBySideToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.iconsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.listToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.detailsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.renameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.connectNetworkDriveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.propertyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fileNameLabel = new System.Windows.Forms.Label();
this.fileNameComboBox = new System.Windows.Forms.ComboBox();
this.fileTypeLabel = new System.Windows.Forms.Label();
this.fileTypeComboBox = new System.Windows.Forms.ComboBox();
this.okButton = new FileDialogs.SplitButton();
this.cancelButton = new System.Windows.Forms.Button();
this.placesBar = new System.Windows.Forms.ToolStrip();
this.lookInComboBox = new FileDialogs.LookInComboBox();
this.toolStrip.SuspendLayout();
this.SuspendLayout();
//
// lookInLabel
//
this.lookInLabel.AutoSize = true;
this.lookInLabel.Location = new System.Drawing.Point(35, 6);
this.lookInLabel.Name = "lookInLabel";
this.lookInLabel.Size = new System.Drawing.Size(44, 13);
this.lookInLabel.TabIndex = 6;
this.lookInLabel.Text = "Look &in:";
//
// toolStrip
//
this.toolStrip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.toolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.backToolStripSplitButton,
this.upOneLevelToolStripButton,
this.toolStripSeparator1,
this.searchTheWebToolStripButton,
this.deleteToolStripButton,
this.createNewFolderToolStripButton,
this.viewsToolStripSplitButton,
this.toolsToolStripDropDownButton});
this.toolStrip.Location = new System.Drawing.Point(333, 3);
this.toolStrip.Name = "toolStrip";
this.toolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.toolStrip.Size = new System.Drawing.Size(210, 25);
this.toolStrip.TabIndex = 8;
this.toolStrip.TabStop = true;
//
// backToolStripSplitButton
//
this.backToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.backToolStripSplitButton.Enabled = false;
this.backToolStripSplitButton.Image = ((System.Drawing.Image)(resources.GetObject("backToolStripSplitButton.Image")));
this.backToolStripSplitButton.ImageTransparentColor = System.Drawing.Color.Transparent;
this.backToolStripSplitButton.Name = "backToolStripSplitButton";
this.backToolStripSplitButton.Size = new System.Drawing.Size(32, 22);
this.backToolStripSplitButton.ButtonClick += new System.EventHandler(this.backToolStripSplitButton_ButtonClick);
this.backToolStripSplitButton.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.backToolStripSplitButton_DropDownItemClicked);
//
// upOneLevelToolStripButton
//
this.upOneLevelToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.upOneLevelToolStripButton.Enabled = false;
this.upOneLevelToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("upOneLevelToolStripButton.Image")));
this.upOneLevelToolStripButton.ImageTransparentColor = System.Drawing.Color.Transparent;
this.upOneLevelToolStripButton.Name = "upOneLevelToolStripButton";
this.upOneLevelToolStripButton.Size = new System.Drawing.Size(23, 22);
this.upOneLevelToolStripButton.ToolTipText = "Up One Level (Alt+2)";
this.upOneLevelToolStripButton.Click += new System.EventHandler(this.upOneLevelToolStripButton_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// searchTheWebToolStripButton
//
this.searchTheWebToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.searchTheWebToolStripButton.Enabled = false;
this.searchTheWebToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("searchTheWebToolStripButton.Image")));
this.searchTheWebToolStripButton.ImageTransparentColor = System.Drawing.Color.Transparent;
this.searchTheWebToolStripButton.Name = "searchTheWebToolStripButton";
this.searchTheWebToolStripButton.Size = new System.Drawing.Size(23, 22);
this.searchTheWebToolStripButton.ToolTipText = "Search the Web (Alt+3)";
//
// deleteToolStripButton
//
this.deleteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.deleteToolStripButton.Enabled = false;
this.deleteToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("deleteToolStripButton.Image")));
this.deleteToolStripButton.ImageTransparentColor = System.Drawing.Color.Transparent;
this.deleteToolStripButton.Name = "deleteToolStripButton";
this.deleteToolStripButton.Size = new System.Drawing.Size(23, 22);
this.deleteToolStripButton.ToolTipText = "Delete (Del)";
this.deleteToolStripButton.Click += new System.EventHandler(this.deleteToolStripButton_Click);
//
// createNewFolderToolStripButton
//
this.createNewFolderToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.createNewFolderToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("createNewFolderToolStripButton.Image")));
this.createNewFolderToolStripButton.ImageTransparentColor = System.Drawing.Color.Transparent;
this.createNewFolderToolStripButton.Name = "createNewFolderToolStripButton";
this.createNewFolderToolStripButton.Size = new System.Drawing.Size(23, 22);
this.createNewFolderToolStripButton.ToolTipText = "Create New Folder (Alt+5)";
this.createNewFolderToolStripButton.Click += new System.EventHandler(this.createNewFolderToolStripButton_Click);
//
// viewsToolStripSplitButton
//
this.viewsToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.viewsToolStripSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.thumbnailsToolStripMenuItem,
this.sideBySideToolStripMenuItem,
this.iconsToolStripMenuItem,
this.listToolStripMenuItem,
this.detailsToolStripMenuItem});
this.viewsToolStripSplitButton.Image = ((System.Drawing.Image)(resources.GetObject("viewsToolStripSplitButton.Image")));
this.viewsToolStripSplitButton.ImageTransparentColor = System.Drawing.Color.Transparent;
this.viewsToolStripSplitButton.Name = "viewsToolStripSplitButton";
this.viewsToolStripSplitButton.Size = new System.Drawing.Size(32, 22);
this.viewsToolStripSplitButton.ToolTipText = "Views";
this.viewsToolStripSplitButton.ButtonClick += new System.EventHandler(this.viewsToolStripSplitButton_ButtonClick);
this.viewsToolStripSplitButton.DropDownOpening += new System.EventHandler(this.viewsToolStripSplitButton_DropDownOpening);
this.viewsToolStripSplitButton.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.viewsToolStripSplitButton_DropDownItemClicked);
//
// thumbnailsToolStripMenuItem
//
this.thumbnailsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("thumbnailsToolStripMenuItem.Image")));
this.thumbnailsToolStripMenuItem.Name = "thumbnailsToolStripMenuItem";
this.thumbnailsToolStripMenuItem.Size = new System.Drawing.Size(138, 22);
this.thumbnailsToolStripMenuItem.Text = "&Thumbnails";
//
// sideBySideToolStripMenuItem
//
this.sideBySideToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("sideBySideToolStripMenuItem.Image")));
this.sideBySideToolStripMenuItem.Name = "sideBySideToolStripMenuItem";
this.sideBySideToolStripMenuItem.Size = new System.Drawing.Size(138, 22);
this.sideBySideToolStripMenuItem.Text = "Tile&s";
//
// iconsToolStripMenuItem
//
this.iconsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("iconsToolStripMenuItem.Image")));
this.iconsToolStripMenuItem.Name = "iconsToolStripMenuItem";
this.iconsToolStripMenuItem.Size = new System.Drawing.Size(138, 22);
this.iconsToolStripMenuItem.Text = "Ico&ns";
//
// listToolStripMenuItem
//
this.listToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("listToolStripMenuItem.Image")));
this.listToolStripMenuItem.Name = "listToolStripMenuItem";
this.listToolStripMenuItem.Size = new System.Drawing.Size(138, 22);
this.listToolStripMenuItem.Text = "&List";
//
// detailsToolStripMenuItem
//
this.detailsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("detailsToolStripMenuItem.Image")));
this.detailsToolStripMenuItem.Name = "detailsToolStripMenuItem";
this.detailsToolStripMenuItem.Size = new System.Drawing.Size(138, 22);
this.detailsToolStripMenuItem.Text = "&Details";
//
// toolsToolStripDropDownButton
//
this.toolsToolStripDropDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolsToolStripDropDownButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.deleteToolStripMenuItem,
this.renameToolStripMenuItem,
this.connectNetworkDriveToolStripMenuItem,
this.toolStripMenuItem1,
this.propertyToolStripMenuItem});
this.toolsToolStripDropDownButton.Image = ((System.Drawing.Image)(resources.GetObject("toolsToolStripDropDownButton.Image")));
this.toolsToolStripDropDownButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolsToolStripDropDownButton.Name = "toolsToolStripDropDownButton";
this.toolsToolStripDropDownButton.Size = new System.Drawing.Size(45, 22);
this.toolsToolStripDropDownButton.Text = "Too&ls";
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Enabled = false;
this.deleteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("deleteToolStripMenuItem.Image")));
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.ShortcutKeyDisplayString = "Del";
this.deleteToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.deleteToolStripMenuItem.Text = "&Delete";
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripButton_Click);
//
// renameToolStripMenuItem
//
this.renameToolStripMenuItem.Name = "renameToolStripMenuItem";
this.renameToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F2;
this.renameToolStripMenuItem.ShowShortcutKeys = false;
this.renameToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.renameToolStripMenuItem.Text = "&Rename";
this.renameToolStripMenuItem.Visible = false;
this.renameToolStripMenuItem.Click += new System.EventHandler(this.renameToolStripMenuItem_Click);
//
// connectNetworkDriveToolStripMenuItem
//
this.connectNetworkDriveToolStripMenuItem.Name = "connectNetworkDriveToolStripMenuItem";
this.connectNetworkDriveToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.connectNetworkDriveToolStripMenuItem.Text = "Map &Network Drive...";
this.connectNetworkDriveToolStripMenuItem.Click += new System.EventHandler(this.connectNetworkDriveToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(185, 6);
this.toolStripMenuItem1.Visible = false;
//
// propertyToolStripMenuItem
//
this.propertyToolStripMenuItem.Name = "propertyToolStripMenuItem";
this.propertyToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.propertyToolStripMenuItem.Text = "&Properties";
this.propertyToolStripMenuItem.Visible = false;
this.propertyToolStripMenuItem.Click += new System.EventHandler(this.propertyToolStripMenuItem_Click);
//
// fileNameLabel
//
this.fileNameLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.fileNameLabel.AutoSize = true;
this.fileNameLabel.Location = new System.Drawing.Point(95, 310);
this.fileNameLabel.Name = "fileNameLabel";
this.fileNameLabel.Size = new System.Drawing.Size(56, 13);
this.fileNameLabel.TabIndex = 0;
this.fileNameLabel.Text = "File &name:";
//
// fileNameComboBox
//
this.fileNameComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileNameComboBox.FormattingEnabled = true;
this.fileNameComboBox.Location = new System.Drawing.Point(171, 309);
this.fileNameComboBox.Name = "fileNameComboBox";
this.fileNameComboBox.Size = new System.Drawing.Size(299, 21);
this.fileNameComboBox.TabIndex = 1;
this.fileNameComboBox.TextChanged += new System.EventHandler(this.fileNameComboBox_TextChanged);
//
// fileTypeLabel
//
this.fileTypeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.fileTypeLabel.AutoSize = true;
this.fileTypeLabel.Location = new System.Drawing.Point(95, 336);
this.fileTypeLabel.Name = "fileTypeLabel";
this.fileTypeLabel.Size = new System.Drawing.Size(70, 13);
this.fileTypeLabel.TabIndex = 2;
this.fileTypeLabel.Text = "Files of &type:";
//
// fileTypeComboBox
//
this.fileTypeComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.fileTypeComboBox.FormattingEnabled = true;
this.fileTypeComboBox.Location = new System.Drawing.Point(171, 335);
this.fileTypeComboBox.Name = "fileTypeComboBox";
this.fileTypeComboBox.Size = new System.Drawing.Size(299, 21);
this.fileTypeComboBox.TabIndex = 3;
this.fileTypeComboBox.SelectionChangeCommitted += new System.EventHandler(this.fileTypeComboBox_SelectionChangeCommitted);
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.AutoSize = true;
this.okButton.Location = new System.Drawing.Point(491, 309);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(96, 23);
this.okButton.TabIndex = 4;
this.okButton.Text = "&Open";
this.okButton.UseVisualStyleBackColor = true;
this.okButton.Click += new System.EventHandler(this.okButton_Click);
this.okButton.EnabledChanged += new System.EventHandler(this.okButton_EnabledChanged);
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(492, 334);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(95, 22);
this.cancelButton.TabIndex = 5;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// placesBar
//
this.placesBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.placesBar.AutoSize = false;
this.placesBar.Dock = System.Windows.Forms.DockStyle.None;
this.placesBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.placesBar.ImageScalingSize = new System.Drawing.Size(32, 32);
this.placesBar.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow;
this.placesBar.Location = new System.Drawing.Point(5, 28);
this.placesBar.Name = "placesBar";
this.placesBar.Padding = new System.Windows.Forms.Padding(0, 1, 0, 0);
this.placesBar.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.placesBar.Size = new System.Drawing.Size(87, 327);
this.placesBar.Stretch = true;
this.placesBar.TabIndex = 10;
this.placesBar.TabStop = true;
this.placesBar.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.placesStrip_ItemClicked);
//
// lookInComboBox
//
this.lookInComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lookInComboBox.CurrentItem = null;
this.lookInComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lookInComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.lookInComboBox.FormattingEnabled = true;
this.lookInComboBox.Location = new System.Drawing.Point(98, 3);
this.lookInComboBox.Name = "lookInComboBox";
this.lookInComboBox.Size = new System.Drawing.Size(216, 22);
this.lookInComboBox.TabIndex = 7;
this.lookInComboBox.SelectionChangeCommitted += new System.EventHandler(this.lookInComboBox_SelectionChangeCommitted);
this.lookInComboBox.DropDown += new System.EventHandler(this.lookInComboBox_DropDown);
//
// FileDialog
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(593, 359);
this.Controls.Add(this.placesBar);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.fileTypeComboBox);
this.Controls.Add(this.fileTypeLabel);
this.Controls.Add(this.fileNameComboBox);
this.Controls.Add(this.fileNameLabel);
this.Controls.Add(this.toolStrip);
this.Controls.Add(this.lookInComboBox);
this.Controls.Add(this.lookInLabel);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(601, 393);
this.Name = "FileDialog";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private FileDialogs.LookInComboBox lookInComboBox;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripSplitButton backToolStripSplitButton;
private System.Windows.Forms.ToolStripButton upOneLevelToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton deleteToolStripButton;
private System.Windows.Forms.ToolStripButton createNewFolderToolStripButton;
private System.Windows.Forms.ToolStripDropDownButton toolsToolStripDropDownButton;
private System.Windows.Forms.ToolStripMenuItem thumbnailsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sideBySideToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem iconsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem listToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem detailsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem renameToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem propertyToolStripMenuItem;
internal System.Windows.Forms.ComboBox fileTypeComboBox;
private System.Windows.Forms.ToolStrip placesBar;
private System.Windows.Forms.ToolStripMenuItem connectNetworkDriveToolStripMenuItem;
internal System.Windows.Forms.ComboBox fileNameComboBox;
internal FileDialogs.SplitButton okButton;
internal System.Windows.Forms.Button cancelButton;
internal System.Windows.Forms.Label lookInLabel;
internal System.Windows.Forms.Label fileNameLabel;
internal System.Windows.Forms.Label fileTypeLabel;
internal System.Windows.Forms.ToolStripButton searchTheWebToolStripButton;
internal System.Windows.Forms.ToolStripSplitButton viewsToolStripSplitButton;
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Aurora.DataManager;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Services.Connectors;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services.UserAccountService
{
public class UserAccountService : ConnectorBase, IUserAccountService, IService
{
#region Declares
protected IAuthenticationService m_AuthenticationService;
protected IUserAccountData m_Database;
protected IGridService m_GridService;
protected IInventoryService m_InventoryService;
protected GenericAccountCache<UserAccount> m_cache = new GenericAccountCache<UserAccount>();
#endregion
#region IService Members
public virtual string Name
{
get { return GetType().Name; }
}
public void Initialize(IConfigSource config, IRegistryCore registry)
{
IConfig handlerConfig = config.Configs["Handlers"];
if (handlerConfig.GetString("UserAccountHandler", "") != Name)
return;
Configure(config, registry);
Init(registry, Name);
}
public void Configure(IConfigSource config, IRegistryCore registry)
{
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand(
"create user",
"create user [<first> [<last> [<pass> [<email>]]]]",
"Create a new user", HandleCreateUser);
MainConsole.Instance.Commands.AddCommand("reset user password",
"reset user password [<first> [<last> [<password>]]]",
"Reset a user password", HandleResetUserPassword);
MainConsole.Instance.Commands.AddCommand(
"show account",
"show account <first> <last>",
"Show account details for the given user", HandleShowAccount);
MainConsole.Instance.Commands.AddCommand(
"set user level",
"set user level [<first> [<last> [<level>]]]",
"Set user level. If the user's level is > 0, "
+ "this account will be treated as god-moded. "
+ "It will also affect the 'login level' command. ",
HandleSetUserLevel);
MainConsole.Instance.Commands.AddCommand(
"set user profile title",
"set user profile title [<first> [<last> [<Title>]]]",
"Sets the title (Normally resident) in a user's title to some custom value.",
HandleSetTitle);
MainConsole.Instance.Commands.AddCommand(
"set partner",
"set partner",
"Sets the partner in a user's profile.",
HandleSetPartner);
}
registry.RegisterModuleInterface<IUserAccountService>(this);
}
public void Start(IConfigSource config, IRegistryCore registry)
{
m_GridService = registry.RequestModuleInterface<IGridService>();
m_AuthenticationService = registry.RequestModuleInterface<IAuthenticationService>();
m_InventoryService = registry.RequestModuleInterface<IInventoryService>();
m_Database = DataManager.RequestPlugin<IUserAccountData>();
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
}
public void FinishedStartup()
{
}
#endregion
#region IUserAccountService Members
public virtual IUserAccountService InnerService
{
get { return this; }
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public UserAccount GetUserAccount(List<UUID> scopeIDs, string firstName, string lastName)
{
UserAccount account;
if (m_cache.Get(firstName + " " + lastName, out account))
return AllScopeIDImpl.CheckScopeIDs(scopeIDs, account);
object remoteValue = DoRemote(scopeIDs, firstName, lastName);
if (remoteValue != null || m_doRemoteOnly)
{
UserAccount acc = (UserAccount)remoteValue;
if (remoteValue != null)
m_cache.Cache(acc.PrincipalID, acc);
return acc;
}
UserAccount[] d;
d = m_Database.Get(scopeIDs,
new[] {"FirstName", "LastName"},
new[] {firstName, lastName});
if (d.Length < 1)
return null;
CacheAccount(d[0]);
return d[0];
}
public void CacheAccount(UserAccount account)
{
if ((account != null) && (account.UserLevel <= -1))
return;
m_cache.Cache(account.PrincipalID, account);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public UserAccount GetUserAccount(List<UUID> scopeIDs, string name)
{
UserAccount account;
if (m_cache.Get(name, out account))
return AllScopeIDImpl.CheckScopeIDs(scopeIDs, account);
object remoteValue = DoRemote(scopeIDs, name);
if (remoteValue != null || m_doRemoteOnly)
{
UserAccount acc = (UserAccount)remoteValue;
if (remoteValue != null)
m_cache.Cache(acc.PrincipalID, acc);
return acc;
}
UserAccount[] d;
d = m_Database.Get(scopeIDs,
new[] {"Name"},
new[] {name});
if (d.Length < 1)
{
string[] split = name.Split(' ');
if (split.Length == 2)
return GetUserAccount(scopeIDs, split[0], split[1]);
return null;
}
CacheAccount(d[0]);
return d[0];
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low, RenamedMethod="GetUserAccountUUID")]
public UserAccount GetUserAccount(List<UUID> scopeIDs, UUID principalID)
{
UserAccount account;
if (m_cache.Get(principalID, out account))
return AllScopeIDImpl.CheckScopeIDs(scopeIDs, account);
object remoteValue = DoRemote(scopeIDs, principalID);
if (remoteValue != null || m_doRemoteOnly)
{
UserAccount acc = (UserAccount)remoteValue;
if (remoteValue != null)
m_cache.Cache(principalID, acc);
return acc;
}
UserAccount[] d;
d = m_Database.Get(scopeIDs,
new[] {"PrincipalID"},
new[] {principalID.ToString()});
if (d.Length < 1)
{
m_cache.Cache(principalID, null);
return null;
}
CacheAccount(d[0]);
return d[0];
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public bool StoreUserAccount(UserAccount data)
{
object remoteValue = DoRemote(data);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
if (data.UserTitle == null)
data.UserTitle = "";
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UpdateUserInformation", data.PrincipalID);
return m_Database.Store(data);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, string query)
{
object remoteValue = DoRemote(scopeIDs, query);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserAccount>)remoteValue;
UserAccount[] d = m_Database.GetUsers(scopeIDs, query);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>(d);
return ret;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, string query, uint? start, uint? count)
{
object remoteValue = DoRemote(scopeIDs, query);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserAccount>)remoteValue;
UserAccount[] d = m_Database.GetUsers(scopeIDs, query, start, count);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>(d);
return ret;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, int level, int flags)
{
object remoteValue = DoRemote(level, flags);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserAccount>)remoteValue;
UserAccount[] d = m_Database.GetUsers(scopeIDs, level, flags);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>(d);
return ret;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public uint NumberOfUserAccounts(List<UUID> scopeIDs, string query)
{
object remoteValue = DoRemote(scopeIDs, query);
if (remoteValue != null || m_doRemoteOnly)
return (uint)remoteValue;
return m_Database.NumberOfUsers(scopeIDs, query);
}
public void CreateUser(string name, string password, string email)
{
CreateUser(UUID.Random(), UUID.Zero, name, password, email);
}
/// <summary>
/// Create a user
/// </summary>
/// <param name = "firstName"></param>
/// <param name = "lastName"></param>
/// <param name = "password"></param>
/// <param name = "email"></param>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public string CreateUser(UUID userID, UUID scopeID, string name, string password, string email)
{
return CreateUser(new UserAccount(scopeID, userID, name, email), password);
}
/// <summary>
/// Create a user
/// </summary>
/// <param name = "account"></param>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public string CreateUser(UserAccount newAcc, string password)
{
object remoteValue = DoRemote(newAcc, password);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? "" : remoteValue.ToString();
UserAccount account = GetUserAccount(null, newAcc.PrincipalID);
UserAccount nameaccount = GetUserAccount(null, newAcc.Name);
if (null == account && nameaccount == null)
{
if (StoreUserAccount(newAcc))
{
bool success;
if (m_AuthenticationService != null && password != "")
{
success = m_AuthenticationService.SetPasswordHashed(newAcc.PrincipalID, "UserAccount", password);
if (!success)
{
MainConsole.Instance.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0}.",
newAcc.Name);
return "Unable to set password";
}
}
MainConsole.Instance.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} created successfully", newAcc.Name);
//Cache it as well
CacheAccount(newAcc);
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("CreateUserInformation", newAcc.PrincipalID);
return "";
}
else
{
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0}", newAcc.Name);
return "Unable to save account";
}
}
else
{
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} already exists!", newAcc.Name);
return "A user with the same name already exists";
}
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public void DeleteUser(UUID userID, string password, bool archiveInformation, bool wipeFromDatabase)
{
object remoteValue = DoRemote(userID, password, archiveInformation, wipeFromDatabase);
if (remoteValue != null || m_doRemoteOnly)
return;
if (password != "" && m_AuthenticationService.Authenticate(userID, "UserAccount", password, 0) == "")
return;//Not authed
if (!m_Database.DeleteAccount(userID, archiveInformation))
{
MainConsole.Instance.WarnFormat("Failed to remove the account for {0}, please check that the database is valid after this operation!", userID);
return;
}
if(wipeFromDatabase)
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("DeleteUserInformation", userID);
}
#endregion
#region Console commands
protected void HandleSetPartner(string[] cmdParams)
{
string first = MainConsole.Instance.Prompt("First User's name");
string second = MainConsole.Instance.Prompt("Second User's name");
IProfileConnector profileConnector = Aurora.DataManager.DataManager.RequestPlugin<IProfileConnector>();
if (profileConnector != null)
{
IUserProfileInfo firstProfile = profileConnector.GetUserProfile(GetUserAccount(null, first).PrincipalID);
IUserProfileInfo secondProfile = profileConnector.GetUserProfile(GetUserAccount(null, second).PrincipalID);
firstProfile.Partner = secondProfile.PrincipalID;
secondProfile.Partner = firstProfile.PrincipalID;
profileConnector.UpdateUserProfile(firstProfile);
profileConnector.UpdateUserProfile(secondProfile);
MainConsole.Instance.Warn("Partner information updated. ");
}
}
protected void HandleSetTitle(string[] cmdparams)
{
string firstName;
string lastName;
string title;
firstName = cmdparams.Length < 5 ? MainConsole.Instance.Prompt("First name") : cmdparams[4];
lastName = cmdparams.Length < 6 ? MainConsole.Instance.Prompt("Last name") : cmdparams[5];
UserAccount account = GetUserAccount(null, firstName, lastName);
if (account == null)
{
MainConsole.Instance.Info("No such user");
return;
}
title = cmdparams.Length < 7 ? MainConsole.Instance.Prompt("User Title") : Util.CombineParams(cmdparams, 6);
account.UserTitle = title;
Aurora.Framework.IProfileConnector profileConnector = Aurora.DataManager.DataManager.RequestPlugin<Aurora.Framework.IProfileConnector>();
if (profileConnector != null)
{
Aurora.Framework.IUserProfileInfo profile = profileConnector.GetUserProfile(account.PrincipalID);
profile.MembershipGroup = title;
profile.CustomType = title;
profileConnector.UpdateUserProfile(profile);
}
bool success = StoreUserAccount(account);
if (!success)
MainConsole.Instance.InfoFormat("Unable to set user profile title for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.InfoFormat("User profile title set for user {0} {1} to {2}", firstName, lastName, title);
}
protected void HandleSetUserLevel(string[] cmdparams)
{
string firstName;
string lastName;
string rawLevel;
int level;
firstName = cmdparams.Length < 4 ? MainConsole.Instance.Prompt("First name") : cmdparams[3];
lastName = cmdparams.Length < 5 ? MainConsole.Instance.Prompt("Last name") : cmdparams[4];
UserAccount account = GetUserAccount(null, firstName, lastName);
if (account == null)
{
MainConsole.Instance.Info("No such user");
return;
}
rawLevel = cmdparams.Length < 6 ? MainConsole.Instance.Prompt("User level") : cmdparams[5];
if (int.TryParse(rawLevel, out level) == false)
{
MainConsole.Instance.Info("Invalid user level");
return;
}
account.UserLevel = level;
bool success = StoreUserAccount(account);
if (!success)
MainConsole.Instance.InfoFormat("Unable to set user level for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.InfoFormat("User level set for user {0} {1} to {2}", firstName, lastName, level);
}
protected void HandleShowAccount(string[] cmdparams)
{
if (cmdparams.Length != 4)
{
MainConsole.Instance.Output("Usage: show account <first-name> <last-name>");
return;
}
string firstName = cmdparams[2];
string lastName = cmdparams[3];
UserAccount ua = GetUserAccount(null, firstName, lastName);
if (ua == null)
{
MainConsole.Instance.InfoFormat("No user named {0} {1}", firstName, lastName);
return;
}
MainConsole.Instance.InfoFormat("Name: {0}", ua.Name);
MainConsole.Instance.InfoFormat("ID: {0}", ua.PrincipalID);
MainConsole.Instance.InfoFormat("Title: {0}", ua.UserTitle);
MainConsole.Instance.InfoFormat("E-mail: {0}", ua.Email);
MainConsole.Instance.InfoFormat("Created: {0}", Utils.UnixTimeToDateTime(ua.Created));
MainConsole.Instance.InfoFormat("Level: {0}", ua.UserLevel);
MainConsole.Instance.InfoFormat("Flags: {0}", ua.UserFlags);
}
/// <summary>
/// Handle the create user command from the console.
/// </summary>
/// <param name = "cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param>
protected void HandleCreateUser(string[] cmdparams)
{
string name, password, email, uuid, scopeID;
name = MainConsole.Instance.Prompt("Name", "Default User");
password = MainConsole.Instance.PasswordPrompt("Password");
email = MainConsole.Instance.Prompt("Email", "");
uuid = MainConsole.Instance.Prompt("UUID (Don't change unless you have a reason)", UUID.Random().ToString());
scopeID = MainConsole.Instance.Prompt("Scope (Don't change unless you know what this is)", UUID.Zero.ToString());
CreateUser(UUID.Parse(uuid), UUID.Parse(scopeID), name, Util.Md5Hash(password), email);
}
protected void HandleResetUserPassword(string[] cmdparams)
{
string name;
string newPassword;
name = MainConsole.Instance.Prompt("Name");
newPassword = MainConsole.Instance.PasswordPrompt("New password");
UserAccount account = GetUserAccount(null, name);
if (account == null)
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: No such user");
bool success = false;
if (m_AuthenticationService != null)
success = m_AuthenticationService.SetPassword(account.PrincipalID, "UserAccount", newPassword);
if (!success)
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: Unable to reset password for account {0}.",
name);
else
MainConsole.Instance.InfoFormat("[USER ACCOUNT SERVICE]: Password reset for user {0}", name);
}
#endregion
}
}
| |
//
// RSAManaged.cs - Implements the RSA algorithm.
//
// Authors:
// Sebastien Pouliot (sebastien@ximian.com)
// Ben Maurer (bmaurer@users.sf.net)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Portions (C) 2003 Ben Maurer
// Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com)
//
// Key generation translated from Bouncy Castle JCE (http://www.bouncycastle.org/)
// See bouncycastle.txt for license.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using System.Text;
using Mono.Math;
// Big chunks of code are coming from the original RSACryptoServiceProvider class.
// The class was refactored to :
// a. ease integration of new hash algorithm (like MD2, RIPEMD160, ...);
// b. provide better support for the coming SSL implementation (requires
// EncryptValue/DecryptValue) with, or without, Mono runtime/corlib;
// c. provide an alternative RSA implementation for all Windows (like using
// OAEP without Windows XP).
namespace Mono.Security.Cryptography {
internal class RSAManaged : RSA {
private const int defaultKeySize = 1024;
private bool isCRTpossible = false;
private bool keyBlinding = true;
private bool keypairGenerated = false;
private bool m_disposed = false;
private BigInteger d;
private BigInteger p;
private BigInteger q;
private BigInteger dp;
private BigInteger dq;
private BigInteger qInv;
private BigInteger n; // modulus
private BigInteger e;
public RSAManaged () : this (defaultKeySize)
{
}
public RSAManaged (int keySize)
{
LegalKeySizesValue = new KeySizes [1];
LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
base.KeySize = keySize;
}
~RSAManaged ()
{
// Zeroize private key
Dispose (false);
}
private void GenerateKeyPair ()
{
// p and q values should have a length of half the strength in bits
int pbitlength = ((KeySize + 1) >> 1);
int qbitlength = (KeySize - pbitlength);
const uint uint_e = 17;
e = uint_e; // fixed
// generate p, prime and (p-1) relatively prime to e
for (;;) {
p = BigInteger.GeneratePseudoPrime (pbitlength);
if (p % uint_e != 1)
break;
}
// generate a modulus of the required length
for (;;) {
// generate q, prime and (q-1) relatively prime to e,
// and not equal to p
for (;;) {
q = BigInteger.GeneratePseudoPrime (qbitlength);
if ((q % uint_e != 1) && (p != q))
break;
}
// calculate the modulus
n = p * q;
if (n.BitCount () == KeySize)
break;
// if we get here our primes aren't big enough, make the largest
// of the two p and try again
if (p < q)
p = q;
}
BigInteger pSub1 = (p - 1);
BigInteger qSub1 = (q - 1);
BigInteger phi = pSub1 * qSub1;
// calculate the private exponent
d = e.ModInverse (phi);
// calculate the CRT factors
dp = d % pSub1;
dq = d % qSub1;
qInv = q.ModInverse (p);
keypairGenerated = true;
isCRTpossible = true;
if (KeyGenerated != null)
KeyGenerated (this, null);
}
// overrides from RSA class
public override int KeySize {
get {
if (m_disposed)
throw new ObjectDisposedException (Locale.GetText ("Keypair was disposed"));
// in case keypair hasn't been (yet) generated
if (keypairGenerated) {
int ks = n.BitCount ();
if ((ks & 7) != 0)
ks = ks + (8 - (ks & 7));
return ks;
}
else
return base.KeySize;
}
}
public override string KeyExchangeAlgorithm {
get { return "RSA-PKCS1-KeyEx"; }
}
// note: when (if) we generate a keypair then it will have both
// the public and private keys
public bool PublicOnly {
get { return (keypairGenerated && ((d == null) || (n == null))); }
}
public override string SignatureAlgorithm {
get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
}
public override byte[] DecryptValue (byte[] rgb)
{
if (m_disposed)
throw new ObjectDisposedException ("private key");
// decrypt operation is used for signature
if (!keypairGenerated)
GenerateKeyPair ();
BigInteger input = new BigInteger (rgb);
BigInteger r = null;
// we use key blinding (by default) against timing attacks
if (keyBlinding) {
// x = (r^e * g) mod n
// *new* random number (so it's timing is also random)
r = BigInteger.GenerateRandom (n.BitCount ());
input = r.ModPow (e, n) * input % n;
}
BigInteger output;
// decrypt (which uses the private key) can be
// optimized by using CRT (Chinese Remainder Theorem)
if (isCRTpossible) {
// m1 = c^dp mod p
BigInteger m1 = input.ModPow (dp, p);
// m2 = c^dq mod q
BigInteger m2 = input.ModPow (dq, q);
BigInteger h;
if (m2 > m1) {
// thanks to benm!
h = p - ((m2 - m1) * qInv % p);
output = m2 + q * h;
} else {
// h = (m1 - m2) * qInv mod p
h = (m1 - m2) * qInv % p;
// m = m2 + q * h;
output = m2 + q * h;
}
} else if (!PublicOnly) {
// m = c^d mod n
output = input.ModPow (d, n);
} else {
throw new CryptographicException (Locale.GetText ("Missing private key to decrypt value."));
}
if (keyBlinding) {
// Complete blinding
// x^e / r mod n
output = output * r.ModInverse (n) % n;
r.Clear ();
}
// it's sometimes possible for the results to be a byte short
// and this can break some software (see #79502) so we 0x00 pad the result
byte[] result = GetPaddedValue (output, (KeySize >> 3));
// zeroize values
input.Clear ();
output.Clear ();
return result;
}
public override byte[] EncryptValue (byte[] rgb)
{
if (m_disposed)
throw new ObjectDisposedException ("public key");
if (!keypairGenerated)
GenerateKeyPair ();
BigInteger input = new BigInteger (rgb);
BigInteger output = input.ModPow (e, n);
// it's sometimes possible for the results to be a byte short
// and this can break some software (see #79502) so we 0x00 pad the result
byte[] result = GetPaddedValue (output, (KeySize >> 3));
// zeroize value
input.Clear ();
output.Clear ();
return result;
}
public override RSAParameters ExportParameters (bool includePrivateParameters)
{
if (m_disposed)
throw new ObjectDisposedException (Locale.GetText ("Keypair was disposed"));
if (!keypairGenerated)
GenerateKeyPair ();
RSAParameters param = new RSAParameters ();
param.Exponent = e.GetBytes ();
param.Modulus = n.GetBytes ();
if (includePrivateParameters) {
// some parameters are required for exporting the private key
if (d == null)
throw new CryptographicException ("Missing private key");
param.D = d.GetBytes ();
// hack for bugzilla #57941 where D wasn't provided
if (param.D.Length != param.Modulus.Length) {
byte[] normalizedD = new byte [param.Modulus.Length];
Buffer.BlockCopy (param.D, 0, normalizedD, (normalizedD.Length - param.D.Length), param.D.Length);
param.D = normalizedD;
}
// but CRT parameters are optionals
if ((p != null) && (q != null) && (dp != null) && (dq != null) && (qInv != null)) {
// and we include them only if we have them all
int length = (KeySize >> 4);
param.P = GetPaddedValue (p, length);
param.Q = GetPaddedValue (q, length);
param.DP = GetPaddedValue (dp, length);
param.DQ = GetPaddedValue (dq, length);
param.InverseQ = GetPaddedValue (qInv, length);
}
}
return param;
}
public override void ImportParameters (RSAParameters parameters)
{
if (m_disposed)
throw new ObjectDisposedException (Locale.GetText ("Keypair was disposed"));
// if missing "mandatory" parameters
if (parameters.Exponent == null)
throw new CryptographicException (Locale.GetText ("Missing Exponent"));
if (parameters.Modulus == null)
throw new CryptographicException (Locale.GetText ("Missing Modulus"));
e = new BigInteger (parameters.Exponent);
n = new BigInteger (parameters.Modulus);
//reset all private key values to null
d = dp = dq = qInv = p = q = null;
// only if the private key is present
if (parameters.D != null)
d = new BigInteger (parameters.D);
if (parameters.DP != null)
dp = new BigInteger (parameters.DP);
if (parameters.DQ != null)
dq = new BigInteger (parameters.DQ);
if (parameters.InverseQ != null)
qInv = new BigInteger (parameters.InverseQ);
if (parameters.P != null)
p = new BigInteger (parameters.P);
if (parameters.Q != null)
q = new BigInteger (parameters.Q);
// we now have a keypair
keypairGenerated = true;
bool privateKey = ((p != null) && (q != null) && (dp != null));
isCRTpossible = (privateKey && (dq != null) && (qInv != null));
// check if the public/private keys match
// the way the check is made allows a bad D to work if CRT is available (like MS does, see unit tests)
if (!privateKey)
return;
// always check n == p * q
bool ok = (n == (p * q));
if (ok) {
// we now know that p and q are correct, so (p - 1), (q - 1) and phi will be ok too
BigInteger pSub1 = (p - 1);
BigInteger qSub1 = (q - 1);
BigInteger phi = pSub1 * qSub1;
// e is fairly static but anyway we can ensure it makes sense by recomputing d
BigInteger dcheck = e.ModInverse (phi);
// now if our new d(check) is different than the d we're provided then we cannot
// be sure if 'd' or 'e' is invalid... (note that, from experience, 'd' is more
// likely to be invalid since it's twice as large as DP (or DQ) and sits at the
// end of the structure (e.g. truncation).
ok = (d == dcheck);
// ... unless we have the pre-computed CRT parameters
if (!ok && isCRTpossible) {
// we can override the previous decision since Mono always prefer, for
// performance reasons, using the CRT algorithm
ok = (dp == (dcheck % pSub1)) && (dq == (dcheck % qSub1)) &&
(qInv == q.ModInverse (p));
}
}
if (!ok)
throw new CryptographicException (Locale.GetText ("Private/public key mismatch"));
}
protected override void Dispose (bool disposing)
{
if (!m_disposed) {
// Always zeroize private key
if (d != null) {
d.Clear ();
d = null;
}
if (p != null) {
p.Clear ();
p = null;
}
if (q != null) {
q.Clear ();
q = null;
}
if (dp != null) {
dp.Clear ();
dp = null;
}
if (dq != null) {
dq.Clear ();
dq = null;
}
if (qInv != null) {
qInv.Clear ();
qInv = null;
}
if (disposing) {
// clear public key
if (e != null) {
e.Clear ();
e = null;
}
if (n != null) {
n.Clear ();
n = null;
}
}
}
// call base class
// no need as they all are abstract before us
m_disposed = true;
}
public delegate void KeyGeneratedEventHandler (object sender, EventArgs e);
public event KeyGeneratedEventHandler KeyGenerated;
public override string ToXmlString (bool includePrivateParameters)
{
StringBuilder sb = new StringBuilder ();
RSAParameters rsaParams = ExportParameters (includePrivateParameters);
try {
sb.Append ("<RSAKeyValue>");
sb.Append ("<Modulus>");
sb.Append (Convert.ToBase64String (rsaParams.Modulus));
sb.Append ("</Modulus>");
sb.Append ("<Exponent>");
sb.Append (Convert.ToBase64String (rsaParams.Exponent));
sb.Append ("</Exponent>");
if (includePrivateParameters) {
if (rsaParams.P != null) {
sb.Append ("<P>");
sb.Append (Convert.ToBase64String (rsaParams.P));
sb.Append ("</P>");
}
if (rsaParams.Q != null) {
sb.Append ("<Q>");
sb.Append (Convert.ToBase64String (rsaParams.Q));
sb.Append ("</Q>");
}
if (rsaParams.DP != null) {
sb.Append ("<DP>");
sb.Append (Convert.ToBase64String (rsaParams.DP));
sb.Append ("</DP>");
}
if (rsaParams.DQ != null) {
sb.Append ("<DQ>");
sb.Append (Convert.ToBase64String (rsaParams.DQ));
sb.Append ("</DQ>");
}
if (rsaParams.InverseQ != null) {
sb.Append ("<InverseQ>");
sb.Append (Convert.ToBase64String (rsaParams.InverseQ));
sb.Append ("</InverseQ>");
}
sb.Append ("<D>");
sb.Append (Convert.ToBase64String (rsaParams.D));
sb.Append ("</D>");
}
sb.Append ("</RSAKeyValue>");
}
catch {
if (rsaParams.P != null)
Array.Clear (rsaParams.P, 0, rsaParams.P.Length);
if (rsaParams.Q != null)
Array.Clear (rsaParams.Q, 0, rsaParams.Q.Length);
if (rsaParams.DP != null)
Array.Clear (rsaParams.DP, 0, rsaParams.DP.Length);
if (rsaParams.DQ != null)
Array.Clear (rsaParams.DQ, 0, rsaParams.DQ.Length);
if (rsaParams.InverseQ != null)
Array.Clear (rsaParams.InverseQ, 0, rsaParams.InverseQ.Length);
if (rsaParams.D != null)
Array.Clear (rsaParams.D, 0, rsaParams.D.Length);
throw;
}
return sb.ToString ();
}
// internal for Mono 1.0.x in order to preserve public contract
// they are public for Mono 1.1.x (for 1.2) as the API isn't froze ATM
public bool UseKeyBlinding {
get { return keyBlinding; }
// you REALLY shoudn't touch this (true is fine ;-)
set { keyBlinding = value; }
}
public bool IsCrtPossible {
// either the key pair isn't generated (and will be
// generated with CRT parameters) or CRT is (or isn't)
// possible (in case the key was imported)
get { return (!keypairGenerated || isCRTpossible); }
}
private byte[] GetPaddedValue (BigInteger value, int length)
{
byte[] result = value.GetBytes ();
if (result.Length >= length)
return result;
// left-pad 0x00 value on the result (same integer, correct length)
byte[] padded = new byte[length];
Buffer.BlockCopy (result, 0, padded, (length - result.Length), result.Length);
// temporary result may contain decrypted (plaintext) data, clear it
Array.Clear (result, 0, result.Length);
return padded;
}
}
}
| |
/*
* 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 SearchMailboxesRequest request.
/// </summary>
internal sealed class SearchMailboxesRequest : MultiResponseServiceRequest<SearchMailboxesResponse>, IDiscoveryVersionable
{
private List<MailboxQuery> searchQueries = new List<MailboxQuery>();
private SearchResultType searchResultType = SearchResultType.PreviewOnly;
private SortDirection sortOrder = SortDirection.Ascending;
private string sortByProperty;
private bool performDeduplication;
private int pageSize;
private string pageItemReference;
private SearchPageDirection pageDirection = SearchPageDirection.Next;
private PreviewItemResponseShape previewItemResponseShape;
/// <summary>
/// Initializes a new instance of the <see cref="SearchMailboxesRequest"/> class.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="errorHandlingMode"> Indicates how errors should be handled.</param>
internal SearchMailboxesRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode)
: base(service, errorHandlingMode)
{
}
/// <summary>
/// Creates the service response.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="responseIndex">Index of the response.</param>
/// <returns>Service response.</returns>
internal override SearchMailboxesResponse CreateServiceResponse(ExchangeService service, int responseIndex)
{
return new SearchMailboxesResponse();
}
/// <summary>
/// Gets the name of the response XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetResponseXmlElementName()
{
return XmlElementNames.SearchMailboxesResponse;
}
/// <summary>
/// Gets the name of the response message XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetResponseMessageXmlElementName()
{
return XmlElementNames.SearchMailboxesResponseMessage;
}
/// <summary>
/// Gets the expected response message count.
/// </summary>
/// <returns>Number of expected response messages.</returns>
internal override int GetExpectedResponseMessageCount()
{
return 1;
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetXmlElementName()
{
return XmlElementNames.SearchMailboxes;
}
/// <summary>
/// Validate request.
/// </summary>
internal override void Validate()
{
base.Validate();
if (this.SearchQueries == null || this.SearchQueries.Count == 0)
{
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
foreach (MailboxQuery searchQuery in this.SearchQueries)
{
if (searchQuery.MailboxSearchScopes == null || searchQuery.MailboxSearchScopes.Length == 0)
{
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
foreach (MailboxSearchScope searchScope in searchQuery.MailboxSearchScopes)
{
if (searchScope.ExtendedAttributes != null && searchScope.ExtendedAttributes.Count > 0 && !DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this))
{
throw new ServiceVersionException(
string.Format(
Strings.ClassIncompatibleWithRequestVersion,
typeof(ExtendedAttribute).Name,
DiscoverySchemaChanges.SearchMailboxesExtendedData.MinimumServerVersion));
}
if (searchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN && (!DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this) || !DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this)))
{
throw new ServiceVersionException(
string.Format(
Strings.EnumValueIncompatibleWithRequestVersion,
searchScope.SearchScopeType.ToString(),
typeof(MailboxSearchScopeType).Name,
DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.MinimumServerVersion));
}
}
}
if (!string.IsNullOrEmpty(this.SortByProperty))
{
PropertyDefinitionBase prop = null;
try
{
prop = ServiceObjectSchema.FindPropertyDefinition(this.SortByProperty);
}
catch (KeyNotFoundException)
{
}
if (prop == null)
{
throw new ServiceValidationException(string.Format(Strings.InvalidSortByPropertyForMailboxSearch, this.SortByProperty));
}
}
}
/// <summary>
/// Parses the response.
/// See O15:324151 on why we need to override ParseResponse here instead of calling the one in MultiResponseServiceRequest.cs
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Service response collection.</returns>
internal override object ParseResponse(EwsServiceXmlReader reader)
{
ServiceResponseCollection<SearchMailboxesResponse> serviceResponses = new ServiceResponseCollection<SearchMailboxesResponse>();
reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages);
while (true)
{
// Read ahead to see if we've reached the end of the response messages early.
reader.Read();
if (reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages))
{
break;
}
SearchMailboxesResponse response = new SearchMailboxesResponse();
response.LoadFromXml(reader, this.GetResponseMessageXmlElementName());
serviceResponses.Add(response);
}
reader.ReadEndElementIfNecessary(XmlNamespace.Messages, XmlElementNames.ResponseMessages);
return serviceResponses;
}
/// <summary>
/// Writes XML elements.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SearchQueries);
foreach (MailboxQuery mailboxQuery in this.SearchQueries)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxQuery);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Query, mailboxQuery.Query);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScopes);
foreach (MailboxSearchScope mailboxSearchScope in mailboxQuery.MailboxSearchScopes)
{
// The checks here silently downgrade the schema based on compatability checks, to recieve errors use the validate method
if (mailboxSearchScope.SearchScopeType == MailboxSearchScopeType.LegacyExchangeDN || DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this))
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScope);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Mailbox, mailboxSearchScope.Mailbox);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.SearchScope, mailboxSearchScope.SearchScope);
if (DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this))
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttributes);
if (mailboxSearchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, XmlElementNames.SearchScopeType);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, mailboxSearchScope.SearchScopeType);
writer.WriteEndElement();
}
if (mailboxSearchScope.ExtendedAttributes != null && mailboxSearchScope.ExtendedAttributes.Count > 0)
{
foreach (ExtendedAttribute attribute in mailboxSearchScope.ExtendedAttributes)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, attribute.Name);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, attribute.Value);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // ExtendedData
}
writer.WriteEndElement(); // MailboxSearchScope
}
}
writer.WriteEndElement(); // MailboxSearchScopes
writer.WriteEndElement(); // MailboxQuery
}
writer.WriteEndElement(); // SearchQueries
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.ResultType, this.ResultType);
if (this.PreviewItemResponseShape != null)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.PreviewItemResponseShape);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.BaseShape, this.PreviewItemResponseShape.BaseShape);
if (this.PreviewItemResponseShape.AdditionalProperties != null && this.PreviewItemResponseShape.AdditionalProperties.Length > 0)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties);
foreach (ExtendedPropertyDefinition additionalProperty in this.PreviewItemResponseShape.AdditionalProperties)
{
additionalProperty.WriteToXml(writer);
}
writer.WriteEndElement(); // AdditionalProperties
}
writer.WriteEndElement(); // PreviewItemResponseShape
}
if (!string.IsNullOrEmpty(this.SortByProperty))
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SortBy);
writer.WriteAttributeValue(XmlElementNames.Order, this.SortOrder.ToString());
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.FieldURI);
writer.WriteAttributeValue(XmlElementNames.FieldURI, this.sortByProperty);
writer.WriteEndElement(); // FieldURI
writer.WriteEndElement(); // SortBy
}
// Language
if (!string.IsNullOrEmpty(this.Language))
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Language, this.Language);
}
// Dedupe
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Deduplication, this.performDeduplication);
if (this.PageSize > 0)
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageSize, this.PageSize.ToString());
}
if (!string.IsNullOrEmpty(this.PageItemReference))
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageItemReference, this.PageItemReference);
}
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageDirection, this.PageDirection.ToString());
}
/// <summary>
/// Gets the request version.
/// </summary>
/// <returns>Earliest Exchange version in which this request is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2013;
}
/// <summary>
/// Collection of query + mailboxes
/// </summary>
public List<MailboxQuery> SearchQueries
{
get { return this.searchQueries; }
set { this.searchQueries = value; }
}
/// <summary>
/// Search result type
/// </summary>
public SearchResultType ResultType
{
get { return this.searchResultType; }
set { this.searchResultType = value; }
}
/// <summary>
/// Preview item response shape
/// </summary>
public PreviewItemResponseShape PreviewItemResponseShape
{
get { return this.previewItemResponseShape; }
set { this.previewItemResponseShape = value; }
}
/// <summary>
/// Sort order
/// </summary>
public SortDirection SortOrder
{
get { return this.sortOrder; }
set { this.sortOrder = value; }
}
/// <summary>
/// Sort by property name
/// </summary>
public string SortByProperty
{
get { return this.sortByProperty; }
set { this.sortByProperty = value; }
}
/// <summary>
/// Query language
/// </summary>
public string Language
{
get;
set;
}
/// <summary>
/// Perform deduplication or not
/// </summary>
public bool PerformDeduplication
{
get { return this.performDeduplication; }
set { this.performDeduplication = value; }
}
/// <summary>
/// Page size
/// </summary>
public int PageSize
{
get { return this.pageSize; }
set { this.pageSize = value; }
}
/// <summary>
/// Page item reference
/// </summary>
public string PageItemReference
{
get { return this.pageItemReference; }
set { this.pageItemReference = value; }
}
/// <summary>
/// Page direction
/// </summary>
public SearchPageDirection PageDirection
{
get { return this.pageDirection; }
set { this.pageDirection = value; }
}
/// <summary>
/// Gets or sets the server version.
/// </summary>
/// <value>
/// The server version.
/// </value>
long IDiscoveryVersionable.ServerVersion
{
get;
set;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.Text
{
// Our input file data structures look like:
//
// Header structure looks like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page indexes that will follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
internal abstract class BaseCodePageEncoding : EncodingNLS
{
internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
protected int iExtraBytes = 0;
// Our private unicode-to-bytes best-fit-array, and vice versa.
protected char[] arrayUnicodeBestFit = null;
protected char[] arrayBytesBestFit = null;
[System.Security.SecuritySafeCritical] // static constructors should be safe to call
static BaseCodePageEncoding()
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage)
: this(codepage, codepage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage, int dataCodePage)
: base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null))
{
SetFallbackEncoding();
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
: base(codepage, enc, dec)
{
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
// Just a helper as we cannot use 'this' when calling 'base(...)'
private void SetFallbackEncoding()
{
(EncoderFallback as InternalEncoderBestFitFallback).encoding = this;
(DecoderFallback as InternalDecoderBestFitFallback).encoding = this;
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add an unused WORD so that CodePages is aligned with DWORD boundary.
}
private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44;
[StructLayout(LayoutKind.Explicit, Pack = 2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision;// WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
}
private const int CODEPAGE_HEADER_SIZE = 48;
// Initialize our global stuff
private static byte[] s_codePagesDataHeader = new byte[CODEPAGE_DATA_FILE_HEADER_SIZE];
protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream(CODE_PAGE_DATA_FILE_NAME);
protected static readonly Object s_streamLock = new Object(); // this lock used when reading from s_codePagesEncodingDataStream
// Real variables
protected byte[] m_codePageHeader = new byte[CODEPAGE_HEADER_SIZE];
protected int m_firstDataWordOffset;
protected int m_dataSize;
// Safe handle wrapper around section map view
[System.Security.SecurityCritical] // auto-generated
protected SafeAllocHHandle safeNativeMemoryHandle = null;
internal static Stream GetEncodingDataStream(String tableName)
{
Debug.Assert(tableName != null, "table name can not be null");
// NOTE: We must reflect on a public type that is exposed in the contract here
// (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to
// the right assembly.
Stream stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName);
if (stream == null)
{
// We can not continue if we can't get the resource.
throw new InvalidOperationException();
}
// Read the header
stream.Read(s_codePagesDataHeader, 0, s_codePagesDataHeader.Length);
return stream;
}
// We need to load tables for our code page
[System.Security.SecurityCritical] // auto-generated
private unsafe void LoadCodePageTables()
{
if (!FindCodePage(dataTableCodePage))
{
// Didn't have one
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
}
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
[System.Security.SecurityCritical] // auto-generated
private unsafe bool FindCodePage(int codePage)
{
Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader");
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = s_codePagesDataHeader)
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = codePageIndex)
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
long position = s_codePagesEncodingDataStream.Position;
s_codePagesEncodingDataStream.Seek((long)pCodePageIndex->Offset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(m_codePageHeader, 0, m_codePageHeader.Length);
m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; // stream now pointing to the codepage data
if (i == codePagesCount - 1) // last codepage
{
m_dataSize = (int)(s_codePagesEncodingDataStream.Length - pCodePageIndex->Offset - m_codePageHeader.Length);
}
else
{
// Read Next codepage data to get the offset and then calculate the size
s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin);
int currentOffset = pCodePageIndex->Offset;
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
m_dataSize = pCodePageIndex->Offset - currentOffset - m_codePageHeader.Length;
}
return true;
}
}
}
}
// Couldn't find it
return false;
}
// Get our code page byte count
[System.Security.SecurityCritical] // auto-generated
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = s_codePagesDataHeader)
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = codePageIndex)
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table");
// Return what it says for byte count
return pCodePageIndex->ByteCount;
}
}
}
}
// Couldn't find it
return 0;
}
// We have a managed code page entry, so load our tables
[System.Security.SecurityCritical]
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
[System.Security.SecurityCritical] // auto-generated
protected unsafe byte* GetNativeMemory(int iSize)
{
if (safeNativeMemoryHandle == null)
{
byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize);
Debug.Assert(pNativeMemory != null);
safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory);
}
return (byte*)safeNativeMemoryHandle.DangerousGetHandle();
}
[System.Security.SecurityCritical]
protected abstract unsafe void ReadBestFitTable();
[System.Security.SecuritySafeCritical]
internal char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
[System.Security.SecuritySafeCritical]
internal char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may have already finalized, making the memory section
// invalid. We detect that by validating the memory section handle then re-initializing the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void CheckMemorySection()
{
if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// Copyright 2016 Tom Deseyn <tom.deseyn@gmail.com>
// This software is made available under the MIT License
// See COPYING for details
#pragma warning disable 0618 // 'Marshal.SizeOf(Type)' is obsolete
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using Tmds.DBus.CodeGen;
namespace Tmds.DBus.Protocol
{
internal class MessageReader
{
private readonly EndianFlag _endianness;
private readonly ArraySegment<byte> _data;
private readonly Message _message;
private readonly IProxyFactory _proxyFactory;
private int _pos = 0;
private bool _skipNextStructPadding = false;
static Dictionary<Type, bool> s_isPrimitiveStruct = new Dictionary<Type, bool> ();
public MessageReader(EndianFlag endianness, ArraySegment<byte> data)
{
_endianness = endianness;
_data = data;
}
public MessageReader (Message message, IProxyFactory proxyFactory) :
this(message.Header.Endianness, new ArraySegment<byte>(message.Body ?? Array.Empty<byte>()))
{
_message = message;
_proxyFactory = proxyFactory;
}
public void SetSkipNextStructPadding()
{
_skipNextStructPadding = true;
}
public object Read(Type type)
{
if (type.GetTypeInfo().IsEnum)
{
var value = Read(Enum.GetUnderlyingType(type));
return Enum.ToObject(type, value);
}
if (type == typeof(bool))
{
return ReadBoolean();
}
else if (type == typeof(byte))
{
return ReadByte();
}
else if (type == typeof(double))
{
return ReadDouble();
}
else if (type == typeof(short))
{
return ReadInt16();
}
else if (type == typeof(int))
{
return ReadInt32();
}
else if (type == typeof(long))
{
return ReadInt64();
}
else if (type == typeof(ObjectPath))
{
return ReadObjectPath();
}
else if (type == typeof(Signature))
{
return ReadSignature();
}
else if (type == typeof(string))
{
return ReadString();
}
else if (type == typeof(float))
{
return ReadSingle();
}
else if (type == typeof(ushort))
{
return ReadUInt16();
}
else if (type == typeof(uint))
{
return ReadUInt32();
}
else if (type == typeof(ulong))
{
return ReadUInt64();
}
else if (type == typeof(object))
{
return ReadVariant();
}
else if (type == typeof(IDBusObject))
{
return ReadBusObject();
}
var method = ReadMethodFactory.CreateReadMethodForType(type);
if (method.IsStatic)
{
return method.Invoke(null, new object[] { this });
}
else
{
return method.Invoke(this, null);
}
}
public void Seek (int stride)
{
var check = _pos + stride;
if (check < 0 || check > _data.Count)
throw new ArgumentOutOfRangeException ("stride");
_pos = check;
}
public T ReadDBusInterface<T>()
{
ObjectPath path = ReadObjectPath();
return _proxyFactory.CreateProxy<T>(_message.Header.Sender, path);
}
public T ReadEnum<T>()
{
Type type = typeof(T);
var value = Read(Enum.GetUnderlyingType(type));
return (T)Enum.ToObject(type, value);
}
public byte ReadByte ()
{
return _data.Array[_data.Offset + _pos++];
}
public bool ReadBoolean ()
{
uint intval = ReadUInt32 ();
switch (intval) {
case 0:
return false;
case 1:
return true;
default:
throw new ProtocolException("Read value " + intval + " at position " + _pos + " while expecting boolean (0/1)");
}
}
unsafe protected void MarshalUShort (void* dstPtr)
{
ReadPad (2);
if (_data.Count < _pos + 2)
throw new ProtocolException("Cannot read beyond end of data");
if (_endianness == Environment.NativeEndianness) {
fixed (byte* p = &_data.Array[_data.Offset + _pos])
*((ushort*)dstPtr) = *((ushort*)p);
} else {
byte* dst = (byte*)dstPtr;
dst[0] = _data.Array[_data.Offset + _pos + 1];
dst[1] = _data.Array[_data.Offset + _pos + 0];
}
_pos += 2;
}
unsafe public short ReadInt16 ()
{
short val;
MarshalUShort (&val);
return val;
}
unsafe public ushort ReadUInt16 ()
{
ushort val;
MarshalUShort (&val);
return val;
}
unsafe protected void MarshalUInt (void* dstPtr)
{
ReadPad (4);
if (_data.Count < _pos + 4)
throw new ProtocolException("Cannot read beyond end of data");
if (_endianness == Environment.NativeEndianness) {
fixed (byte* p = &_data.Array[_data.Offset + _pos])
*((uint*)dstPtr) = *((uint*)p);
} else {
byte* dst = (byte*)dstPtr;
dst[0] = _data.Array[_data.Offset + _pos + 3];
dst[1] = _data.Array[_data.Offset + _pos + 2];
dst[2] = _data.Array[_data.Offset + _pos + 1];
dst[3] = _data.Array[_data.Offset + _pos + 0];
}
_pos += 4;
}
unsafe public int ReadInt32 ()
{
int val;
MarshalUInt (&val);
return val;
}
unsafe public uint ReadUInt32 ()
{
uint val;
MarshalUInt (&val);
return val;
}
unsafe protected void MarshalULong (void* dstPtr)
{
ReadPad (8);
if (_data.Count < _pos + 8)
throw new ProtocolException("Cannot read beyond end of data");
if (_endianness == Environment.NativeEndianness) {
fixed (byte* p = &_data.Array[_data.Offset + _pos])
*((ulong*)dstPtr) = *((ulong*)p);
} else {
byte* dst = (byte*)dstPtr;
for (int i = 0; i < 8; ++i)
dst[i] = _data.Array[_data.Offset + _pos + (7 - i)];
}
_pos += 8;
}
unsafe public long ReadInt64 ()
{
long val;
MarshalULong (&val);
return val;
}
unsafe public ulong ReadUInt64 ()
{
ulong val;
MarshalULong (&val);
return val;
}
unsafe public float ReadSingle ()
{
float val;
MarshalUInt (&val);
return val;
}
unsafe public double ReadDouble ()
{
double val;
MarshalULong (&val);
return val;
}
public string ReadString ()
{
uint ln = ReadUInt32 ();
string val = Encoding.UTF8.GetString (_data.Array, _data.Offset + _pos, (int)ln);
_pos += (int)ln;
ReadNull ();
return val;
}
public void SkipString()
{
ReadString();
}
public ObjectPath ReadObjectPath ()
{
//exactly the same as string
return new ObjectPath (ReadString ());
}
public IDBusObject ReadBusObject()
{
return new BusObject(ReadObjectPath());
}
public Signature ReadSignature ()
{
byte ln = ReadByte ();
// Avoid an array allocation for small signatures
if (ln == 1) {
DType dtype = (DType)ReadByte ();
ReadNull ();
return new Signature (dtype);
}
if (ln > ProtocolInformation.MaxSignatureLength)
throw new ProtocolException("Signature length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxSignatureLength + " bytes");
byte[] sigData = new byte[ln];
Array.Copy (_data.Array, _data.Offset + _pos, sigData, 0, (int)ln);
_pos += (int)ln;
ReadNull ();
return Signature.Take (sigData);
}
public T ReadSafeHandle<T>()
{
var idx = ReadInt32();
var fds = _message.UnixFds;
int fd = -1;
if (fds != null && idx < fds.Length)
{
fd = fds[idx].Handle;
}
return (T)Activator.CreateInstance(typeof(T), new object[] { (IntPtr)fd , true });
}
public object ReadVariant ()
{
var sig = ReadSignature ();
if (!sig.IsSingleCompleteType)
throw new InvalidOperationException (string.Format ("ReadVariant need a single complete type signature, {0} was given", sig.ToString ()));
return Read(sig.ToType());
}
public T ReadVariantAsType<T>()
{
var sig = ReadSignature ();
if (!sig.IsSingleCompleteType)
throw new InvalidOperationException (string.Format ("ReadVariant need a single complete type signature, {0} was given", sig.ToString ()));
var type = typeof(T);
if (sig != Signature.GetSig(type, isCompileTimeType: true))
throw new InvalidCastException($"Cannot convert dbus type '{sig.ToString()}' to '{type.FullName}'");
return (T)Read(type);
}
public T ReadDictionaryObject<T>()
{
var type = typeof(T);
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
object val = Activator.CreateInstance (type);
uint ln = ReadUInt32 ();
if (ln > ProtocolInformation.MaxArrayLength)
throw new ProtocolException("Dict length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxArrayLength + " bytes");
ReadPad (8);
int endPos = _pos + (int)ln;
while (_pos < endPos) {
ReadPad (8);
var key = ReadString();
var sig = ReadSignature();
if (!sig.IsSingleCompleteType)
throw new InvalidOperationException (string.Format ("ReadVariant need a single complete type signature, {0} was given", sig.ToString ()));
// if the key contains a '-' which is an invalid identifier character,
// we try and replace it with '_' and see if we find a match.
// The name may be prefixed with '_'.
var field = fis.Where(f => ((f.Name.Length == key.Length) || (f.Name.Length == key.Length + 1 && f.Name[0] == '_'))
&& (f.Name.EndsWith(key, StringComparison.Ordinal) || (key.Contains("-") && f.Name.Replace('_', '-').EndsWith(key, StringComparison.Ordinal)))).SingleOrDefault();
if (field == null)
{
var value = Read(sig.ToType());
}
else
{
Type fieldType;
string propertyName;
PropertyTypeInspector.InspectField(field, out propertyName, out fieldType);
if (sig != Signature.GetSig(fieldType, isCompileTimeType: true))
{
throw new ArgumentException($"Dictionary '{type.FullName}' field '{field.Name}' with type '{fieldType.FullName}' cannot be read from D-Bus type '{sig}'");
}
var readValue = Read(fieldType);
field.SetValue (val, readValue);
}
}
if (_pos != endPos)
throw new ProtocolException("Read pos " + _pos + " != ep " + endPos);
return (T)val;
}
public Dictionary<TKey, TValue> ReadDictionary<TKey, TValue> ()
{
uint ln = ReadUInt32 ();
if (ln > ProtocolInformation.MaxArrayLength)
throw new ProtocolException("Dict length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxArrayLength + " bytes");
var val = new Dictionary<TKey, TValue> ((int)(ln / 8));
ReadPad (8);
int endPos = _pos + (int)ln;
var keyReader = ReadMethodFactory.CreateReadMethodDelegate<TKey>();
var valueReader = ReadMethodFactory.CreateReadMethodDelegate<TValue>();
while (_pos < endPos) {
ReadPad (8);
TKey k = keyReader(this);
TValue v = valueReader(this);
val.Add (k, v);
}
if (_pos != endPos)
throw new ProtocolException("Read pos " + _pos + " != ep " + endPos);
return val;
}
public T[] ReadArray<T> ()
{
uint ln = ReadUInt32 ();
Type elemType = typeof (T);
if (ln > ProtocolInformation.MaxArrayLength)
throw new ProtocolException("Array length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxArrayLength + " bytes");
//advance to the alignment of the element
ReadPad (ProtocolInformation.GetAlignment (elemType));
if (elemType.GetTypeInfo().IsPrimitive) {
// Fast path for primitive types (except bool which isn't blittable and take another path)
if (elemType != typeof (bool))
return MarshalArray<T> (ln);
else
return (T[])(Array)MarshalBoolArray (ln);
}
var list = new List<T> ();
int endPos = _pos + (int)ln;
var elementReader = ReadMethodFactory.CreateReadMethodDelegate<T>();
while (_pos < endPos)
list.Add (elementReader(this));
if (_pos != endPos)
throw new ProtocolException("Read pos " + _pos + " != ep " + endPos);
return list.ToArray ();
}
TArray[] MarshalArray<TArray> (uint length)
{
int sof = Marshal.SizeOf<TArray>();
TArray[] array = new TArray[(int)(length / sof)];
if (_endianness == Environment.NativeEndianness) {
Buffer.BlockCopy (_data.Array, _data.Offset + _pos, array, 0, (int)length);
_pos += (int)length;
} else {
GCHandle handle = GCHandle.Alloc (array, GCHandleType.Pinned);
DirectCopy (sof, length, handle);
handle.Free ();
}
return array;
}
void DirectCopy (int sof, uint length, GCHandle handle)
{
DirectCopy (sof, length, handle.AddrOfPinnedObject ());
}
unsafe void DirectCopy (int sof, uint length, IntPtr handle)
{
if (_endianness == Environment.NativeEndianness) {
Marshal.Copy (_data.Array, _data.Offset + _pos, handle, (int)length);
} else {
byte* ptr = (byte*)(void*)handle;
for (int i = _pos; i < _pos + length; i += sof)
for (int j = i; j < i + sof; j++)
ptr[2 * i - _pos + (sof - 1) - j] = _data.Array[_data.Offset + j];
}
_pos += (int)length * sof;
}
bool[] MarshalBoolArray (uint length)
{
bool[] array = new bool [length];
for (int i = 0; i < length; i++)
array[i] = ReadBoolean ();
return array;
}
public T ReadStruct<T> ()
{
if (!_skipNextStructPadding)
{
ReadPad (8);
}
_skipNextStructPadding = false;
FieldInfo[] fis = ArgTypeInspector.GetStructFields(typeof(T), isValueTuple: false);
// Empty struct? No need for processing
if (fis.Length == 0)
return default (T);
if (IsEligibleStruct (typeof(T), fis))
return (T)MarshalStruct (typeof(T), fis);
object val = Activator.CreateInstance<T> ();
foreach (System.Reflection.FieldInfo fi in fis)
fi.SetValue (val, Read (fi.FieldType));
return (T)val;
}
public T ReadValueTupleStruct<T> ()
{
if (!_skipNextStructPadding)
{
ReadPad (8);
}
_skipNextStructPadding = false;
bool isValueTuple = true;
FieldInfo[] fis = ArgTypeInspector.GetStructFields(typeof(T), isValueTuple);
// Empty struct? No need for processing
if (fis.Length == 0)
return default (T);
object val = Activator.CreateInstance<T> ();
for (int i = 0; i < fis.Length; i++)
{
var fi = fis[i];
if (i == 7 && isValueTuple)
{
_skipNextStructPadding = true;
}
fi.SetValue (val, Read(fi.FieldType));
}
return (T)val;
}
object MarshalStruct (Type structType, FieldInfo[] fis)
{
object strct = Activator.CreateInstance (structType);
int sof = Marshal.SizeOf (fis[0].FieldType);
GCHandle handle = GCHandle.Alloc (strct, GCHandleType.Pinned);
DirectCopy (sof, (uint)(fis.Length * sof), handle);
handle.Free ();
return strct;
}
public void ReadNull ()
{
if (_data.Array[_data.Offset + _pos] != 0)
throw new ProtocolException("Read non-zero byte at position " + _pos + " while expecting null terminator");
_pos++;
}
public void ReadPad (int alignment)
{
for (int endPos = ProtocolInformation.Padded (_pos, alignment) ; _pos != endPos ; _pos++)
if (_data.Array[_data.Offset + _pos] != 0)
throw new ProtocolException("Read non-zero byte at position " + _pos + " while expecting padding. Value given: " + _data.Array[_data.Offset + _pos]);
}
// If a struct is only composed of primitive type fields (i.e. blittable types)
// then this method return true. Result is cached in isPrimitiveStruct dictionary.
internal static bool IsEligibleStruct (Type structType, FieldInfo[] fields)
{
lock (s_isPrimitiveStruct)
{
bool result;
if (s_isPrimitiveStruct.TryGetValue(structType, out result))
return result;
var typeInfo = structType.GetTypeInfo();
if (!typeInfo.IsLayoutSequential)
return false;
if (!(s_isPrimitiveStruct[structType] = fields.All((f) => f.FieldType.GetTypeInfo().IsPrimitive && f.FieldType != typeof(bool))))
return false;
int alignement = ProtocolInformation.GetAlignment(fields[0].FieldType);
return s_isPrimitiveStruct[structType] = !fields.Any((f) => ProtocolInformation.GetAlignment(f.FieldType) != alignement);
}
}
private class BusObject : IDBusObject
{
public BusObject(ObjectPath path)
{
ObjectPath = path;
}
public ObjectPath ObjectPath { get; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Web.Security;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Services;
using Umbraco.Web.Macros;
using Umbraco.Web.Security;
namespace Umbraco.Web.Routing
{
/// <summary>
/// Provides the default <see cref="IPublishedRouter"/> implementation.
/// </summary>
public class PublishedRouter : IPublishedRouter
{
private readonly IWebRoutingSection _webRoutingSection;
private readonly ContentFinderCollection _contentFinders;
private readonly IContentLastChanceFinder _contentLastChanceFinder;
private readonly ServiceContext _services;
private readonly IProfilingLogger _profilingLogger;
private readonly IVariationContextAccessor _variationContextAccessor;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="PublishedRouter"/> class.
/// </summary>
public PublishedRouter(
IWebRoutingSection webRoutingSection,
ContentFinderCollection contentFinders,
IContentLastChanceFinder contentLastChanceFinder,
IVariationContextAccessor variationContextAccessor,
ServiceContext services,
IProfilingLogger proflog)
{
_webRoutingSection = webRoutingSection ?? throw new ArgumentNullException(nameof(webRoutingSection));
_contentFinders = contentFinders ?? throw new ArgumentNullException(nameof(contentFinders));
_contentLastChanceFinder = contentLastChanceFinder ?? throw new ArgumentNullException(nameof(contentLastChanceFinder));
_services = services ?? throw new ArgumentNullException(nameof(services));
_profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog));
_variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
_logger = proflog;
}
/// <inheritdoc />
public PublishedRequest CreateRequest(UmbracoContext umbracoContext, Uri uri = null)
{
return new PublishedRequest(this, umbracoContext, uri ?? umbracoContext.CleanedUmbracoUrl);
}
#region Request
/// <inheritdoc />
public bool TryRouteRequest(PublishedRequest request)
{
// disabled - is it going to change the routing?
//_pcr.OnPreparing();
FindDomain(request);
if (request.IsRedirect) return false;
if (request.HasPublishedContent) return true;
FindPublishedContent(request);
if (request.IsRedirect) return false;
// don't handle anything - we just want to ensure that we find the content
//HandlePublishedContent();
//FindTemplate();
//FollowExternalRedirect();
//HandleWildcardDomains();
// disabled - we just want to ensure that we find the content
//_pcr.OnPrepared();
return request.HasPublishedContent;
}
private void SetVariationContext(string culture)
{
var variationContext = _variationContextAccessor.VariationContext;
if (variationContext != null && variationContext.Culture == culture) return;
_variationContextAccessor.VariationContext = new VariationContext(culture);
}
/// <inheritdoc />
public bool PrepareRequest(PublishedRequest request)
{
// note - at that point the original legacy module did something do handle IIS custom 404 errors
// ie pages looking like /anything.aspx?404;/path/to/document - I guess the reason was to support
// "directory URLs" without having to do wildcard mapping to ASP.NET on old IIS. This is a pain
// to maintain and probably not used anymore - removed as of 06/2012. @zpqrtbnk.
//
// to trigger Umbraco's not-found, one should configure IIS and/or ASP.NET custom 404 errors
// so that they point to a non-existing page eg /redirect-404.aspx
// TODO: SD: We need more information on this for when we release 4.10.0 as I'm not sure what this means.
// trigger the Preparing event - at that point anything can still be changed
// the idea is that it is possible to change the uri
//
request.OnPreparing();
//find domain
FindDomain(request);
// if request has been flagged to redirect then return
// whoever called us is in charge of actually redirecting
if (request.IsRedirect)
{
return false;
}
// set the culture on the thread - once, so it's set when running document lookups
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = request.Culture;
SetVariationContext(request.Culture.Name);
//find the published content if it's not assigned. This could be manually assigned with a custom route handler, or
// with something like EnsurePublishedContentRequestAttribute or UmbracoVirtualNodeRouteHandler. Those in turn call this method
// to setup the rest of the pipeline but we don't want to run the finders since there's one assigned.
if (request.PublishedContent == null)
{
// find the document & template
FindPublishedContentAndTemplate(request);
}
// handle wildcard domains
HandleWildcardDomains(request);
// set the culture on the thread -- again, 'cos it might have changed due to a finder or wildcard domain
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = request.Culture;
SetVariationContext(request.Culture.Name);
// trigger the Prepared event - at that point it is still possible to change about anything
// even though the request might be flagged for redirection - we'll redirect _after_ the event
//
// also, OnPrepared() will make the PublishedRequest readonly, so nothing can change
//
request.OnPrepared();
// we don't take care of anything so if the content has changed, it's up to the user
// to find out the appropriate template
//complete the PCR and assign the remaining values
return ConfigureRequest(request);
}
/// <summary>
/// Called by PrepareRequest once everything has been discovered, resolved and assigned to the PCR. This method
/// finalizes the PCR with the values assigned.
/// </summary>
/// <returns>
/// Returns false if the request was not successfully configured
/// </returns>
/// <remarks>
/// This method logic has been put into it's own method in case developers have created a custom PCR or are assigning their own values
/// but need to finalize it themselves.
/// </remarks>
public bool ConfigureRequest(PublishedRequest frequest)
{
if (frequest.HasPublishedContent == false)
{
return false;
}
// set the culture on the thread -- again, 'cos it might have changed in the event handler
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = frequest.Culture;
SetVariationContext(frequest.Culture.Name);
// if request has been flagged to redirect, or has no content to display,
// then return - whoever called us is in charge of actually redirecting
if (frequest.IsRedirect || frequest.HasPublishedContent == false)
{
return false;
}
// we may be 404 _and_ have a content
// can't go beyond that point without a PublishedContent to render
// it's ok not to have a template, in order to give MVC a chance to hijack routes
// note - the page() ctor below will cause the "page" to get the value of all its
// "elements" ie of all the IPublishedContent property. If we use the object value,
// that will trigger macro execution - which can't happen because macro execution
// requires that _pcr.UmbracoPage is already initialized = catch-22. The "legacy"
// pipeline did _not_ evaluate the macros, ie it is using the data value, and we
// have to keep doing it because of that catch-22.
// assign the legacy page back to the request
// handlers like default.aspx will want it and most macros currently need it
frequest.LegacyContentHashTable = new PublishedContentHashtableConverter(frequest);
return true;
}
/// <inheritdoc />
public void UpdateRequestToNotFound(PublishedRequest request)
{
// clear content
var content = request.PublishedContent;
request.PublishedContent = null;
HandlePublishedContent(request); // will go 404
FindTemplate(request);
// if request has been flagged to redirect then return
// whoever called us is in charge of redirecting
if (request.IsRedirect)
return;
if (request.HasPublishedContent == false)
{
// means the engine could not find a proper document to handle 404
// restore the saved content so we know it exists
request.PublishedContent = content;
return;
}
if (request.HasTemplate == false)
{
// means we may have a document, but we have no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much either
return;
}
// see note in PrepareRequest()
// assign the legacy page back to the docrequest
// handlers like default.aspx will want it and most macros currently need it
request.LegacyContentHashTable = new PublishedContentHashtableConverter(request);
}
#endregion
#region Domain
/// <summary>
/// Finds the site root (if any) matching the http request, and updates the PublishedRequest accordingly.
/// </summary>
/// <returns>A value indicating whether a domain was found.</returns>
internal bool FindDomain(PublishedRequest request)
{
const string tracePrefix = "FindDomain: ";
// note - we are not handling schemes nor ports here.
_logger.Debug<PublishedRouter>("{TracePrefix}Uri={RequestUri}", tracePrefix, request.Uri);
var domainsCache = request.UmbracoContext.PublishedSnapshot.Domains;
var domains = domainsCache.GetAll(includeWildcards: false).ToList();
// determines whether a domain corresponds to a published document, since some
// domains may exist but on a document that has been unpublished - as a whole - or
// that is not published for the domain's culture - in which case the domain does
// not apply
bool IsPublishedContentDomain(Domain domain)
{
// just get it from content cache - optimize there, not here
var domainDocument = request.UmbracoContext.PublishedSnapshot.Content.GetById(domain.ContentId);
// not published - at all
if (domainDocument == null)
return false;
// invariant - always published
if (!domainDocument.ContentType.VariesByCulture())
return true;
// variant, ensure that the culture corresponding to the domain's language is published
return domainDocument.Cultures.ContainsKey(domain.Culture.Name);
}
domains = domains.Where(IsPublishedContentDomain).ToList();
var defaultCulture = domainsCache.DefaultCulture;
// try to find a domain matching the current request
var domainAndUri = DomainUtilities.SelectDomain(domains, request.Uri, defaultCulture: defaultCulture);
// handle domain - always has a contentId and a culture
if (domainAndUri != null)
{
// matching an existing domain
_logger.Debug<PublishedRouter>("{TracePrefix}Matches domain={Domain}, rootId={RootContentId}, culture={Culture}", tracePrefix, domainAndUri.Name, domainAndUri.ContentId, domainAndUri.Culture);
request.Domain = domainAndUri;
request.Culture = domainAndUri.Culture;
// canonical? not implemented at the moment
// if (...)
// {
// _pcr.RedirectUrl = "...";
// return true;
// }
}
else
{
// not matching any existing domain
_logger.Debug<PublishedRouter>("{TracePrefix}Matches no domain", tracePrefix);
request.Culture = defaultCulture == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultCulture);
}
_logger.Debug<PublishedRouter>("{TracePrefix}Culture={CultureName}", tracePrefix, request.Culture.Name);
return request.Domain != null;
}
/// <summary>
/// Looks for wildcard domains in the path and updates <c>Culture</c> accordingly.
/// </summary>
internal void HandleWildcardDomains(PublishedRequest request)
{
const string tracePrefix = "HandleWildcardDomains: ";
if (request.HasPublishedContent == false)
return;
var nodePath = request.PublishedContent.Path;
_logger.Debug<PublishedRouter>("{TracePrefix}Path={NodePath}", tracePrefix, nodePath);
var rootNodeId = request.HasDomain ? request.Domain.ContentId : (int?)null;
var domain = DomainUtilities.FindWildcardDomainInPath(request.UmbracoContext.PublishedSnapshot.Domains.GetAll(true), nodePath, rootNodeId);
// always has a contentId and a culture
if (domain != null)
{
request.Culture = domain.Culture;
_logger.Debug<PublishedRouter>("{TracePrefix}Got domain on node {DomainContentId}, set culture to {CultureName}", tracePrefix, domain.ContentId, request.Culture.Name);
}
else
{
_logger.Debug<PublishedRouter>("{TracePrefix}No match.", tracePrefix);
}
}
#endregion
#region Rendering engine
internal bool FindTemplateRenderingEngineInDirectory(DirectoryInfo directory, string alias, string[] extensions)
{
if (directory == null || directory.Exists == false)
return false;
var pos = alias.IndexOf('/');
if (pos > 0)
{
// recurse
var subdir = directory.GetDirectories(alias.Substring(0, pos)).FirstOrDefault();
alias = alias.Substring(pos + 1);
return subdir != null && FindTemplateRenderingEngineInDirectory(subdir, alias, extensions);
}
// look here
return directory.GetFiles().Any(f => extensions.Any(e => f.Name.InvariantEquals(alias + e)));
}
#endregion
#region Document and template
/// <inheritdoc />
public ITemplate GetTemplate(string alias)
{
return _services.FileService.GetTemplate(alias);
}
/// <summary>
/// Finds the Umbraco document (if any) matching the request, and updates the PublishedRequest accordingly.
/// </summary>
/// <returns>A value indicating whether a document and template were found.</returns>
private void FindPublishedContentAndTemplate(PublishedRequest request)
{
_logger.Debug<PublishedRouter>("FindPublishedContentAndTemplate: Path={UriAbsolutePath}", request.Uri.AbsolutePath);
// run the document finders
FindPublishedContent(request);
// if request has been flagged to redirect then return
// whoever called us is in charge of actually redirecting
// -- do not process anything any further --
if (request.IsRedirect)
return;
// not handling umbracoRedirect here but after LookupDocument2
// so internal redirect, 404, etc has precedence over redirect
// handle not-found, redirects, access...
HandlePublishedContent(request);
// find a template
FindTemplate(request);
// handle umbracoRedirect
FollowExternalRedirect(request);
}
/// <summary>
/// Tries to find the document matching the request, by running the IPublishedContentFinder instances.
/// </summary>
/// <exception cref="InvalidOperationException">There is no finder collection.</exception>
internal void FindPublishedContent(PublishedRequest request)
{
const string tracePrefix = "FindPublishedContent: ";
// look for the document
// the first successful finder, if any, will set this.PublishedContent, and may also set this.Template
// some finders may implement caching
using (_profilingLogger.DebugDuration<PublishedRouter>(
$"{tracePrefix}Begin finders",
$"{tracePrefix}End finders, {(request.HasPublishedContent ? "a document was found" : "no document was found")}"))
{
//iterate but return on first one that finds it
var found = _contentFinders.Any(finder =>
{
_logger.Debug<PublishedRouter>("Finder {ContentFinderType}", finder.GetType().FullName);
return finder.TryFindContent(request);
});
}
// indicate that the published content (if any) we have at the moment is the
// one that was found by the standard finders before anything else took place.
request.SetIsInitialPublishedContent();
}
/// <summary>
/// Handles the published content (if any).
/// </summary>
/// <remarks>
/// Handles "not found", internal redirects, access validation...
/// things that must be handled in one place because they can create loops
/// </remarks>
private void HandlePublishedContent(PublishedRequest request)
{
// because these might loop, we have to have some sort of infinite loop detection
int i = 0, j = 0;
const int maxLoop = 8;
do
{
_logger.Debug<PublishedRouter>("HandlePublishedContent: Loop {LoopCounter}", i);
// handle not found
if (request.HasPublishedContent == false)
{
request.Is404 = true;
_logger.Debug<PublishedRouter>("HandlePublishedContent: No document, try last chance lookup");
// if it fails then give up, there isn't much more that we can do
if (_contentLastChanceFinder.TryFindContent(request) == false)
{
_logger.Debug<PublishedRouter>("HandlePublishedContent: Failed to find a document, give up");
break;
}
_logger.Debug<PublishedRouter>("HandlePublishedContent: Found a document");
}
// follow internal redirects as long as it's not running out of control ie infinite loop of some sort
j = 0;
while (FollowInternalRedirects(request) && j++ < maxLoop)
{ }
if (j == maxLoop) // we're running out of control
break;
// ensure access
if (request.HasPublishedContent)
EnsurePublishedContentAccess(request);
// loop while we don't have page, ie the redirect or access
// got us to nowhere and now we need to run the notFoundLookup again
// as long as it's not running out of control ie infinite loop of some sort
} while (request.HasPublishedContent == false && i++ < maxLoop);
if (i == maxLoop || j == maxLoop)
{
_logger.Debug<PublishedRouter>("HandlePublishedContent: Looks like we are running into an infinite loop, abort");
request.PublishedContent = null;
}
_logger.Debug<PublishedRouter>("HandlePublishedContent: End");
}
/// <summary>
/// Follows internal redirections through the <c>umbracoInternalRedirectId</c> document property.
/// </summary>
/// <returns>A value indicating whether redirection took place and led to a new published document.</returns>
/// <remarks>
/// <para>Redirecting to a different site root and/or culture will not pick the new site root nor the new culture.</para>
/// <para>As per legacy, if the redirect does not work, we just ignore it.</para>
/// </remarks>
private bool FollowInternalRedirects(PublishedRequest request)
{
if (request.PublishedContent == null)
throw new InvalidOperationException("There is no PublishedContent.");
// don't try to find a redirect if the property doesn't exist
if (request.PublishedContent.HasProperty(Constants.Conventions.Content.InternalRedirectId) == false)
return false;
var redirect = false;
var valid = false;
IPublishedContent internalRedirectNode = null;
var internalRedirectId = request.PublishedContent.Value(Constants.Conventions.Content.InternalRedirectId, defaultValue: -1);
if (internalRedirectId > 0)
{
// try and get the redirect node from a legacy integer ID
valid = true;
internalRedirectNode = request.UmbracoContext.Content.GetById(internalRedirectId);
}
else
{
var udiInternalRedirectId = request.PublishedContent.Value<GuidUdi>(Constants.Conventions.Content.InternalRedirectId);
if (udiInternalRedirectId != null)
{
// try and get the redirect node from a UDI Guid
valid = true;
internalRedirectNode = request.UmbracoContext.Content.GetById(udiInternalRedirectId.Guid);
}
}
if (valid == false)
{
// bad redirect - log and display the current page (legacy behavior)
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: value is not an int nor a GuidUdi.",
request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue());
}
if (internalRedirectNode == null)
{
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: no such published document.",
request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue());
}
else if (internalRedirectId == request.PublishedContent.Id)
{
// redirect to self
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Redirecting to self, ignore");
}
else
{
request.SetInternalRedirectPublishedContent(internalRedirectNode); // don't use .PublishedContent here
redirect = true;
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Redirecting to id={InternalRedirectId}", internalRedirectId);
}
return redirect;
}
/// <summary>
/// Ensures that access to current node is permitted.
/// </summary>
/// <remarks>Redirecting to a different site root and/or culture will not pick the new site root nor the new culture.</remarks>
private void EnsurePublishedContentAccess(PublishedRequest request)
{
if (request.PublishedContent == null)
throw new InvalidOperationException("There is no PublishedContent.");
var path = request.PublishedContent.Path;
var publicAccessAttempt = _services.PublicAccessService.IsProtected(path);
if (publicAccessAttempt)
{
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Page is protected, check for access");
var membershipHelper = Current.Factory.GetInstance<MembershipHelper>();
if (membershipHelper.IsLoggedIn() == false)
{
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Not logged in, redirect to login page");
var loginPageId = publicAccessAttempt.Result.LoginNodeId;
if (loginPageId != request.PublishedContent.Id)
request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(loginPageId);
}
else if (_services.PublicAccessService.HasAccess(request.PublishedContent.Id, _services.ContentService, membershipHelper.CurrentUserName, membershipHelper.GetCurrentUserRoles()) == false)
{
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Current member has not access, redirect to error page");
var errorPageId = publicAccessAttempt.Result.NoAccessNodeId;
if (errorPageId != request.PublishedContent.Id)
request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(errorPageId);
}
else
{
if (membershipHelper.IsUmbracoMembershipProviderActive())
{
// grab the current member
var member = membershipHelper.GetCurrentMember();
// if the member has the "approved" and/or "locked out" properties, make sure they're correctly set before allowing access
var memberIsActive = true;
if (member != null)
{
if (member.HasProperty(Constants.Conventions.Member.IsApproved) == false)
memberIsActive = member.Value<bool>(Constants.Conventions.Member.IsApproved);
if (member.HasProperty(Constants.Conventions.Member.IsLockedOut) == false)
memberIsActive = member.Value<bool>(Constants.Conventions.Member.IsLockedOut) == false;
}
if (memberIsActive == false)
{
_logger.Debug<PublishedRouter>(
"Current member is either unapproved or locked out, redirect to error page");
var errorPageId = publicAccessAttempt.Result.NoAccessNodeId;
if (errorPageId != request.PublishedContent.Id)
request.PublishedContent =
request.UmbracoContext.PublishedSnapshot.Content.GetById(errorPageId);
}
else
{
_logger.Debug<PublishedRouter>("Current member has access");
}
}
else
{
_logger.Debug<PublishedRouter>("Current custom MembershipProvider member has access");
}
}
}
else
{
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Page is not protected");
}
}
/// <summary>
/// Finds a template for the current node, if any.
/// </summary>
private void FindTemplate(PublishedRequest request)
{
// NOTE: at the moment there is only 1 way to find a template, and then ppl must
// use the Prepared event to change the template if they wish. Should we also
// implement an ITemplateFinder logic?
if (request.PublishedContent == null)
{
request.TemplateModel = null;
return;
}
// read the alternate template alias, from querystring, form, cookie or server vars,
// only if the published content is the initial once, else the alternate template
// does not apply
// + optionally, apply the alternate template on internal redirects
var useAltTemplate = request.IsInitialPublishedContent
|| (_webRoutingSection.InternalRedirectPreservesTemplate && request.IsInternalRedirectPublishedContent);
var altTemplate = useAltTemplate
? request.UmbracoContext.HttpContext.Request[Constants.Conventions.Url.AltTemplate]
: null;
if (string.IsNullOrWhiteSpace(altTemplate))
{
// we don't have an alternate template specified. use the current one if there's one already,
// which can happen if a content lookup also set the template (LookupByNiceUrlAndTemplate...),
// else lookup the template id on the document then lookup the template with that id.
if (request.HasTemplate)
{
_logger.Debug<PublishedRequest>("FindTemplate: Has a template already, and no alternate template.");
return;
}
// TODO: When we remove the need for a database for templates, then this id should be irrelevant,
// not sure how were going to do this nicely.
// TODO: We need to limit altTemplate to only allow templates that are assigned to the current document type!
// if the template isn't assigned to the document type we should log a warning and return 404
var templateId = request.PublishedContent.TemplateId;
request.TemplateModel = GetTemplateModel(templateId);
}
else
{
// we have an alternate template specified. lookup the template with that alias
// this means the we override any template that a content lookup might have set
// so /path/to/page/template1?altTemplate=template2 will use template2
// ignore if the alias does not match - just trace
if (request.HasTemplate)
_logger.Debug<PublishedRouter>("FindTemplate: Has a template already, but also an alternative template.");
_logger.Debug<PublishedRouter>("FindTemplate: Look for alternative template alias={AltTemplate}", altTemplate);
// IsAllowedTemplate deals both with DisableAlternativeTemplates and ValidateAlternativeTemplates settings
if (request.PublishedContent.IsAllowedTemplate(altTemplate))
{
// allowed, use
var template = _services.FileService.GetTemplate(altTemplate);
if (template != null)
{
request.TemplateModel = template;
_logger.Debug<PublishedRouter>("FindTemplate: Got alternative template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
}
else
{
_logger.Debug<PublishedRouter>("FindTemplate: The alternative template with alias={AltTemplate} does not exist, ignoring.", altTemplate);
}
}
else
{
_logger.Warn<PublishedRouter>("FindTemplate: Alternative template {TemplateAlias} is not allowed on node {NodeId}, ignoring.", altTemplate, request.PublishedContent.Id);
// no allowed, back to default
var templateId = request.PublishedContent.TemplateId;
request.TemplateModel = GetTemplateModel(templateId);
}
}
if (request.HasTemplate == false)
{
_logger.Debug<PublishedRouter>("FindTemplate: No template was found.");
// initial idea was: if we're not already 404 and UmbracoSettings.HandleMissingTemplateAs404 is true
// then reset _pcr.Document to null to force a 404.
//
// but: because we want to let MVC hijack routes even though no template is defined, we decide that
// a missing template is OK but the request will then be forwarded to MVC, which will need to take
// care of everything.
//
// so, don't set _pcr.Document to null here
}
else
{
_logger.Debug<PublishedRouter>("FindTemplate: Running with template id={TemplateId} alias={TemplateAlias}", request.TemplateModel.Id, request.TemplateModel.Alias);
}
}
private ITemplate GetTemplateModel(int? templateId)
{
if (templateId.HasValue == false || templateId.Value == default)
{
_logger.Debug<PublishedRouter>("GetTemplateModel: No template.");
return null;
}
_logger.Debug<PublishedRouter>("GetTemplateModel: Get template id={TemplateId}", templateId);
if (templateId == null)
throw new InvalidOperationException("The template is not set, the page cannot render.");
var template = _services.FileService.GetTemplate(templateId.Value);
if (template == null)
throw new InvalidOperationException("The template with Id " + templateId + " does not exist, the page cannot render.");
_logger.Debug<PublishedRouter>("GetTemplateModel: Got template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
return template;
}
/// <summary>
/// Follows external redirection through <c>umbracoRedirect</c> document property.
/// </summary>
/// <remarks>As per legacy, if the redirect does not work, we just ignore it.</remarks>
private void FollowExternalRedirect(PublishedRequest request)
{
if (request.HasPublishedContent == false) return;
// don't try to find a redirect if the property doesn't exist
if (request.PublishedContent.HasProperty(Constants.Conventions.Content.Redirect) == false)
return;
var redirectId = request.PublishedContent.Value(Constants.Conventions.Content.Redirect, defaultValue: -1);
var redirectUrl = "#";
if (redirectId > 0)
{
redirectUrl = request.UmbracoContext.UrlProvider.GetUrl(redirectId);
}
else
{
// might be a UDI instead of an int Id
var redirectUdi = request.PublishedContent.Value<GuidUdi>(Constants.Conventions.Content.Redirect);
if (redirectUdi != null)
redirectUrl = request.UmbracoContext.UrlProvider.GetUrl(redirectUdi.Guid);
}
if (redirectUrl != "#")
request.SetRedirect(redirectUrl);
}
#endregion
}
}
| |
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Copyright (c) 2002-2003, Craig Reynolds <craig_reynolds@playstation.sony.com>
// Copyright (C) 2007 Bjoern Graf <bjoern.graf@gmx.net>
// Copyright (C) 2007 Michael Coles <michael@digini.com>
// All rights reserved.
//
// This software is licensed as described in the file license.txt, which
// you should have received as part of this distribution. The terms
// are also available at http://www.codeplex.com/SharpSteer/Project/License.aspx.
using System;
using System.Numerics;
namespace SharpSteer2.Database
{
/// <summary>
/// This structure represents the spatial database. Typically one of
/// these would be created, by a call to lqCreateDatabase, for a given
/// application.
/// </summary>
class LocalityQueryDatabase
{
// type for a pointer to a function used to map over client objects
public delegate void LQCallBackFunction(Object clientObject, float distanceSquared, Object clientQueryState);
/// <summary>
/// This structure is a proxy for (and contains a pointer to) a client
/// (application) obj in the spatial database. One of these exists
/// for each client obj. This might be included within the
/// structure of a client obj, or could be allocated separately.
/// </summary>
public class ClientProxy
{
// previous obj in this bin, or null
public ClientProxy Prev;
// next obj in this bin, or null
public ClientProxy Next;
// bin ID (pointer to pointer to bin contents list)
//public ClientProxy bin;
// bin ID (index into bin contents list)
public int? Bin;
// pointer to client obj
public readonly Object Obj;
// the obj's location ("key point") used for spatial sorting
public Vector3 Position;
public ClientProxy(Object obj)
{
Obj = obj;
}
}
// the origin is the super-brick corner minimum coordinates
Vector3 _origin;
// length of the edges of the super-brick
Vector3 _size;
// number of sub-brick divisions in each direction
readonly int _divX;
readonly int _divY;
readonly int _divZ;
// pointer to an array of pointers, one for each bin
// The last index is the extra bin for "everything else" (points outside super-brick)
readonly ClientProxy[] _bins;
// extra bin for "everything else" (points outside super-brick)
//ClientProxy other;
/*
* Allocate and initialize an LQ database, return a pointer to it.
* The application needs to call this before using the LQ facility.
* The nine parameters define the properties of the "super-brick":
* (1) origin: coordinates of one corner of the super-brick, its
* minimum x, y and z extent.
* (2) size: the width, height and depth of the super-brick.
* (3) the number of subdivisions (sub-bricks) along each axis.
* This routine also allocates the bin array, and initialize its
* contents.
*/
public LocalityQueryDatabase(Vector3 origin, Vector3 size, int divx, int divy, int divz)
{
_origin = origin;
_size = size;
_divX = divx;
_divY = divy;
_divZ = divz;
// The last index is the "other" bin
int bincount = divx * divy * divz + 1;
_bins = new ClientProxy[bincount];
for (int i = 0; i < _bins.Length; i++)
{
_bins[i] = null;
}
}
/* Determine index into linear bin array given 3D bin indices */
private int BinCoordsToBinIndex(int ix, int iy, int iz)
{
return ((ix * _divY * _divZ) + (iy * _divZ) + iz);
}
/* Call for each client obj every time its location changes. For
example, in an animation application, this would be called each
frame for every moving obj. */
public void UpdateForNewLocation(ClientProxy obj, Vector3 position)
{
/* find bin for new location */
int newBin = BinForLocation(position);
/* store location in client obj, for future reference */
obj.Position = position;
/* has obj moved into a new bin? */
if (newBin != obj.Bin)
{
RemoveFromBin(obj);
AddToBin(obj, newBin);
}
}
/* Adds a given client obj to a given bin, linking it into the bin
contents list. */
private void AddToBin(ClientProxy obj, int binIndex)
{
/* if bin is currently empty */
if (_bins[binIndex] == null)
{
obj.Prev = null;
obj.Next = null;
}
else
{
obj.Prev = null;
obj.Next = _bins[binIndex];
_bins[binIndex].Prev = obj;
}
_bins[binIndex] = obj;
/* record bin ID in proxy obj */
obj.Bin = binIndex;
}
/* Find the bin ID for a location in space. The location is given in
terms of its XYZ coordinates. The bin ID is a pointer to a pointer
to the bin contents list. */
private /*lqClientProxy*/int BinForLocation(Vector3 position)
{
/* if point outside super-brick, return the "other" bin */
if (position.X < _origin.X || position.Y < _origin.Y || position.Z < _origin.Z ||
position.X >= _origin.X + _size.X || position.Y >= _origin.Y + _size.Y || position.Z >= _origin.Z + _size.Z)
{
return _bins.Length - 1;
}
/* if point inside super-brick, compute the bin coordinates */
int ix = (int)(((position.X - _origin.X) / _size.X) * _divX);
int iy = (int)(((position.Y - _origin.Y) / _size.Y) * _divY);
int iz = (int)(((position.Z - _origin.Z) / _size.Z) * _divZ);
/* convert to linear bin number */
int i = BinCoordsToBinIndex(ix, iy, iz);
/* return pointer to that bin */
return i;// (bins[i]);
}
/* Apply an application-specific function to all objects in a certain
locality. The locality is specified as a sphere with a given
center and radius. All objects whose location (key-point) is
within this sphere are identified and the function is applied to
them. The application-supplied function takes three arguments:
(1) a void* pointer to an lqClientProxy's "object".
(2) the square of the distance from the center of the search
locality sphere (x,y,z) to object's key-point.
(3) a void* pointer to the caller-supplied "client query state"
object -- typically NULL, but can be used to store state
between calls to the lqCallBackFunction.
This routine uses the LQ database to quickly reject any objects in
bins which do not overlap with the sphere of interest. Incremental
calculation of index values is used to efficiently traverse the
bins of interest. */
public void MapOverAllObjectsInLocality(Vector3 center, float radius, LQCallBackFunction func, Object clientQueryState)
{
int partlyOut = 0;
bool completelyOutside =
(((center.X + radius) < _origin.X) ||
((center.Y + radius) < _origin.Y) ||
((center.Z + radius) < _origin.Z) ||
((center.X - radius) >= _origin.X + _size.X) ||
((center.Y - radius) >= _origin.Y + _size.Y) ||
((center.Z - radius) >= _origin.Z + _size.Z));
/* is the sphere completely outside the "super brick"? */
if (completelyOutside)
{
MapOverAllOutsideObjects(center, radius, func, clientQueryState);
return;
}
/* compute min and max bin coordinates for each dimension */
int minBinX = (int)((((center.X - radius) - _origin.X) / _size.X) * _divX);
int minBinY = (int)((((center.Y - radius) - _origin.Y) / _size.Y) * _divY);
int minBinZ = (int)((((center.Z - radius) - _origin.Z) / _size.Z) * _divZ);
int maxBinX = (int)((((center.X + radius) - _origin.X) / _size.X) * _divX);
int maxBinY = (int)((((center.Y + radius) - _origin.Y) / _size.Y) * _divY);
int maxBinZ = (int)((((center.Z + radius) - _origin.Z) / _size.Z) * _divZ);
/* clip bin coordinates */
if (minBinX < 0) { partlyOut = 1; minBinX = 0; }
if (minBinY < 0) { partlyOut = 1; minBinY = 0; }
if (minBinZ < 0) { partlyOut = 1; minBinZ = 0; }
if (maxBinX >= _divX) { partlyOut = 1; maxBinX = _divX - 1; }
if (maxBinY >= _divY) { partlyOut = 1; maxBinY = _divY - 1; }
if (maxBinZ >= _divZ) { partlyOut = 1; maxBinZ = _divZ - 1; }
/* map function over outside objects if necessary (if clipped) */
if (partlyOut != 0)
MapOverAllOutsideObjects(center, radius, func, clientQueryState);
/* map function over objects in bins */
MapOverAllObjectsInLocalityClipped(
center, radius,
func,
clientQueryState,
minBinX, minBinY, minBinZ,
maxBinX, maxBinY, maxBinZ);
}
/// <summary>
/// Given a bin's list of client proxies, traverse the list and invoke
/// the given lqCallBackFunction on each obj that falls within the
/// search radius.
/// </summary>
/// <param name="co"></param>
/// <param name="radiusSquared"></param>
/// <param name="func"></param>
/// <param name="state"></param>
/// <param name="position"></param>
private static void TraverseBinClientObjectList(ClientProxy co, float radiusSquared, LQCallBackFunction func, Object state, Vector3 position)
{
while (co != null)
{
// compute distance (squared) from this client obj to given
// locality sphere's centerpoint
Vector3 d = position - co.Position;
float distanceSquared = d.LengthSquared();
// apply function if client obj within sphere
if (distanceSquared < radiusSquared)
func(co.Obj, distanceSquared, state);
// consider next client obj in bin list
co = co.Next;
}
}
/// <summary>
/// This subroutine of lqMapOverAllObjectsInLocality efficiently
/// traverses of subset of bins specified by max and min bin
/// coordinates.
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="func"></param>
/// <param name="clientQueryState"></param>
/// <param name="minBinX"></param>
/// <param name="minBinY"></param>
/// <param name="minBinZ"></param>
/// <param name="maxBinX"></param>
/// <param name="maxBinY"></param>
/// <param name="maxBinZ"></param>
private void MapOverAllObjectsInLocalityClipped(Vector3 center, float radius,
LQCallBackFunction func,
Object clientQueryState,
int minBinX, int minBinY, int minBinZ,
int maxBinX, int maxBinY, int maxBinZ)
{
int i;
int slab = _divY * _divZ;
int row = _divZ;
int istart = minBinX * slab;
int jstart = minBinY * row;
int kstart = minBinZ;
float radiusSquared = radius * radius;
/* loop for x bins across diameter of sphere */
int iindex = istart;
for (i = minBinX; i <= maxBinX; i++)
{
/* loop for y bins across diameter of sphere */
int jindex = jstart;
int j;
for (j = minBinY; j <= maxBinY; j++)
{
/* loop for z bins across diameter of sphere */
int kindex = kstart;
int k;
for (k = minBinZ; k <= maxBinZ; k++)
{
/* get current bin's client obj list */
ClientProxy bin = _bins[iindex + jindex + kindex];
ClientProxy co = bin;
/* traverse current bin's client obj list */
TraverseBinClientObjectList(co,
radiusSquared,
func,
clientQueryState,
center);
kindex += 1;
}
jindex += row;
}
iindex += slab;
}
}
/// <summary>
/// If the query region (sphere) extends outside of the "super-brick"
/// we need to check for objects in the catch-all "other" bin which
/// holds any object which are not inside the regular sub-bricks
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="func"></param>
/// <param name="clientQueryState"></param>
private void MapOverAllOutsideObjects(Vector3 center, float radius, LQCallBackFunction func, Object clientQueryState)
{
ClientProxy co = _bins[_bins.Length - 1];
float radiusSquared = radius * radius;
// traverse the "other" bin's client object list
TraverseBinClientObjectList(co, radiusSquared, func, clientQueryState, center);
}
private static void MapOverAllObjectsInBin(ClientProxy binProxyList, LQCallBackFunction func, Object clientQueryState)
{
// walk down proxy list, applying call-back function to each one
while (binProxyList != null)
{
func(binProxyList.Obj, 0, clientQueryState);
binProxyList = binProxyList.Next;
}
}
/* Apply a user-supplied function to all objects in the database,
regardless of locality (cf lqMapOverAllObjectsInLocality) */
public void MapOverAllObjects(LQCallBackFunction func, Object clientQueryState)
{
foreach (ClientProxy bin in _bins)
{
MapOverAllObjectsInBin(bin, func, clientQueryState);
}
}
/* Removes a given client obj from its current bin, unlinking it
from the bin contents list. */
public void RemoveFromBin(ClientProxy obj)
{
/* adjust pointers if obj is currently in a bin */
if (obj.Bin != null)
{
/* If this obj is at the head of the list, move the bin
pointer to the next item in the list (might be null). */
if (_bins[obj.Bin.Value] == obj)
_bins[obj.Bin.Value] = obj.Next;
/* If there is a prev obj, link its "next" pointer to the
obj after this one. */
if (obj.Prev != null)
obj.Prev.Next = obj.Next;
/* If there is a next obj, link its "prev" pointer to the
obj before this one. */
if (obj.Next != null)
obj.Next.Prev = obj.Prev;
}
/* Null out prev, next and bin pointers of this obj. */
obj.Prev = null;
obj.Next = null;
obj.Bin = null;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using MooGet;
using NUnit.Framework;
namespace MooGet.Specs {
[TestFixture]
public class OldSourceSpec : MooGetSpec {
[TestFixture]
public class Integration : OldSourceSpec {
[Test]
public void can_add_a_source() {
moo("source").ShouldContain(Moo.OfficialNugetFeed);
moo("source").ShouldNotContain("http://foo.com/whatever");
moo("source add http://foo.com/whatever");
moo("source").ShouldContain(Moo.OfficialNugetFeed);
moo("source").ShouldContain("http://foo.com/whatever");
}
[Test]
public void can_remove_a_source() {
moo("source add http://foo.com/whatever");
moo("source").ShouldContain(Moo.OfficialNugetFeed);
moo("source").ShouldContain("http://foo.com/whatever");
moo("source rm {0}", Moo.OfficialNugetFeed);
moo("source").ShouldNotContain(Moo.OfficialNugetFeed);
moo("source").ShouldContain("http://foo.com/whatever");
}
[Test]
public void default_sources_include_official_NuGet_feed() {
// Moo.Dir should not exist because it's not "installed"
Directory.Exists(PathToTempHome(".moo")).ShouldBeFalse();
moo("source").ShouldContain(Moo.OfficialNugetFeed);
// Moo.Dir should still not exist because it's not "installed"
Directory.Exists(PathToTempHome(".moo")).ShouldBeFalse();
}
}
// see ./spec/content/example-feed.xml to see the feed that these specs use
static OldSource source = new OldSource(PathToContent("example-feed.xml"));
[Test]
public void can_get_all_packages_from_a_source() {
var packages = source.AllPackages;
packages.Count.ShouldEqual(151);
packages.First().Id.ShouldEqual("Adam.JSGenerator");
packages.Last().Id.ShouldEqual("xmlbuilder");
}
/*
<entry>
<id>urn:uuid:23ddcce9-f31c-4d28-93fd-0496a433b972</id>
<title type="text">Adam.JSGenerator</title>
<published>2010-10-25T22:55:16Z</published>
<updated>2010-10-25T22:55:16Z</updated>
<author>
<name>Dave Van den Eynde</name>
</author>
<author>
<name>Wouter Demuynck</name>
</author>
<link rel="enclosure" href="http://173.203.67.148/ctp1/packages/download?p=Adam.JSGenerator.1.1.0.0.nupkg"/>
<content type="text">Adam.JSGenerator helps producing snippets of JavaScript code from managed code.</content>
<pkg:requireLicenseAcceptance>false</pkg:requireLicenseAcceptance>
<pkg:packageId>Adam.JSGenerator</pkg:packageId>
<pkg:version>1.1.0.0</pkg:version>
<pkg:language>en-US</pkg:language>
<pkg:tags xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">JavaScript JSON</string>
</pkg:tags>
</entry>
*/
[Test]
public void can_read_all_package_info__example_1() {
var package = source.AllPackages.First();
package.Id.ShouldEqual("Adam.JSGenerator");
package.Title.ShouldEqual("Adam.JSGenerator");
package.Description.ShouldEqual("Adam.JSGenerator helps producing snippets of JavaScript code from managed code.");
package.DownloadUrl.ShouldEqual("http://173.203.67.148/ctp1/packages/download?p=Adam.JSGenerator.1.1.0.0.nupkg");
package.Authors.Count.ShouldEqual(2);
package.Authors.ShouldContain("Dave Van den Eynde");
package.Authors.ShouldContain("Wouter Demuynck");
package.VersionText.ShouldEqual("1.1.0.0");
package.Language.ShouldEqual("en-US");
package.Tags.Count.ShouldEqual(2);
package.Tags.ShouldContain("JavaScript");
package.Tags.ShouldContain("JSON");
package.RequireLicenseAcceptance.ShouldBeFalse();
}
/*
<entry>
<id>urn:uuid:42a992a5-fb8a-4402-bf74-8d75b8a59e00</id>
<title type="text">xmlbuilder</title>
<published>2010-10-25T22:55:49Z</published>
<updated>2010-10-25T22:55:49Z</updated>
<author>
<name>Rogerio Araujo</name>
</author>
<link rel="enclosure" href="http://173.203.67.148/ctp1/packages/download?p=xmlbuilder.1.0.1.nupkg"/>
<link rel="license" href="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<content type="text">A DSL to help on XML authoring, with this library you can create xml content with few lines of code, there's no need to use System.Xml classes, the XMLBuilder hides all complexity behind xml generation.</content>
<pkg:requireLicenseAcceptance>false</pkg:requireLicenseAcceptance>
<pkg:packageId>xmlbuilder</pkg:packageId>
<pkg:version>1.0.1</pkg:version>
<pkg:language>en-US</pkg:language>
</entry>
*/
[Test] // be sure to get its LicenseUrl
public void can_read_all_package_info__example_2() {
var package = source.AllPackages.Last();
package.Id.ShouldEqual("xmlbuilder");
package.VersionText.ShouldEqual("1.0.1");
package.Title.ShouldEqual("xmlbuilder");
package.Description.ShouldEqual("A DSL to help on XML authoring, with this library you can create xml content with few lines of code, there's no need to use System.Xml classes, the XMLBuilder hides all complexity behind xml generation.");
package.Authors.Count.ShouldEqual(1);
package.Authors.First().ShouldEqual("Rogerio Araujo");
package.DownloadUrl.ShouldEqual("http://173.203.67.148/ctp1/packages/download?p=xmlbuilder.1.0.1.nupkg");
package.LicenseUrl.ShouldEqual("http://www.apache.org/licenses/LICENSE-2.0.html");
package.Language.ShouldEqual("en-US");
package.RequireLicenseAcceptance.ShouldBeFalse();
}
[Test]
public void can_read_all_dependencies() {
var package = source.Get("ESRI.SilverlightWpf.Design.Types");
package.Dependencies.Count.ShouldEqual(4);
foreach (var dependency in new Dictionary<string,string>(){
{"ESRI.SilverlightWpf.Core", "2.0.0.314"},
{"ESRI.SilverlightWpf.Behaviors", "2.0.0.314"},
{"ESRI.SilverlightWpf.Bing", "2.0.0.314"},
{"ESRI.SilverlightWpf.Toolkit", "2.0.0.314"}
}) {
package.Dependencies.Select(d => d.Id).ShouldContain(dependency.Key);
package.Dependencies.Select(d => d.VersionText).ShouldContain(dependency.Value);
}
}
// either nothing currently uses this or it's not displayed in the feed
//[Test][Ignore]
//public void can_read_summary() {}
// // nothing currently uses this ... i'll add some fake examples of my own
// [Test][Ignore]
// public void can_read_ProjectUrl() {}
// // nothing currently uses this ... i'll add some fake examples of my own
// [Test][Ignore]
// public void can_read_IconUrl() {}
// // not displayed in the feed? or no packages use this?
// [Test][Ignore] // for us, this should be useful for tracking who can push/remove updates
// public void can_read_Owners() {}
[Test]
public void reads_many_tags_split_by_spaces_if_only_one_string_element() {
var package = source.Get("FluentCassandra");
package.Tags.Count.ShouldEqual(5);
foreach (var tag in new string[] { "Fluent", "Cassandra", "Apache", "NoSQL", "Database" })
package.Tags.ShouldContain(tag);
}
[Test]
public void reads_many_tags_without_splitting_if_many_string_elements() {
var package = source.Get("common.eventing");
package.Tags.Count.ShouldEqual(4);
foreach (var tag in new string[] { "pub", "sub", "event", "broker" })
package.Tags.ShouldContain(tag);
}
// nuspec doesn't specify what categories are for, so we stick them into the package's tags
[Test]
public void can_read_category_terms_as_tags() {
var socketLabs = source.AllPackages.First(p => p.Id == "SocketLabs");
socketLabs.Tags.Count.ShouldEqual(1);
socketLabs.Tags.First().ShouldEqual("Email"); // <--- comes from a category
}
[Test]
public void can_get_just_the_latest_versions_of_packages_from_a_source() {
var packages = source.Packages; // or LatestPackages
Assert.That( packages.Count, Is.EqualTo(140));
// TODO need to check that the versions are actually the LATEST and not, say ... the oldest?
}
[Test][Ignore]
public void can_get_all_of_the_versions_available_for_a_particular_package() {
}
[Test][Ignore("TODO clean up searching ... re-spec searching AS WE NEED IT")]
public void can_search_for_package_by_title() {
var packages = source.SearchByTitle("ninject");
Assert.That( packages.Count, Is.EqualTo(4) );
Assert.That( packages.Select(p => p.Title).ToArray(),
Is.EqualTo(new string[] { "MvcTurbine.Ninject", "Ninject", "Ninject.MVC3", "SNAP.Ninject" }));
}
[Test]
public void can_search_for_package_by_description() {
var packages = source.SearchByDescription("dependency injection");
Assert.That( packages.Count, Is.EqualTo(5) );
Assert.That( packages.Select(p => p.Title).ToArray(),
Is.EqualTo(new string[] { "LightCore", "LightCore.WebIntegration", "Ninject", "structuremap", "Unity" }));
}
[Test]
public void can_search_for_package_by_title_or_description() {
var packages = source.SearchByTitleOrDescription("xml");
Assert.That( packages.Count, Is.EqualTo(6) );
Assert.That( packages.Select(p => p.Title).ToArray(),
Is.EqualTo(new string[] { "AntiXSS", "Artem.XmlProviders", "chargify", "FluentNHibernate", "protobuf-net", "xmlbuilder" }));
}
}
}
| |
using System;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement.Records;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
using YesSql.Sql;
namespace OrchardCore.ContentFields.Indexing.SQL
{
[Feature("OrchardCore.ContentFields.Indexing.SQL")]
public class Migrations : DataMigration
{
private readonly ILogger _logger;
public Migrations(ILogger<Migrations> logger)
{
_logger = logger;
}
public int Create()
{
// NOTE: The Text Length has been decreased from 4000 characters to 768.
// For existing SQL databases update the TextFieldIndex tables Text column length manually.
// INFO: The Text Length is now of 766 chars, but this is only used on a new installation.
SchemaBuilder.CreateMapIndexTable<TextFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Text", column => column.Nullable().WithLength(TextFieldIndex.MaxTextSize))
.Column<string>("BigText", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterIndexTable<TextFieldIndex>(table => table
.CreateIndex("IDX_TextFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TextFieldIndex>(table => table
.CreateIndex("IDX_TextFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TextFieldIndex>(table => table
.CreateIndex("IDX_TextFieldIndex_DocumentId_Text",
"DocumentId",
"Text",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<BooleanFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<bool>("Boolean", column => column.Nullable())
);
SchemaBuilder.AlterIndexTable<BooleanFieldIndex>(table => table
.CreateIndex("IDX_BooleanFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<BooleanFieldIndex>(table => table
.CreateIndex("IDX_BooleanFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Boolean",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<NumericFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<decimal>("Numeric", column => column.Nullable())
);
SchemaBuilder.AlterIndexTable<NumericFieldIndex>(table => table
.CreateIndex("IDX_NumericFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<NumericFieldIndex>(table => table
.CreateIndex("IDX_NumericFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<NumericFieldIndex>(table => table
.CreateIndex("IDX_NumericFieldIndex_DocumentId_Numeric",
"DocumentId",
"Numeric",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<DateTimeFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("DateTime", column => column.Nullable())
);
SchemaBuilder.AlterIndexTable<DateTimeFieldIndex>(table => table
.CreateIndex("IDX_DateTimeFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateTimeFieldIndex>(table => table
.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateTimeFieldIndex>(table => table
.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_DateTime",
"DocumentId",
"DateTime",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<DateFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("Date", column => column.Nullable())
);
SchemaBuilder.AlterIndexTable<DateFieldIndex>(table => table
.CreateIndex("IDX_DateFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateFieldIndex>(table => table
.CreateIndex("IDX_DateFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateFieldIndex>(table => table
.CreateIndex("IDX_DateFieldIndex_DocumentId_Date",
"DocumentId",
"ContentType",
"Date",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<ContentPickerFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("SelectedContentItemId", column => column.WithLength(26))
);
SchemaBuilder.AlterIndexTable<ContentPickerFieldIndex>(table => table
.CreateIndex("IDX_ContentPickerFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<ContentPickerFieldIndex>(table => table
.CreateIndex("IDX_ContentPickerFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<ContentPickerFieldIndex>(table => table
.CreateIndex("IDX_ContentPickerField_DocumentId_SelectedItemId",
"DocumentId",
"SelectedContentItemId",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<TimeFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<TimeSpan>("Time", column => column.Nullable())
);
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId_Time",
"DocumentId",
"Time",
"Published",
"Latest")
);
// NOTE: The Url and Text Length has been decreased from 4000 characters to 768.
// For existing SQL databases update the LinkFieldIndex tables Url and Text column length manually.
// The BigText and BigUrl columns are new additions so will not be populated until the content item is republished.
// INFO: The Url and Text Length is now of 766 chars, but this is only used on a new installation.
SchemaBuilder.CreateMapIndexTable<LinkFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Url", column => column.Nullable().WithLength(LinkFieldIndex.MaxUrlSize))
.Column<string>("BigUrl", column => column.Nullable().Unlimited())
.Column<string>("Text", column => column.Nullable().WithLength(LinkFieldIndex.MaxTextSize))
.Column<string>("BigText", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.CreateIndex("IDX_LinkFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.CreateIndex("IDX_LinkFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.CreateIndex("IDX_LinkFieldIndex_DocumentId_Url",
"DocumentId",
"Url",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.CreateIndex("IDX_LinkFieldIndex_DocumentId_Text",
"DocumentId",
"Text",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<HtmlFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Html", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterIndexTable<HtmlFieldIndex>(table => table
.CreateIndex("IDX_HtmlFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<HtmlFieldIndex>(table => table
.CreateIndex("IDX_HtmlFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.CreateMapIndexTable<MultiTextFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Value", column => column.Nullable().WithLength(MultiTextFieldIndex.MaxValueSize))
.Column<string>("BigValue", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterIndexTable<MultiTextFieldIndex>(table => table
.CreateIndex("IDX_MultiTextFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<MultiTextFieldIndex>(table => table
.CreateIndex("IDX_MultiTextFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<MultiTextFieldIndex>(table => table
.CreateIndex("IDX_MultiTextFieldIndex_DocumentId_Value",
"DocumentId",
"Value",
"Published",
"Latest")
);
// Shortcut other migration steps on new content definition schemas.
return 5;
}
// This code can be removed in a later version.
public int UpdateFrom1()
{
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.AddColumn<string>("BigUrl", column => column.Nullable().Unlimited()));
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.AddColumn<string>("BigText", column => column.Nullable().Unlimited()));
return 2;
}
// This code can be removed in a later version.
public int UpdateFrom2()
{
SchemaBuilder.CreateMapIndexTable<MultiTextFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Value", column => column.Nullable().WithLength(MultiTextFieldIndex.MaxValueSize))
.Column<string>("BigValue", column => column.Nullable().Unlimited())
);
return 3;
}
// This code can be removed in a later version.
public int UpdateFrom3()
{
SchemaBuilder.AlterIndexTable<TextFieldIndex>(table => table
.CreateIndex("IDX_TextFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TextFieldIndex>(table => table
.CreateIndex("IDX_TextFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
// Can't be created on existing databases where the 'Text' may be of 768 chars.
//SchemaBuilder.AlterIndexTable<TextFieldIndex>(table => table
// .CreateIndex("IDX_TextFieldIndex_DocumentId_Text",
// "DocumentId",
// "Text",
// "Published",
// "Latest")
//);
SchemaBuilder.AlterIndexTable<BooleanFieldIndex>(table => table
.CreateIndex("IDX_BooleanFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<BooleanFieldIndex>(table => table
.CreateIndex("IDX_BooleanFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Boolean",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<NumericFieldIndex>(table => table
.CreateIndex("IDX_NumericFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<NumericFieldIndex>(table => table
.CreateIndex("IDX_NumericFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<NumericFieldIndex>(table => table
.CreateIndex("IDX_NumericFieldIndex_DocumentId_Numeric",
"DocumentId",
"Numeric",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateTimeFieldIndex>(table => table
.CreateIndex("IDX_DateTimeFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateTimeFieldIndex>(table => table
.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateTimeFieldIndex>(table => table
.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_DateTime",
"DocumentId",
"DateTime",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateFieldIndex>(table => table
.CreateIndex("IDX_DateFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateFieldIndex>(table => table
.CreateIndex("IDX_DateFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<DateFieldIndex>(table => table
.CreateIndex("IDX_DateFieldIndex_DocumentId_Date",
"DocumentId",
"Date",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<ContentPickerFieldIndex>(table => table
.CreateIndex("IDX_ContentPickerFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<ContentPickerFieldIndex>(table => table
.CreateIndex("IDX_ContentPickerFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<ContentPickerFieldIndex>(table => table
.CreateIndex("IDX_ContentPickerField_DocumentId_SelectedItemId",
"DocumentId",
"SelectedContentItemId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId_Time",
"DocumentId",
"Time",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.CreateIndex("IDX_LinkFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
.CreateIndex("IDX_LinkFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
// Can't be created on existing databases where the 'Url' may be of 768 chars.
//SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
// .CreateIndex("IDX_LinkFieldIndex_DocumentId_Url",
// "DocumentId",
// "Url",
// "Published",
// "Latest")
//);
// Can't be created on existing databases where the 'Text' may be of 768 chars.
//SchemaBuilder.AlterIndexTable<LinkFieldIndex>(table => table
// .CreateIndex("IDX_LinkFieldIndex_DocumentId_Text",
// "DocumentId",
// "Text",
// "Published",
// "Latest")
//);
SchemaBuilder.AlterIndexTable<HtmlFieldIndex>(table => table
.CreateIndex("IDX_HtmlFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<HtmlFieldIndex>(table => table
.CreateIndex("IDX_HtmlFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<MultiTextFieldIndex>(table => table
.CreateIndex("IDX_MultiTextFieldIndex_DocumentId",
"DocumentId",
"ContentItemId",
"ContentItemVersionId",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<MultiTextFieldIndex>(table => table
.CreateIndex("IDX_MultiTextFieldIndex_DocumentId_ContentType",
"DocumentId",
"ContentType",
"ContentPart",
"ContentField",
"Published",
"Latest")
);
SchemaBuilder.AlterIndexTable<MultiTextFieldIndex>(table => table
.CreateIndex("IDX_MultiTextFieldIndex_DocumentId_Value",
"DocumentId",
"Value",
"Published",
"Latest")
);
return 4;
}
// This code can be removed in a later version.
public int UpdateFrom4()
{
// Attempts to drop an index that existed only in RC2.
try
{
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.DropIndex("IDX_TimeFieldIndex_Time")
);
}
catch
{
_logger.LogWarning("Failed to drop an index that does not exist 'IDX_TimeFieldIndex_Time'");
}
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.DropIndex("IDX_TimeFieldIndex_DocumentId_Time")
);
// SqLite does not support dropping columns.
try
{
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.DropColumn("Time"));
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.AddColumn<TimeSpan>("Time", column => column.Nullable()));
}
catch
{
_logger.LogWarning("Failed to alter 'Time' column. This is not an error when using SqLite");
}
SchemaBuilder.AlterIndexTable<TimeFieldIndex>(table => table
.CreateIndex("IDX_TimeFieldIndex_DocumentId_Time",
"DocumentId",
"Time",
"Published",
"Latest")
);
return 5;
}
}
}
| |
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
public sealed class TfsVCSourceProvider : SourceProvider, ISourceProvider
{
private bool _undoShelvesetPendingChanges = false;
public override string RepositoryType => WellKnownRepositoryTypes.TfsVersionControl;
public async Task GetSourceAsync(
IExecutionContext executionContext,
ServiceEndpoint endpoint,
CancellationToken cancellationToken)
{
Trace.Entering();
// Validate args.
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(endpoint, nameof(endpoint));
#if OS_WINDOWS
// Validate .NET Framework 4.6 or higher is installed.
var netFrameworkUtil = HostContext.GetService<INetFrameworkUtil>();
if (!netFrameworkUtil.Test(new Version(4, 6)))
{
throw new Exception(StringUtil.Loc("MinimumNetFramework46"));
}
#endif
// Create the tf command manager.
var tf = HostContext.CreateService<ITfsVCCommandManager>();
tf.CancellationToken = cancellationToken;
tf.Endpoint = endpoint;
tf.ExecutionContext = executionContext;
// Setup proxy.
var agentProxy = HostContext.GetService<IVstsAgentWebProxy>();
if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.IsBypassed(endpoint.Url))
{
executionContext.Debug($"Configure '{tf.FilePath}' to work through proxy server '{executionContext.Variables.Agent_ProxyUrl}'.");
tf.SetupProxy(executionContext.Variables.Agent_ProxyUrl, executionContext.Variables.Agent_ProxyUsername, executionContext.Variables.Agent_ProxyPassword);
}
// Add TF to the PATH.
string tfPath = tf.FilePath;
ArgUtil.File(tfPath, nameof(tfPath));
var varUtil = HostContext.GetService<IVarUtil>();
executionContext.Output(StringUtil.Loc("Prepending0WithDirectoryContaining1", Constants.PathVariable, Path.GetFileName(tfPath)));
varUtil.PrependPath(Path.GetDirectoryName(tfPath));
executionContext.Debug($"{Constants.PathVariable}: '{Environment.GetEnvironmentVariable(Constants.PathVariable)}'");
#if OS_WINDOWS
// Set TFVC_BUILDAGENT_POLICYPATH
string policyDllPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.ServerOM), "Microsoft.TeamFoundation.VersionControl.Controls.dll");
ArgUtil.File(policyDllPath, nameof(policyDllPath));
const string policyPathEnvKey = "TFVC_BUILDAGENT_POLICYPATH";
executionContext.Output(StringUtil.Loc("SetEnvVar", policyPathEnvKey));
Environment.SetEnvironmentVariable(policyPathEnvKey, policyDllPath);
#endif
// Check if the administrator accepted the license terms of the TEE EULA when configuring the agent.
AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings();
if (tf.Features.HasFlag(TfsVCFeatures.Eula) && settings.AcceptTeeEula)
{
// Check if the "tf eula -accept" command needs to be run for the current user.
bool skipEula = false;
try
{
skipEula = tf.TestEulaAccepted();
}
catch (Exception ex)
{
executionContext.Debug("Unexpected exception while testing whether the TEE EULA has been accepted for the current user.");
executionContext.Debug(ex.ToString());
}
if (!skipEula)
{
// Run the command "tf eula -accept".
try
{
await tf.EulaAsync();
}
catch (Exception ex)
{
executionContext.Debug(ex.ToString());
executionContext.Warning(ex.Message);
}
}
}
// Get the workspaces.
executionContext.Output(StringUtil.Loc("QueryingWorkspaceInfo"));
ITfsVCWorkspace[] tfWorkspaces = await tf.WorkspacesAsync();
// Determine the workspace name.
string buildDirectory = executionContext.Variables.Agent_BuildDirectory;
ArgUtil.NotNullOrEmpty(buildDirectory, nameof(buildDirectory));
string workspaceName = $"ws_{Path.GetFileName(buildDirectory)}_{settings.AgentId}";
executionContext.Variables.Set(Constants.Variables.Build.RepoTfvcWorkspace, workspaceName);
// Get the definition mappings.
DefinitionWorkspaceMapping[] definitionMappings =
JsonConvert.DeserializeObject<DefinitionWorkspaceMappings>(endpoint.Data[WellKnownEndpointData.TfvcWorkspaceMapping])?.Mappings;
// Determine the sources directory.
string sourcesDirectory = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory);
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
// Attempt to re-use an existing workspace if the command manager supports scorch
// or if clean is not specified.
ITfsVCWorkspace existingTFWorkspace = null;
bool clean = endpoint.Data.ContainsKey(WellKnownEndpointData.Clean) &&
StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean], defaultValue: false);
if (tf.Features.HasFlag(TfsVCFeatures.Scorch) || !clean)
{
existingTFWorkspace = WorkspaceUtil.MatchExactWorkspace(
executionContext: executionContext,
tfWorkspaces: tfWorkspaces,
name: workspaceName,
definitionMappings: definitionMappings,
sourcesDirectory: sourcesDirectory);
if (existingTFWorkspace != null)
{
if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
{
// Undo pending changes.
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory);
if (tfStatus?.HasPendingChanges ?? false)
{
await tf.UndoAsync(localPath: sourcesDirectory);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, cancellationToken);
});
}
}
else
{
// Perform "undo" for each map.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
{
if (definitionMapping.MappingType == DefinitionMappingType.Map)
{
// Check the status.
string localPath = definitionMapping.GetRootedLocalPath(sourcesDirectory);
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath);
if (tfStatus?.HasPendingChanges ?? false)
{
// Undo.
await tf.UndoAsync(localPath: localPath);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, cancellationToken);
});
}
}
}
}
// Scorch.
if (clean)
{
// Try to scorch.
try
{
await tf.ScorchAsync();
}
catch (ProcessExitCodeException ex)
{
// Scorch failed.
// Warn, drop the folder, and re-clone.
executionContext.Warning(ex.Message);
existingTFWorkspace = null;
}
}
}
}
// Create a new workspace.
if (existingTFWorkspace == null)
{
// Remove any conflicting workspaces.
await RemoveConflictingWorkspacesAsync(
tf: tf,
tfWorkspaces: tfWorkspaces,
name: workspaceName,
directory: sourcesDirectory);
// Remove any conflicting workspace from a different computer.
// This is primarily a hosted scenario where a registered hosted
// agent can land on a different computer each time.
tfWorkspaces = await tf.WorkspacesAsync(matchWorkspaceNameOnAnyComputer: true);
foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0])
{
await tf.WorkspaceDeleteAsync(tfWorkspace);
}
// Recreate the sources directory.
executionContext.Debug($"Deleting: '{sourcesDirectory}'.");
IOUtil.DeleteDirectory(sourcesDirectory, cancellationToken);
Directory.CreateDirectory(sourcesDirectory);
// Create the workspace.
await tf.WorkspaceNewAsync();
// Remove the default mapping.
if (tf.Features.HasFlag(TfsVCFeatures.DefaultWorkfoldMap))
{
await tf.WorkfoldUnmapAsync("$/");
}
// Sort the definition mappings.
definitionMappings =
(definitionMappings ?? new DefinitionWorkspaceMapping[0])
.OrderBy(x => x.NormalizedServerPath?.Length ?? 0) // By server path length.
.ToArray() ?? new DefinitionWorkspaceMapping[0];
// Add the definition mappings to the workspace.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings)
{
switch (definitionMapping.MappingType)
{
case DefinitionMappingType.Cloak:
// Add the cloak.
await tf.WorkfoldCloakAsync(serverPath: definitionMapping.ServerPath);
break;
case DefinitionMappingType.Map:
// Add the mapping.
await tf.WorkfoldMapAsync(
serverPath: definitionMapping.ServerPath,
localPath: definitionMapping.GetRootedLocalPath(sourcesDirectory));
break;
default:
throw new NotSupportedException();
}
}
}
if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
{
// Get.
await tf.GetAsync(localPath: sourcesDirectory);
}
else
{
// Perform "get" for each map.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
{
if (definitionMapping.MappingType == DefinitionMappingType.Map)
{
await tf.GetAsync(localPath: definitionMapping.GetRootedLocalPath(sourcesDirectory));
}
}
}
// Steps for shelveset/gated.
string shelvesetName = GetEndpointData(endpoint, Constants.EndpointData.SourceTfvcShelveset);
if (!string.IsNullOrEmpty(shelvesetName))
{
// Steps for gated.
ITfsVCShelveset tfShelveset = null;
string gatedShelvesetName = GetEndpointData(endpoint, Constants.EndpointData.GatedShelvesetName);
if (!string.IsNullOrEmpty(gatedShelvesetName))
{
// Clean the last-saved-checkin-metadata for existing workspaces.
//
// A better long term fix is to add a switch to "tf unshelve" that completely overwrites
// the last-saved-checkin-metadata, instead of merging associated work items.
//
// The targeted workaround for now is to create a trivial change and "tf shelve /move",
// which will delete the last-saved-checkin-metadata.
if (existingTFWorkspace != null)
{
executionContext.Output("Cleaning last saved checkin metadata.");
// Find a local mapped directory.
string firstLocalDirectory =
(definitionMappings ?? new DefinitionWorkspaceMapping[0])
.Where(x => x.MappingType == DefinitionMappingType.Map)
.Select(x => x.GetRootedLocalPath(sourcesDirectory))
.FirstOrDefault(x => Directory.Exists(x));
if (firstLocalDirectory == null)
{
executionContext.Warning("No mapped folder found. Unable to clean last-saved-checkin-metadata.");
}
else
{
// Create a trival change and "tf shelve /move" to clear the
// last-saved-checkin-metadata.
string cleanName = "__tf_clean_wksp_metadata";
string tempCleanFile = Path.Combine(firstLocalDirectory, cleanName);
try
{
File.WriteAllText(path: tempCleanFile, contents: "clean last-saved-checkin-metadata", encoding: Encoding.UTF8);
await tf.AddAsync(tempCleanFile);
await tf.ShelveAsync(shelveset: cleanName, commentFile: tempCleanFile, move: true);
}
catch (Exception ex)
{
executionContext.Warning($"Unable to clean last-saved-checkin-metadata. {ex.Message}");
try
{
await tf.UndoAsync(tempCleanFile);
}
catch (Exception ex2)
{
executionContext.Warning($"Unable to undo '{tempCleanFile}'. {ex2.Message}");
}
}
finally
{
IOUtil.DeleteFile(tempCleanFile);
}
}
}
// Get the shelveset metadata.
tfShelveset = await tf.ShelvesetsAsync(shelveset: shelvesetName);
// The above command throws if the shelveset is not found,
// so the following assertion should never fail.
ArgUtil.NotNull(tfShelveset, nameof(tfShelveset));
}
// Unshelve.
await tf.UnshelveAsync(shelveset: shelvesetName);
// Ensure we undo pending changes for shelveset build at the end.
_undoShelvesetPendingChanges = true;
if (!string.IsNullOrEmpty(gatedShelvesetName))
{
// Create the comment file for reshelve.
StringBuilder comment = new StringBuilder(tfShelveset.Comment ?? string.Empty);
string runCi = GetEndpointData(endpoint, Constants.EndpointData.GatedRunCI);
bool gatedRunCi = StringUtil.ConvertToBoolean(runCi, true);
if (!gatedRunCi)
{
if (comment.Length > 0)
{
comment.AppendLine();
}
comment.Append(Constants.Build.NoCICheckInComment);
}
string commentFile = null;
try
{
commentFile = Path.GetTempFileName();
File.WriteAllText(path: commentFile, contents: comment.ToString(), encoding: Encoding.UTF8);
// Reshelve.
await tf.ShelveAsync(shelveset: gatedShelvesetName, commentFile: commentFile, move: false);
}
finally
{
// Cleanup the comment file.
if (File.Exists(commentFile))
{
File.Delete(commentFile);
}
}
}
}
// Cleanup proxy settings.
if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.IsBypassed(endpoint.Url))
{
executionContext.Debug($"Remove proxy setting for '{tf.FilePath}' to work through proxy server '{executionContext.Variables.Agent_ProxyUrl}'.");
tf.CleanupProxySetting();
}
}
public async Task PostJobCleanupAsync(IExecutionContext executionContext, ServiceEndpoint endpoint)
{
if (_undoShelvesetPendingChanges)
{
string shelvesetName = GetEndpointData(endpoint, Constants.EndpointData.SourceTfvcShelveset);
executionContext.Debug($"Undo pending changes left by shelveset '{shelvesetName}'.");
// Create the tf command manager.
var tf = HostContext.CreateService<ITfsVCCommandManager>();
tf.CancellationToken = executionContext.CancellationToken;
tf.Endpoint = endpoint;
tf.ExecutionContext = executionContext;
// Get the definition mappings.
DefinitionWorkspaceMapping[] definitionMappings =
JsonConvert.DeserializeObject<DefinitionWorkspaceMappings>(endpoint.Data[WellKnownEndpointData.TfvcWorkspaceMapping])?.Mappings;
// Determine the sources directory.
string sourcesDirectory = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory);
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
try
{
if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
{
// Undo pending changes.
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory);
if (tfStatus?.HasPendingChanges ?? false)
{
await tf.UndoAsync(localPath: sourcesDirectory);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, executionContext.CancellationToken);
});
}
}
else
{
// Perform "undo" for each map.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
{
if (definitionMapping.MappingType == DefinitionMappingType.Map)
{
// Check the status.
string localPath = definitionMapping.GetRootedLocalPath(sourcesDirectory);
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath);
if (tfStatus?.HasPendingChanges ?? false)
{
// Undo.
await tf.UndoAsync(localPath: localPath);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, executionContext.CancellationToken);
});
}
}
}
}
}
catch (Exception ex)
{
// We can't undo pending changes, log a warning and continue.
executionContext.Debug(ex.ToString());
executionContext.Warning(ex.Message);
}
}
}
public override string GetLocalPath(IExecutionContext executionContext, ServiceEndpoint endpoint, string path)
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
ArgUtil.NotNull(endpoint, nameof(endpoint));
path = path ?? string.Empty;
if (path.StartsWith("$/") || path.StartsWith(@"$\"))
{
// Create the tf command manager.
var tf = HostContext.CreateService<ITfsVCCommandManager>();
tf.CancellationToken = CancellationToken.None;
tf.Endpoint = endpoint;
tf.ExecutionContext = executionContext;
// Attempt to resolve the path.
string localPath = tf.ResolvePath(serverPath: path);
if (!string.IsNullOrEmpty(localPath))
{
return localPath;
}
}
// Return the original path.
return path;
}
public override void SetVariablesInEndpoint(IExecutionContext executionContext, ServiceEndpoint endpoint)
{
base.SetVariablesInEndpoint(executionContext, endpoint);
endpoint.Data.Add(Constants.EndpointData.SourceTfvcShelveset, executionContext.Variables.Get(Constants.Variables.Build.SourceTfvcShelveset));
endpoint.Data.Add(Constants.EndpointData.GatedShelvesetName, executionContext.Variables.Get(Constants.Variables.Build.GatedShelvesetName));
endpoint.Data.Add(Constants.EndpointData.GatedRunCI, executionContext.Variables.Get(Constants.Variables.Build.GatedRunCI));
}
public sealed override bool TestOverrideBuildDirectory()
{
var configurationStore = HostContext.GetService<IConfigurationStore>();
AgentSettings settings = configurationStore.GetSettings();
return settings.IsHosted;
}
private async Task RemoveConflictingWorkspacesAsync(ITfsVCCommandManager tf, ITfsVCWorkspace[] tfWorkspaces, string name, string directory)
{
// Validate the args.
ArgUtil.NotNullOrEmpty(name, nameof(name));
ArgUtil.NotNullOrEmpty(directory, nameof(directory));
// Fixup the directory.
directory = directory.TrimEnd('/', '\\');
ArgUtil.NotNullOrEmpty(directory, nameof(directory));
string directorySlash = $"{directory}{Path.DirectorySeparatorChar}";
foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0])
{
// Attempt to match the workspace by name.
if (string.Equals(tfWorkspace.Name, name, StringComparison.OrdinalIgnoreCase))
{
// Try deleting the workspace from the server.
if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace)))
{
// Otherwise fallback to deleting the workspace from the local computer.
await tf.WorkspacesRemoveAsync(tfWorkspace);
}
// Continue iterating over the rest of the workspaces.
continue;
}
// Attempt to match the workspace by local path.
foreach (ITfsVCMapping tfMapping in tfWorkspace.Mappings ?? new ITfsVCMapping[0])
{
// Skip cloaks.
if (tfMapping.Cloak)
{
continue;
}
if (string.Equals(tfMapping.LocalPath, directory, StringComparison.CurrentCultureIgnoreCase) ||
(tfMapping.LocalPath ?? string.Empty).StartsWith(directorySlash, StringComparison.CurrentCultureIgnoreCase))
{
// Try deleting the workspace from the server.
if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace)))
{
// Otherwise fallback to deleting the workspace from the local computer.
await tf.WorkspacesRemoveAsync(tfWorkspace);
}
// Break out of this nested for loop only.
// Continue iterating over the rest of the workspaces.
break;
}
}
}
}
public static class WorkspaceUtil
{
public static ITfsVCWorkspace MatchExactWorkspace(
IExecutionContext executionContext,
ITfsVCWorkspace[] tfWorkspaces,
string name,
DefinitionWorkspaceMapping[] definitionMappings,
string sourcesDirectory)
{
ArgUtil.NotNullOrEmpty(name, nameof(name));
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
// Short-circuit early if the sources directory is empty.
//
// Consider the sources directory to be empty if it only contains a .tf directory exists. This can
// indicate the workspace is in a corrupted state and the tf commands (e.g. status) will not return
// reliable information. An easy way to reproduce this is to delete the workspace directory, then
// run "tf status" on that workspace. The .tf directory will be recreated but the contents will be
// in a corrupted state.
if (!Directory.Exists(sourcesDirectory) ||
!Directory.EnumerateFileSystemEntries(sourcesDirectory).Any(x => !x.EndsWith($"{Path.DirectorySeparatorChar}.tf")))
{
executionContext.Debug("Sources directory does not exist or is empty.");
return null;
}
string machineName = Environment.MachineName;
executionContext.Debug($"Attempting to find a workspace: '{name}'");
foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0])
{
// Compare the workspace name.
if (!string.Equals(tfWorkspace.Name, name, StringComparison.Ordinal))
{
executionContext.Debug($"Skipping workspace: '{tfWorkspace.Name}'");
continue;
}
executionContext.Debug($"Candidate workspace: '{tfWorkspace.Name}'");
// Compare the machine name.
if (!string.Equals(tfWorkspace.Computer, machineName, StringComparison.Ordinal))
{
executionContext.Debug($"Expected computer name: '{machineName}'. Actual: '{tfWorkspace.Computer}'");
continue;
}
// Compare the number of mappings.
if ((tfWorkspace.Mappings?.Length ?? 0) != (definitionMappings?.Length ?? 0))
{
executionContext.Debug($"Expected number of mappings: '{definitionMappings?.Length ?? 0}'. Actual: '{tfWorkspace.Mappings?.Length ?? 0}'");
continue;
}
// Sort the definition mappings.
List<DefinitionWorkspaceMapping> sortedDefinitionMappings =
(definitionMappings ?? new DefinitionWorkspaceMapping[0])
.OrderBy(x => x.MappingType != DefinitionMappingType.Cloak) // Cloaks first
.ThenBy(x => !x.Recursive) // Then recursive maps
.ThenBy(x => x.NormalizedServerPath) // Then sort by the normalized server path
.ToList();
for (int i = 0; i < sortedDefinitionMappings.Count; i++)
{
DefinitionWorkspaceMapping mapping = sortedDefinitionMappings[i];
executionContext.Debug($"Definition mapping[{i}]: cloak '{mapping.MappingType == DefinitionMappingType.Cloak}', recursive '{mapping.Recursive}', server path '{mapping.NormalizedServerPath}', local path '{mapping.GetRootedLocalPath(sourcesDirectory)}'");
}
// Sort the TF mappings.
List<ITfsVCMapping> sortedTFMappings =
(tfWorkspace.Mappings ?? new ITfsVCMapping[0])
.OrderBy(x => !x.Cloak) // Cloaks first
.ThenBy(x => !x.Recursive) // Then recursive maps
.ThenBy(x => x.ServerPath) // Then sort by server path
.ToList();
for (int i = 0; i < sortedTFMappings.Count; i++)
{
ITfsVCMapping mapping = sortedTFMappings[i];
executionContext.Debug($"Found mapping[{i}]: cloak '{mapping.Cloak}', recursive '{mapping.Recursive}', server path '{mapping.ServerPath}', local path '{mapping.LocalPath}'");
}
// Compare the mappings.
bool allMatch = true;
for (int i = 0; i < sortedTFMappings.Count; i++)
{
ITfsVCMapping tfMapping = sortedTFMappings[i];
DefinitionWorkspaceMapping definitionMapping = sortedDefinitionMappings[i];
// Compare the cloak flag.
bool expectedCloak = definitionMapping.MappingType == DefinitionMappingType.Cloak;
if (tfMapping.Cloak != expectedCloak)
{
executionContext.Debug($"Expected mapping[{i}] cloak: '{expectedCloak}'. Actual: '{tfMapping.Cloak}'");
allMatch = false;
break;
}
// Compare the recursive flag.
if (!expectedCloak && tfMapping.Recursive != definitionMapping.Recursive)
{
executionContext.Debug($"Expected mapping[{i}] recursive: '{definitionMapping.Recursive}'. Actual: '{tfMapping.Recursive}'");
allMatch = false;
break;
}
// Compare the server path. Normalize the expected server path for a single-level map.
string expectedServerPath = definitionMapping.NormalizedServerPath;
if (!string.Equals(tfMapping.ServerPath, expectedServerPath, StringComparison.Ordinal))
{
executionContext.Debug($"Expected mapping[{i}] server path: '{expectedServerPath}'. Actual: '{tfMapping.ServerPath}'");
allMatch = false;
break;
}
// Compare the local path.
if (!expectedCloak)
{
string expectedLocalPath = definitionMapping.GetRootedLocalPath(sourcesDirectory);
if (!string.Equals(tfMapping.LocalPath, expectedLocalPath, StringComparison.Ordinal))
{
executionContext.Debug($"Expected mapping[{i}] local path: '{expectedLocalPath}'. Actual: '{tfMapping.LocalPath}'");
allMatch = false;
break;
}
}
}
if (allMatch)
{
executionContext.Debug("Matching workspace found.");
return tfWorkspace;
}
}
executionContext.Debug("Matching workspace not found.");
return null;
}
}
public sealed class DefinitionWorkspaceMappings
{
public DefinitionWorkspaceMapping[] Mappings { get; set; }
}
public sealed class DefinitionWorkspaceMapping
{
public string LocalPath { get; set; }
public DefinitionMappingType MappingType { get; set; }
/// <summary>
/// Remove the trailing "/*" from the single-level mapping server path.
/// If the ServerPath is "$/*", then the normalized path is returned
/// as "$/" rather than "$".
/// </summary>
public string NormalizedServerPath
{
get
{
string path;
if (!Recursive)
{
// Trim the last two characters (i.e. "/*") from the single-level
// mapping server path.
path = ServerPath.Substring(0, ServerPath.Length - 2);
// Check if trimmed too much. This is important when comparing
// against workspaces on disk.
if (string.Equals(path, "$", StringComparison.Ordinal))
{
path = "$/";
}
}
else
{
path = ServerPath ?? string.Empty;
}
return path;
}
}
/// <summary>
/// Returns true if the path does not end with "/*".
/// </summary>
public bool Recursive => !(ServerPath ?? string.Empty).EndsWith("/*");
public string ServerPath { get; set; }
/// <summary>
/// Gets the rooted local path and normalizes slashes.
/// </summary>
public string GetRootedLocalPath(string sourcesDirectory)
{
// TEE normalizes all slashes in a workspace mapping to match the OS. It is not
// possible on OSX/Linux to have a workspace mapping with a backslash, even though
// backslash is a legal file name character.
string relativePath =
(LocalPath ?? string.Empty)
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar)
.Trim(Path.DirectorySeparatorChar);
return Path.Combine(sourcesDirectory, relativePath);
}
}
public enum DefinitionMappingType
{
Cloak,
Map,
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom.Compiler;
using System.IO;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Common
{
/// <summary>
///
/// A TestCase represents a C# source file that defines a test
/// case generated by Randoop. It has several properties, which
/// are specified as comments in the source code.
///
/// * LAST ACTION: the last method/constructor/field access
/// in the test case.
///
/// * EXCEPTION: the exception type that is thrown when the
/// test case executes.
///
/// * ASSEMBLIES: names of the assemblies that must be
/// references for the test case to compile.
///
/// * IMPORTS: namespaces required for the test case to compile.
///
/// * CLASSNAME: name of the class defined in the test case.
///
/// * TESTCODE: code that comprises the actual tests.
///
/// Below is an example of what a TestCase looks like as a file.
///
/// TODO update
/// //LAST ACTION: NodeType
/// //EXCEPTION: System.FormatException
/// using System.Xml;
/// using System;
/// public class RandoopTestCase3102
/// {
/// public static void Test()
/// {
/// try
/// {
/// //BEGIN TEST
/// System.Xml.XmlDocument v0 = new System.Xml.XmlDocument();
/// System.Xml.XmlNodeType v14 = ((System.Xml.XmlDocument)v13).NodeType;
/// //END TEST
/// }
/// catch (System.Exception e)
/// {
/// System.Console.Error.WriteLine("// EXCEPTION:"
/// + e.GetType().FullName);
/// }
/// }
/// }
/// //REFASSEMBLY: System.Xml.dll
///
/// </summary>
public class TestCase
{
public const string BEGIN_TEST_MARKER = "//BEGIN TEST";
public const string END_TEST_MARKER = "//END TEST";
public LastAction lastAction;
public ExceptionDescription exception;
private Collection<string> imports;
private Collection<RefAssembly> refAssemblies;
private string className;
private Collection<string> testCode;
public readonly Collection<string> testPlanCollection; //xiao.qu@us.abb.com adds to get call sequence for sequence-based reducer (11/05/2012)
private static ExceptionDescription assertionViolation = ExceptionDescription.GetDescription(typeof(Common.AssertionViolation));
/// <summary>
/// Create a TestCase by specifying all its components.
/// </summary>
public TestCase(LastAction lastAction, ExceptionDescription exception, Collection<string> imports,
Collection<string> assemblies, string className, Collection<string> testCode)
{
// Last action.
if (lastAction == null) throw new ArgumentNullException();
this.lastAction = lastAction;
// Exception.
if (exception == null) throw new ArgumentNullException();
this.exception = exception;
// Imports.
if (imports == null) throw new ArgumentNullException();
this.imports = new Collection<string>();
foreach (string s in imports)
{
if (s == null) throw new ArgumentNullException();
this.imports.Add(s);
}
// Referenced assemblies.
this.refAssemblies = new Collection<RefAssembly>();
foreach (string s in assemblies)
{
if (s == null) throw new ArgumentNullException();
this.refAssemblies.Add(new RefAssembly(RefAssembly.REFASSEMBLY_MARKER + s));
}
// Class name.
if (className == null) throw new ArgumentNullException();
this.className = className;
// Test code.
if (testCode == null) throw new ArgumentNullException();
this.testCode = new Collection<string>();
foreach (string s in testCode)
{
if (s == null) throw new ArgumentNullException();
this.testCode.Add(s);
}
}
/// <summary>
/// Creates a TestCase given a file.
/// IMPORTANT: KEEP IN SYNC WITH TestCase.Write().
/// </summary>
public TestCase(FileInfo filePath)
{
StreamReader reader = null;
try
{
reader = new StreamReader(filePath.FullName);
}
catch (Exception e)
{
Common.Enviroment.Fail("Encountered a problem when attempting to read file "
+ filePath
+ ". Exception message: "
+ e.Message);
}
string line;
try
{
// Read lastAction.
line = reader.ReadLine();
if (line == null || !line.StartsWith(LastAction.LASTACTION_MARKER)) throw new TestCaseParseException(filePath);
line = line.Trim();
this.lastAction = new LastAction(line);
// Read exception.
line = reader.ReadLine();
if (line == null || !line.StartsWith(ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER)) throw new TestCaseParseException(filePath);
line = line.Trim();
this.exception = new ExceptionDescription(line);
// Read imports.
this.imports = new Collection<string>();
while (((line = reader.ReadLine()) != null) && line.Trim().StartsWith("using"))
{
this.imports.Add(line.Trim());
}
// Read class name.
if (line == null || !line.Trim().StartsWith("public class")) throw new TestCaseParseException(filePath);
this.className = line.Trim().Substring("public class".Length);
// Read open bracket (class).
line = reader.ReadLine();
if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);
// Main method declaration line.
line = reader.ReadLine();
line = line.Trim();
if (line == null || !line.StartsWith("public static int")) throw new TestCaseParseException(filePath);
if (line == null || !line.EndsWith("()")) throw new TestCaseParseException(filePath);
// Read open bracket (method).
line = reader.ReadLine();
if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);
// Read "try".
line = reader.ReadLine();
if (line == null || !line.Trim().Equals("try")) throw new TestCaseParseException(filePath);
// Read open bracket (try).
line = reader.ReadLine();
if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);
// Read testCode.
this.testCode = new Collection<string>();
line = reader.ReadLine();
if (line == null || !line.Trim().Equals(BEGIN_TEST_MARKER)) throw new TestCaseParseException(filePath);
while (((line = reader.ReadLine()) != null) && !line.Trim().Equals(END_TEST_MARKER))
{
this.testCode.Add(line.Trim());
}
if (line == null || !line.Trim().Equals(END_TEST_MARKER)) throw new TestCaseParseException(filePath);
// Read test plan collections from testCode. --- xiao.qu@us.abb.com adds for sequence-based reducer
this.testPlanCollection = new Collection<string>();
bool planStart = false;
foreach (string testline in testCode)
{
if (testline.Trim().StartsWith("/*"))
{
planStart = true;
continue; //skip to the next line, the beginning of plans
}
if ((planStart == true) && !(testline.Trim().StartsWith("*/")))
{
if ((testline == null) || !testline.Trim().StartsWith("plan")) throw new TestCaseParseException(filePath);
this.testPlanCollection.Add(testline.Trim());
}
if (testline.Trim().StartsWith("*/")) break;
}
// Everything that remains to read are the assemblies referenced.
// Read assemblies referenced.
this.refAssemblies = new Collection<RefAssembly>();
while (((line = reader.ReadLine()) != null))
{
if (line.Trim().StartsWith(RefAssembly.REFASSEMBLY_MARKER))
{
this.refAssemblies.Add(new RefAssembly(line.Trim()));
}
}
}
finally
{
reader.Close();
}
}
public IEnumerable<string> Imports
{
get { return this.imports; }
}
/// <summary>
/// Writes this test case to a file.
/// </summary>
public void WriteToFile(string filePath, bool declareMainMethod)
{
using(var w = new StreamWriter(filePath))
Write(w);
}
/// <summary>
/// Writes this test case to a file.
/// </summary>
public void WriteToFile(FileInfo filePath, bool declareMainMethod)
{
using(var w = new StreamWriter(filePath.FullName))
Write(w);
}
/// <summary>
/// Writes this test case to a file.
/// IMPORTANT: KEEP IN SYNC WITH TestCase(string filePath).
/// </summary>
public void Write(TextWriter w)
{
w.WriteLine(this.lastAction.ToString());
w.WriteLine(this.exception.ToString());
foreach (string s in this.imports)
{
w.WriteLine(s);
}
//w.WriteLine("using System.Diagnostics;"); //xiao.qu@us.abb.com added
w.WriteLine("public class " + this.className);
w.WriteLine("{");
w.WriteLine(" public static int Main()");
w.WriteLine(" {");
w.WriteLine(" try");
w.WriteLine(" {");
w.WriteLine(" " + BEGIN_TEST_MARKER);
foreach (string s in this.testCode)
{
w.WriteLine(" " + s);
}
w.WriteLine(" " + END_TEST_MARKER);
if (this.exception.IsNoException())
{
w.WriteLine(" System.Console.WriteLine(\"This was expected behavior. Will exit with code 100.\");");
w.WriteLine(" return 100;");
}
else
{
w.WriteLine(" System.Console.WriteLine(\"This was unexpected behavior (expected an exception). Will exit with code 99.\");");
w.WriteLine(" return 99;");
}
w.WriteLine(" }");
// TODO the two clauses below mean the same thing. pick one and make sure it's used throughout.
if (!this.exception.IsNoException() && !this.exception.Equals(assertionViolation))
{
w.WriteLine(" catch (" + this.exception.exceptionDescriptionstring + " e)");
w.WriteLine(" {");
w.WriteLine(" System.Console.WriteLine(\""
+ ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER + "\" + e.GetType().FullName);");
w.WriteLine(" System.Console.WriteLine(\"This was expected behavior. Will exit with code 100.\");");
w.WriteLine(" return 100;");
w.WriteLine(" }");
}
if (!this.exception.Equals(ExceptionDescription.GetDescription(typeof(Exception))))
{
w.WriteLine(" catch (System.Exception e)");
w.WriteLine(" {");
w.WriteLine(" System.Console.WriteLine(\""
+ ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER + "\" + e.GetType().FullName);");
w.WriteLine(" System.Console.WriteLine(\"//STACK TRACE:\");");
w.WriteLine(" System.Console.WriteLine(e.StackTrace);");
w.WriteLine(" System.Console.WriteLine();");
w.WriteLine(" System.Console.WriteLine(\"This was unexpected behavior. Will exit with code 99.\");");
w.WriteLine(" return 99;");
w.WriteLine(" }");
}
w.WriteLine(" }");
w.WriteLine("}");
// Print referenced assemblies at the end
// to avoid too much ugliness at top of file.
foreach (RefAssembly ra in this.refAssemblies)
{
w.WriteLine(ra.ToString());
}
w.Flush();
w.Close();
}
/// <summary>
/// Writes this test case to a writer as a unit test.
/// Expects indentation already in place
/// </summary>
public void WriteAsUnitTest(IndentedTextWriter w, string testName)
{
w.WriteLine("[TestMethod]");
// TODO: expected exception
w.WriteLine("public void {0}()", testName);
w.WriteLine("{");
w.Indent++;
foreach (string s in this.testCode)
w.WriteLine(s);
w.Indent--;
w.WriteLine("}");
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
StringWriter w = new StringWriter(b);
Write(w);
return b.ToString();
}
public string RemoveLine(int line)
{
string retval = this.testCode[line];
this.testCode.RemoveAt(line);
return retval;
}
public int NumTestLines
{
get
{
return this.testCode.Count;
}
}
public void AddLine(int line, string oldLine)
{
this.testCode.Insert(line, oldLine);
}
public static TestCase Dummy(string className)
{
LastAction lastAction = new LastAction(LastAction.LASTACTION_MARKER + "none");
ExceptionDescription exception = ExceptionDescription.NoException();
Collection<string> imports = new Collection<string>();
Collection<string> assemblies = new Collection<string>();
Collection<string> testCode = new Collection<string>();
testCode.Add("/* Source code printing failed. */");
return new TestCase(lastAction, exception, imports, assemblies, className, testCode);
}
/// <summary>
/// Used to communicate the result of running a test case
/// as a separate process. See RunExternal().
/// </summary>
public class RunResults
{
public readonly CompilFailure compilationFailureReason;
/// <summary>
/// If !compilationSuccessful, contains the compiler errors.
/// Otherwise, set to null.
/// </summary>
public readonly CompilerErrorCollection compilerErrors;
public readonly bool compilationSuccessful;
public readonly bool behaviorReproduced;
public enum CompilFailure { MissingReference, Other, NA }
private RunResults(bool compilationSuccessful, bool behaviorReproduced,
CompilFailure reason, CompilerErrorCollection compilerErrors)
{
this.compilationFailureReason = reason;
this.compilationSuccessful = compilationSuccessful;
this.behaviorReproduced = behaviorReproduced;
this.compilerErrors = compilerErrors;
}
public static RunResults CompilationFailed(CompilFailure reason, CompilerErrorCollection errors)
{
return new RunResults(false, false, reason, errors);
}
public static RunResults CompiledOKBehaviorWasReproduced()
{
return new RunResults(true, true, CompilFailure.NA, null);
}
public static RunResults CompiledOKBehaviorNotReproduced()
{
return new RunResults(true, false, CompilFailure.NA, null);
}
}
/// <summary>
/// Executes this test case in a separate process.
/// Compares the result of the execution against the
/// recorded behavior.
///
/// Returns a description of the execution
/// (e.g. "behavior preserved" or "behavior not preserved"
/// or "compilation failed").
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public RunResults RunExternal()
{
// Set up compiler parameters.
CompilerParameters cp = new CompilerParameters();
AddReferenceLibraries(cp);
cp.GenerateExecutable = true;
cp.OutputAssembly = "Temp.exe";
cp.GenerateInMemory = false;
cp.TreatWarningsAsErrors = false;
// Compile sources.
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
CompilerResults cr = provider.CompileAssemblyFromSource(cp, this.ToString());
if (cr.Errors.Count > 0)
return AppropriateErrorResult(cr);
// Run test in separate process.
Process p = new Process();
p.StartInfo.FileName = Common.Enviroment.MiniDHandler;
p.StartInfo.RedirectStandardOutput = true;
StringBuilder arguments = new StringBuilder();
arguments.Append("/O:\"C:\\foobar.txt\"");
arguments.Append(" /I:" + "\"" + Common.Enviroment.DefaultDhi + "\"");
arguments.Append(" /App:\"Temp\"");
p.StartInfo.Arguments = arguments.ToString();
p.StartInfo.UseShellExecute = false;
p.StartInfo.ErrorDialog = true;
p.StartInfo.CreateNoWindow = false;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit(10000);
// Exit code 100 means behavior was reproduced.
if (p.ExitCode != 100)
{
return RunResults.CompiledOKBehaviorNotReproduced();
}
return RunResults.CompiledOKBehaviorWasReproduced();
}
private static RunResults AppropriateErrorResult(CompilerResults cr)
{
foreach (CompilerError error in cr.Errors)
{
if (error.ToString().Contains("is defined in an assembly that is not referenced"))
{
//Console.WriteLine("@@@" + error.ToString());
//Console.WriteLine("@@@" + this.ToString());
return RunResults.CompilationFailed(RunResults.CompilFailure.MissingReference, cr.Errors);
}
}
return RunResults.CompilationFailed(RunResults.CompilFailure.Other, cr.Errors);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public void AddReferenceLibraries(CompilerParameters cp)
{
bool addedSystem = false;
bool addedSystemXml = false;
bool addedSystemSecurity = false;
bool addedSystemData = false;
bool addedSystemDrawing = false;
foreach (RefAssembly ra in this.refAssemblies)
{
cp.ReferencedAssemblies.Add(ra.refAssemblyString);
String assemblyName = ra.refAssemblyString.ToLower();
if (assemblyName.EndsWith("system.dll"))
addedSystem = true;
else if (assemblyName.EndsWith("system.xml.dll"))
addedSystemXml = true;
else if (assemblyName.EndsWith("system.security.dll"))
addedSystemSecurity = true;
else if (assemblyName.EndsWith("system.data.dll"))
addedSystemData = true;
else if (assemblyName.EndsWith("system.drawing.dll"))
addedSystemDrawing = true;
}
// Add some standard assemblies by default.
if (!addedSystem)
cp.ReferencedAssemblies.Add("System.dll");
if (!addedSystemXml)
cp.ReferencedAssemblies.Add("System.Xml.dll");
if (!addedSystemSecurity)
cp.ReferencedAssemblies.Add("System.Security.dll");
if (!addedSystemData)
cp.ReferencedAssemblies.Add("System.Data.dll");
if (!addedSystemDrawing)
cp.ReferencedAssemblies.Add("System.Drawing.dll");
}
public class LastAction
{
public static readonly string LASTACTION_MARKER = "//LAST ACTION:";
public readonly string lastActionstring;
/// <summary>
/// The given string must be of the form LastAction.LASTACTION_MARKER + description-string.
/// </summary>
public LastAction(string s)
{
if (s == null) throw new ArgumentNullException("s");
s = s.Trim();
if (!s.StartsWith(LASTACTION_MARKER))
throw new ArgumentException("Last action description must start with "
+ LASTACTION_MARKER);
this.lastActionstring = s.Substring(LASTACTION_MARKER.Length).Trim();
}
public override string ToString()
{
return LASTACTION_MARKER + " " + lastActionstring;
}
public override bool Equals(object obj)
{
LastAction other = obj as LastAction;
if (other == null) return false;
return other.lastActionstring == this.lastActionstring;
}
public override int GetHashCode()
{
return this.lastActionstring.GetHashCode();
}
}
public class RefAssembly
{
public static readonly string REFASSEMBLY_MARKER = "//REFASSEMBLY:";
public readonly string refAssemblyString;
/// <summary>
/// The given string must be of the form RefAssembly.REFASSEMBLY_MARKER + description-string.
/// </summary>
public RefAssembly(string s)
{
if (s == null) throw new ArgumentNullException("s");
s = s.Trim();
if (!s.StartsWith(REFASSEMBLY_MARKER))
throw new ArgumentException("Ref assembly line must start with "
+ REFASSEMBLY_MARKER);
this.refAssemblyString = s.Substring(REFASSEMBLY_MARKER.Length).Trim();
}
public override string ToString()
{
return REFASSEMBLY_MARKER + " " + refAssemblyString;
}
public override bool Equals(object obj)
{
RefAssembly other = obj as RefAssembly;
if (other == null) return false;
return other.refAssemblyString == this.refAssemblyString;
}
public override int GetHashCode()
{
return this.refAssemblyString.GetHashCode();
}
}
[Serializable]
public class TestCaseParseException : Exception
{
public TestCaseParseException(FileInfo testFile)
: base(testFile.FullName)
{
// No body.
}
}
public class ExceptionDescription
{
public static readonly string EXCEPTION_DESCRIPTION_MARKER = "//EXCEPTION:";
private static readonly string NO_EXCEPTION_string = "none";
public readonly string exceptionDescriptionstring;
public string ExceptionDescriptionString
{
get
{
return exceptionDescriptionstring;
}
}
public static ExceptionDescription NoException()
{
return new ExceptionDescription(EXCEPTION_DESCRIPTION_MARKER + " " + NO_EXCEPTION_string);
}
public bool IsNoException()
{
return exceptionDescriptionstring.Equals(NO_EXCEPTION_string);
}
/// <summary>
/// Get the description corresponding to the given type.
/// </summary>
/// <param name="exceptionType">The type of the exception. Cannot be null.</param>
/// <returns></returns>
public static ExceptionDescription GetDescription(Type exceptionType)
{
if (exceptionType == null) throw new ArgumentNullException("exceptionType");
return new ExceptionDescription(ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER
+ SourceCodePrinting.ToCodeString(exceptionType));
}
/// <summary>
/// The given string must be of the form ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER + description-string.
/// </summary>
internal ExceptionDescription(string s)
{
if (s == null) throw new ArgumentNullException();
s = s.Trim();
if (!s.StartsWith(EXCEPTION_DESCRIPTION_MARKER)) throw new ArgumentException("malformed string s");
this.exceptionDescriptionstring = s.Substring(EXCEPTION_DESCRIPTION_MARKER.Length).Trim();
}
public override string ToString()
{
return EXCEPTION_DESCRIPTION_MARKER + " " + exceptionDescriptionstring;
}
public override bool Equals(object obj)
{
ExceptionDescription other = obj as ExceptionDescription;
if (other == null) return false;
return other.exceptionDescriptionstring == this.exceptionDescriptionstring;
}
public override int GetHashCode()
{
return this.exceptionDescriptionstring.GetHashCode();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using WindowsInput;
using WindowsInput.Native;
using NLog;
using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.Storage;
using Wox.Infrastructure;
using Application = System.Windows.Application;
using Control = System.Windows.Controls.Control;
using Keys = System.Windows.Forms.Keys;
namespace Wox.Plugin.Shell
{
public class Main : IPlugin, ISettingProvider, IPluginI18n, IContextMenu, ISavable
{
private const string Image = "Images/shell.png";
private PluginInitContext _context;
private bool _winRStroked;
private readonly KeyboardSimulator _keyboardSimulator = new KeyboardSimulator(new InputSimulator());
private readonly Settings _settings;
private readonly PluginJsonStorage<Settings> _storage;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public Main()
{
_storage = new PluginJsonStorage<Settings>();
_settings = _storage.Load();
}
public void Save()
{
_storage.Save();
}
public List<Result> Query(Query query)
{
List<Result> results = new List<Result>();
string cmd = query.Search;
if (string.IsNullOrEmpty(cmd))
{
return ResultsFromlHistory();
}
else
{
var queryCmd = GetCurrentCmd(cmd);
results.Add(queryCmd);
var history = GetHistoryCmds(cmd, queryCmd);
results.AddRange(history);
try
{
string basedir = null;
string dir = null;
string excmd = Environment.ExpandEnvironmentVariables(cmd);
if (Directory.Exists(excmd) && (cmd.EndsWith("/") || cmd.EndsWith(@"\")))
{
basedir = excmd;
dir = cmd;
}
else if (Directory.Exists(Path.GetDirectoryName(excmd) ?? string.Empty))
{
basedir = Path.GetDirectoryName(excmd);
var dirn = Path.GetDirectoryName(cmd);
dir = (dirn.EndsWith("/") || dirn.EndsWith(@"\")) ? dirn : cmd.Substring(0, dirn.Length + 1);
}
if (basedir != null)
{
var autocomplete = Directory.GetFileSystemEntries(basedir).
Select(o => dir + Path.GetFileName(o)).
Where(o => o.StartsWith(cmd, StringComparison.OrdinalIgnoreCase) &&
!results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase)) &&
!results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase))).ToList();
autocomplete.Sort();
results.AddRange(autocomplete.ConvertAll(m => new Result
{
Title = m,
IcoPath = Image,
Action = c =>
{
Execute(Process.Start, PrepareProcessStartInfo(m));
return true;
}
}));
}
}
catch (Exception e)
{
Logger.WoxError($"Exception when query for <{query}>", e);
}
return results;
}
}
private List<Result> GetHistoryCmds(string cmd, Result result)
{
IEnumerable<Result> history = _settings.Count.Where(o => o.Key.Contains(cmd))
.OrderByDescending(o => o.Value)
.Select(m =>
{
if (m.Key == cmd)
{
result.SubTitle = string.Format(_context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value);
return null;
}
var ret = new Result
{
Title = m.Key,
SubTitle = string.Format(_context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
IcoPath = Image,
Action = c =>
{
Execute(Process.Start, PrepareProcessStartInfo(m.Key));
return true;
}
};
return ret;
}).Where(o => o != null).Take(4);
return history.ToList();
}
private Result GetCurrentCmd(string cmd)
{
Result result = new Result
{
Title = cmd,
Score = 5000,
SubTitle = _context.API.GetTranslation("wox_plugin_cmd_execute_through_shell"),
IcoPath = Image,
Action = c =>
{
Execute(Process.Start, PrepareProcessStartInfo(cmd));
return true;
}
};
return result;
}
private List<Result> ResultsFromlHistory()
{
IEnumerable<Result> history = _settings.Count.OrderByDescending(o => o.Value)
.Select(m => new Result
{
Title = m.Key,
SubTitle = string.Format(_context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
IcoPath = Image,
Action = c =>
{
Execute(Process.Start, PrepareProcessStartInfo(m.Key));
return true;
}
}).Take(5);
return history.ToList();
}
private ProcessStartInfo PrepareProcessStartInfo(string command, bool runAsAdministrator = false)
{
command = command.Trim();
command = Environment.ExpandEnvironmentVariables(command);
var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var runAsAdministratorArg = !runAsAdministrator && !_settings.RunAsAdministrator ? "" : "runas";
ProcessStartInfo info;
if (_settings.Shell == Shell.Cmd)
{
var arguments = _settings.LeaveShellOpen ? $"/k \"{command}\"" : $"/c \"{command}\" & pause";
info = ShellCommand.SetProcessStartInfo("cmd.exe", workingDirectory, arguments, runAsAdministratorArg);
}
else if (_settings.Shell == Shell.Powershell)
{
string arguments;
if (_settings.LeaveShellOpen)
{
arguments = $"-NoExit \"{command}\"";
}
else
{
arguments = $"\"{command} ; Read-Host -Prompt \\\"Press Enter to continue\\\"\"";
}
info = ShellCommand.SetProcessStartInfo("powershell.exe", workingDirectory, arguments, runAsAdministratorArg);
}
else if (_settings.Shell == Shell.RunCommand)
{
var parts = command.Split(new[] { ' ' }, 2);
if (parts.Length == 2)
{
var filename = parts[0];
if (ExistInPath(filename))
{
var arguments = parts[1];
info = ShellCommand.SetProcessStartInfo(filename, workingDirectory, arguments, runAsAdministratorArg);
}
else
{
info = ShellCommand.SetProcessStartInfo(command, verb: runAsAdministratorArg);
}
}
else
{
info = ShellCommand.SetProcessStartInfo(command, verb: runAsAdministratorArg);
}
}
else if (_settings.Shell == Shell.Bash && _settings.SupportWSL)
{
string arguments;
if (_settings.LeaveShellOpen)
{
// FIXME: How to deal with commands containing single quote?
arguments = $"-c \'{command} ; $SHELL\'";
}
else
{
arguments = $"-c \'{command} ; echo -n Press any key to exit... ; read -n1\'";
}
info = new ProcessStartInfo
{
FileName = "bash.exe",
Arguments = arguments
};
}
else
{
throw new NotImplementedException();
}
info.UseShellExecute = true;
_settings.AddCmdHistory(command);
return info;
}
private void Execute(Func<ProcessStartInfo, Process> startProcess,ProcessStartInfo info)
{
try
{
startProcess(info);
}
catch (FileNotFoundException e)
{
var name = "Plugin: Shell";
var message = $"Command not found: {e.Message}";
_context.API.ShowMsg(name, message);
}
catch(Win32Exception e)
{
var name = "Plugin: Shell";
var message = $"Error running the command: {e.Message}";
_context.API.ShowMsg(name, message);
}
}
private bool ExistInPath(string filename)
{
if (File.Exists(filename))
{
return true;
}
else
{
var values = Environment.GetEnvironmentVariable("PATH");
if (values != null)
{
foreach (var path in values.Split(';'))
{
var path1 = Path.Combine(path, filename);
var path2 = Path.Combine(path, filename + ".exe");
if (File.Exists(path1) || File.Exists(path2))
{
return true;
}
}
return false;
}
else
{
return false;
}
}
}
public void Init(PluginInitContext context)
{
this._context = context;
context.API.GlobalKeyboardEvent += API_GlobalKeyboardEvent;
}
bool API_GlobalKeyboardEvent(int keyevent, int vkcode, SpecialKeyState state)
{
if (_settings.ReplaceWinR)
{
if (keyevent == (int)KeyEvent.WM_KEYDOWN && vkcode == (int)Keys.R && state.WinPressed)
{
_winRStroked = true;
OnWinRPressed();
return false;
}
if (keyevent == (int)KeyEvent.WM_KEYUP && _winRStroked && vkcode == (int)Keys.LWin)
{
_winRStroked = false;
_keyboardSimulator.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL);
return false;
}
}
return true;
}
private void OnWinRPressed()
{
_context.API.ChangeQuery($"{_context.CurrentPluginMetadata.ActionKeywords[0]}{Plugin.Query.TermSeperater}");
Application.Current.MainWindow.Visibility = Visibility.Visible;
}
public Control CreateSettingPanel()
{
return new CMDSetting(_settings);
}
public string GetTranslatedPluginTitle()
{
return _context.API.GetTranslation("wox_plugin_cmd_plugin_name");
}
public string GetTranslatedPluginDescription()
{
return _context.API.GetTranslation("wox_plugin_cmd_plugin_description");
}
public List<Result> LoadContextMenus(Result selectedResult)
{
var resultlist = new List<Result>
{
new Result
{
Title = _context.API.GetTranslation("wox_plugin_cmd_run_as_different_user"),
Action = c =>
{
Task.Run(() =>Execute(ShellCommand.RunAsDifferentUser, PrepareProcessStartInfo(selectedResult.Title)));
return true;
},
IcoPath = "Images/app.png"
},
new Result
{
Title = _context.API.GetTranslation("wox_plugin_cmd_run_as_administrator"),
Action = c =>
{
Execute(Process.Start, PrepareProcessStartInfo(selectedResult.Title, true));
return true;
},
IcoPath = Image
}
};
return resultlist;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System;
using System.Globalization;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
internal class DynamicILGenerator : ILGenerator
{
internal DynamicScope m_scope;
private int m_methodSigToken;
internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size)
: base(method, size)
{
m_scope = new DynamicScope();
m_methodSigToken = m_scope.GetTokenFor(methodSignature);
}
[System.Security.SecurityCritical] // auto-generated
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module,
m_methodBuilder.Name,
(byte[])m_scope[m_methodSigToken],
new DynamicResolver(this));
}
#if FEATURE_APPX
private bool ProfileAPICheck
{
get
{
return ((DynamicMethod)m_methodBuilder).ProfileAPICheck;
}
}
#endif // FEATURE_APPX
// *** ILGenerator api ***
public override LocalBuilder DeclareLocal(Type localType, bool pinned)
{
LocalBuilder localBuilder;
if (localType == null)
throw new ArgumentNullException("localType");
Contract.EndContractBlock();
RuntimeType rtType = localType as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
#if FEATURE_APPX
if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif
localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder);
// add the localType to local signature
m_localSignature.AddArgument(localType, pinned);
m_localCount++;
return localBuilder;
}
//
//
// Token resolution calls
//
//
[System.Security.SecuritySafeCritical] // auto-generated
public override void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
throw new ArgumentNullException("meth");
Contract.EndContractBlock();
int stackchange = 0;
int token = 0;
DynamicMethod dynMeth = meth as DynamicMethod;
if (dynMeth == null)
{
RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
if (rtMeth == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "meth");
RuntimeType declaringType = rtMeth.GetRuntimeType();
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
token = GetTokenFor(rtMeth, declaringType);
else
token = GetTokenFor(rtMeth);
}
else
{
// rule out not allowed operations on DynamicMethods
if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn))
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod"));
}
token = GetTokenFor(dynMeth);
}
EnsureCapacity(7);
InternalEmit(opcode);
if (opcode.StackBehaviourPush == StackBehaviour.Varpush
&& meth.ReturnType != typeof(void))
{
stackchange++;
}
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
stackchange -= meth.GetParametersNoCopy().Length;
}
// Pop the "this" parameter if the method is non-static,
// and the instruction is not newobj/ldtoken/ldftn.
if (!meth.IsStatic &&
!(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn)))
{
stackchange--;
}
UpdateStackSize(opcode, stackchange);
PutInteger4(token);
}
[System.Runtime.InteropServices.ComVisible(true)]
public override void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
throw new ArgumentNullException("con");
Contract.EndContractBlock();
RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "con");
RuntimeType declaringType = rtConstructor.GetRuntimeType();
int token;
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
// need to sort out the stack size story
token = GetTokenFor(rtConstructor, declaringType);
else
token = GetTokenFor(rtConstructor);
EnsureCapacity(7);
InternalEmit(opcode);
// need to sort out the stack size story
UpdateStackSize(opcode, 1);
PutInteger4(token);
}
public override void Emit(OpCode opcode, Type type)
{
if (type == null)
throw new ArgumentNullException("type");
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
int token = GetTokenFor(rtType);
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(token);
}
public override void Emit(OpCode opcode, FieldInfo field)
{
if (field == null)
throw new ArgumentNullException("field");
Contract.EndContractBlock();
RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "field");
int token;
if (field.DeclaringType == null)
token = GetTokenFor(runtimeField);
else
token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType());
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(token);
}
public override void Emit(OpCode opcode, String str)
{
if (str == null)
throw new ArgumentNullException("str");
Contract.EndContractBlock();
int tempVal = GetTokenForString(str);
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(tempVal);
}
//
//
// Signature related calls (vararg, calli)
//
//
[System.Security.SecuritySafeCritical] // overrides SC
public override void EmitCalli(OpCode opcode,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
int stackchange = 0;
SignatureHelper sig;
if (optionalParameterTypes != null)
if ((callingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
sig = GetMemberRefSignature(callingConvention,
returnType,
parameterTypes,
optionalParameterTypes);
EnsureCapacity(7);
Emit(OpCodes.Calli);
// If there is a non-void return type, push one.
if (returnType != typeof(void))
stackchange++;
// Pop off arguments if any.
if (parameterTypes != null)
stackchange -= parameterTypes.Length;
// Pop off vararg arguments.
if (optionalParameterTypes != null)
stackchange -= optionalParameterTypes.Length;
// Pop the this parameter if the method has a this parameter.
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
stackchange--;
// Pop the native function pointer.
stackchange--;
UpdateStackSize(OpCodes.Calli, stackchange);
int token = GetTokenForSig(sig.GetSignature(true));
PutInteger4(token);
}
public override void EmitCalli(OpCode opcode,
CallingConvention unmanagedCallConv,
Type returnType,
Type[] parameterTypes)
{
int stackchange = 0;
int cParams = 0;
int i;
SignatureHelper sig;
if (parameterTypes != null)
cParams = parameterTypes.Length;
sig = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType);
if (parameterTypes != null)
for (i = 0; i < cParams; i++)
sig.AddArgument(parameterTypes[i]);
// If there is a non-void return type, push one.
if (returnType != typeof(void))
stackchange++;
// Pop off arguments if any.
if (parameterTypes != null)
stackchange -= cParams;
// Pop the native function pointer.
stackchange--;
UpdateStackSize(OpCodes.Calli, stackchange);
EnsureCapacity(7);
Emit(OpCodes.Calli);
int token = GetTokenForSig(sig.GetSignature(true));
PutInteger4(token);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
throw new ArgumentNullException("methodInfo");
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");
if (methodInfo.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");
if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");
Contract.EndContractBlock();
int tk;
int stackchange = 0;
tk = GetMemberRefToken(methodInfo, optionalParameterTypes);
EnsureCapacity(7);
InternalEmit(opcode);
// Push the return value if there is one.
if (methodInfo.ReturnType != typeof(void))
stackchange++;
// Pop the parameters.
stackchange -= methodInfo.GetParameterTypes().Length;
// Pop the this parameter if the method is non-static and the
// instruction is not newobj.
if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
stackchange--;
// Pop the optional parameters off the stack.
if (optionalParameterTypes != null)
stackchange -= optionalParameterTypes.Length;
UpdateStackSize(opcode, stackchange);
PutInteger4(tk);
}
public override void Emit(OpCode opcode, SignatureHelper signature)
{
if (signature == null)
throw new ArgumentNullException("signature");
Contract.EndContractBlock();
int stackchange = 0;
EnsureCapacity(7);
InternalEmit(opcode);
// The only IL instruction that has VarPop behaviour, that takes a
// Signature token as a parameter is calli. Pop the parameters and
// the native function pointer. To be conservative, do not pop the
// this pointer since this information is not easily derived from
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
Contract.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
// Pop native function pointer off the stack.
stackchange--;
UpdateStackSize(opcode, stackchange);
}
int token = GetTokenForSig(signature.GetSignature(true)); ;
PutInteger4(token);
}
//
//
// Exception related generation
//
//
public override Label BeginExceptionBlock()
{
return base.BeginExceptionBlock();
}
public override void EndExceptionBlock()
{
base.EndExceptionBlock();
}
public override void BeginExceptFilterBlock()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void BeginCatchBlock(Type exceptionType)
{
if (CurrExcStackCount == 0)
throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
Contract.EndContractBlock();
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
RuntimeType rtType = exceptionType as RuntimeType;
if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
{
if (exceptionType != null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
}
this.Emit(OpCodes.Endfilter);
}
else
{
// execute this branch if previous clause is Catch or Fault
if (exceptionType == null)
throw new ArgumentNullException("exceptionType");
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
Label endLabel = current.GetEndLabel();
this.Emit(OpCodes.Leave, endLabel);
// if this is a catch block the exception will be pushed on the stack and we need to update the stack info
UpdateStackSize(OpCodes.Nop, 1);
}
current.MarkCatchAddr(ILOffset, exceptionType);
// this is relying on too much implementation details of the base and so it's highly breaking
// Need to have a more integreted story for exceptions
current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType);
}
public override void BeginFaultBlock()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void BeginFinallyBlock()
{
base.BeginFinallyBlock();
}
//
//
// debugger related calls.
//
//
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void UsingNamespace(String ns)
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void MarkSequencePoint(ISymbolDocumentWriter document,
int startLine,
int startColumn,
int endLine,
int endColumn)
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void BeginScope()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void EndScope()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
[System.Security.SecurityCritical] // auto-generated
private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
{
Type[] parameterTypes;
if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo;
DynamicMethod dm = methodInfo as DynamicMethod;
if (rtMeth == null && dm == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "methodInfo");
ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy();
if (paramInfo != null && paramInfo.Length != 0)
{
parameterTypes = new Type[paramInfo.Length];
for (int i = 0; i < paramInfo.Length; i++)
parameterTypes[i] = paramInfo[i].ParameterType;
}
else
{
parameterTypes = null;
}
SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention,
MethodBuilder.GetMethodBaseReturnType(methodInfo),
parameterTypes,
optionalParameterTypes);
if (rtMeth != null)
return GetTokenForVarArgMethod(rtMeth, sig);
else
return GetTokenForVarArgMethod(dm, sig);
}
[System.Security.SecurityCritical] // auto-generated
internal override SignatureHelper GetMemberRefSignature(
CallingConventions call,
Type returnType,
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
int cParams;
int i;
SignatureHelper sig;
if (parameterTypes == null)
cParams = 0;
else
cParams = parameterTypes.Length;
sig = SignatureHelper.GetMethodSigHelper(call, returnType);
for (i = 0; i < cParams; i++)
sig.AddArgument(parameterTypes[i]);
if (optionalParameterTypes != null && optionalParameterTypes.Length != 0)
{
// add the sentinel
sig.AddSentinel();
for (i = 0; i < optionalParameterTypes.Length; i++)
sig.AddArgument(optionalParameterTypes[i]);
}
return sig;
}
internal override void RecordTokenFixup()
{
// DynamicMethod doesn't need fixup.
}
#region GetTokenFor helpers
private int GetTokenFor(RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif
return m_scope.GetTokenFor(rtType.TypeHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
RtFieldInfo rtField = runtimeField as RtFieldInfo;
if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
}
#endif
return m_scope.GetTokenFor(runtimeField.FieldHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
RtFieldInfo rtField = runtimeField as RtFieldInfo;
if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(DynamicMethod dm)
{
return m_scope.GetTokenFor(dm);
}
private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig);
return m_scope.GetTokenFor(varArgMeth);
}
private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig)
{
VarArgMethod varArgMeth = new VarArgMethod(dm, sig);
return m_scope.GetTokenFor(varArgMeth);
}
private int GetTokenForString(String s)
{
return m_scope.GetTokenFor(s);
}
private int GetTokenForSig(byte[] sig)
{
return m_scope.GetTokenFor(sig);
}
#endregion
}
internal class DynamicResolver : Resolver
{
#region Private Data Members
private __ExceptionInfo[] m_exceptions;
private byte[] m_exceptionHeader;
private DynamicMethod m_method;
private byte[] m_code;
private byte[] m_localSignature;
private int m_stackSize;
private DynamicScope m_scope;
#endregion
#region Internal Methods
internal DynamicResolver(DynamicILGenerator ilGenerator)
{
m_stackSize = ilGenerator.GetMaxStackSize();
m_exceptions = ilGenerator.GetExceptions();
m_code = ilGenerator.BakeByteArray();
m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray();
m_scope = ilGenerator.m_scope;
m_method = (DynamicMethod)ilGenerator.m_methodBuilder;
m_method.m_resolver = this;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DynamicResolver(DynamicILInfo dynamicILInfo)
{
m_stackSize = dynamicILInfo.MaxStackSize;
m_code = dynamicILInfo.Code;
m_localSignature = dynamicILInfo.LocalSignature;
m_exceptionHeader = dynamicILInfo.Exceptions;
//m_exceptions = dynamicILInfo.Exceptions;
m_scope = dynamicILInfo.DynamicScope;
m_method = dynamicILInfo.DynamicMethod;
m_method.m_resolver = this;
}
//
// We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus
// nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed
// part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization,
// or we can be running during shutdown where everything is finalized.
//
// The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle
// is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to
// destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle
// points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer
// is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt
// to do the destruction after next GC.
//
// The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs
// during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static.
//
~DynamicResolver()
{
DynamicMethod method = m_method;
if (method == null)
return;
if (method.m_methodHandle == null)
return;
DestroyScout scout = null;
try
{
scout = new DestroyScout();
}
catch
{
// We go over all DynamicMethodDesc during AppDomain shutdown and make sure
// that everything associated with them is released. So it is ok to skip reregistration
// for finalization during appdomain shutdown
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
// Try again later.
GC.ReRegisterForFinalize(this);
}
return;
}
// We can never ever have two active destroy scouts for the same method. We need to initialize the scout
// outside the try/reregister block to avoid possibility of reregistration for finalization with active scout.
scout.m_methodHandle = method.m_methodHandle.Value;
}
private class DestroyScout
{
internal RuntimeMethodHandleInternal m_methodHandle;
[System.Security.SecuritySafeCritical] // auto-generated
~DestroyScout()
{
if (m_methodHandle.IsNullHandle())
return;
// It is not safe to destroy the method if the managed resolver is alive.
if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null)
{
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
// Somebody might have been holding a reference on us via weak handle.
// We will keep trying. It will be hopefully released eventually.
GC.ReRegisterForFinalize(this);
}
return;
}
RuntimeMethodHandle.Destroy(m_methodHandle);
}
}
// Keep in sync with vm/dynamicmethod.h
[Flags]
internal enum SecurityControlFlags
{
Default = 0x0,
SkipVisibilityChecks = 0x1,
RestrictedSkipVisibilityChecks = 0x2,
HasCreationContext = 0x4,
CanSkipCSEvaluation = 0x8,
}
internal override RuntimeType GetJitContext(ref int securityControlFlags)
{
RuntimeType typeOwner;
SecurityControlFlags flags = SecurityControlFlags.Default;
if (m_method.m_restrictedSkipVisibility)
flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks;
else if (m_method.m_skipVisibility)
flags |= SecurityControlFlags.SkipVisibilityChecks;
typeOwner = m_method.m_typeOwner;
#if FEATURE_COMPRESSEDSTACK
if (m_method.m_creationContext != null)
{
flags |= SecurityControlFlags.HasCreationContext;
if(m_method.m_creationContext.CanSkipEvaluation)
{
flags |= SecurityControlFlags.CanSkipCSEvaluation;
}
}
#endif // FEATURE_COMPRESSEDSTACK
securityControlFlags = (int)flags;
return typeOwner;
}
private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
int num = 0;
if (excp == null)
return 0;
for (int i = 0; i < excp.Length; i++)
num += excp[i].GetNumberOfCatches();
return num;
}
internal override byte[] GetCodeInfo(
ref int stackSize, ref int initLocals, ref int EHCount)
{
stackSize = m_stackSize;
if (m_exceptionHeader != null && m_exceptionHeader.Length != 0)
{
if (m_exceptionHeader.Length < 4)
throw new FormatException();
byte header = m_exceptionHeader[0];
if ((header & 0x40) != 0) // Fat
{
byte[] size = new byte[4];
for (int q = 0; q < 3; q++)
size[q] = m_exceptionHeader[q + 1];
EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24;
}
else
EHCount = (m_exceptionHeader[1] - 2) / 12;
}
else
{
EHCount = CalculateNumberOfExceptions(m_exceptions);
}
initLocals = (m_method.InitLocals) ? 1 : 0;
return m_code;
}
internal override byte[] GetLocalsSignature()
{
return m_localSignature;
}
internal override unsafe byte[] GetRawEHInfo()
{
return m_exceptionHeader;
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe void GetEHInfo(int excNumber, void* exc)
{
CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc;
for (int i = 0; i < m_exceptions.Length; i++)
{
int excCount = m_exceptions[i].GetNumberOfCatches();
if (excNumber < excCount)
{
// found the right exception block
exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber];
exception->TryOffset = m_exceptions[i].GetStartAddress();
if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally)
exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset;
else
exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset;
exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber];
exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset;
// this is cheating because the filter address is the token of the class only for light code gen
exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber];
break;
}
excNumber -= excCount;
}
}
internal override String GetStringLiteral(int token) { return m_scope.GetString(token); }
#if FEATURE_COMPRESSEDSTACK
internal override CompressedStack GetSecurityContext()
{
return m_method.m_creationContext;
}
#endif // FEATURE_COMPRESSEDSTACK
[System.Security.SecurityCritical]
internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
{
typeHandle = new IntPtr();
methodHandle = new IntPtr();
fieldHandle = new IntPtr();
Object handle = m_scope[token];
if (handle == null)
throw new InvalidProgramException();
if (handle is RuntimeTypeHandle)
{
typeHandle = ((RuntimeTypeHandle)handle).Value;
return;
}
if (handle is RuntimeMethodHandle)
{
methodHandle = ((RuntimeMethodHandle)handle).Value;
return;
}
if (handle is RuntimeFieldHandle)
{
fieldHandle = ((RuntimeFieldHandle)handle).Value;
return;
}
DynamicMethod dm = handle as DynamicMethod;
if (dm != null)
{
methodHandle = dm.GetMethodDescriptor().Value;
return;
}
GenericMethodInfo gmi = handle as GenericMethodInfo;
if (gmi != null)
{
methodHandle = gmi.m_methodHandle.Value;
typeHandle = gmi.m_context.Value;
return;
}
GenericFieldInfo gfi = handle as GenericFieldInfo;
if (gfi != null)
{
fieldHandle = gfi.m_fieldHandle.Value;
typeHandle = gfi.m_context.Value;
return;
}
VarArgMethod vaMeth = handle as VarArgMethod;
if (vaMeth != null)
{
if (vaMeth.m_dynamicMethod == null)
{
methodHandle = vaMeth.m_method.MethodHandle.Value;
typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value;
}
else
methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value;
return;
}
}
internal override byte[] ResolveSignature(int token, int fromMethod)
{
return m_scope.ResolveSignature(token, fromMethod);
}
internal override MethodInfo GetDynamicMethod()
{
return m_method.GetMethodInfo();
}
#endregion
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public class DynamicILInfo
{
#region Private Data Members
private DynamicMethod m_method;
private DynamicScope m_scope;
private byte[] m_exceptions;
private byte[] m_code;
private byte[] m_localSignature;
private int m_maxStackSize;
private int m_methodSignature;
#endregion
#region Constructor
internal DynamicILInfo(DynamicScope scope, DynamicMethod method, byte[] methodSignature)
{
m_method = method;
m_scope = scope;
m_methodSignature = m_scope.GetTokenFor(methodSignature);
m_exceptions = EmptyArray<Byte>.Value;
m_code = EmptyArray<Byte>.Value;
m_localSignature = EmptyArray<Byte>.Value;
}
#endregion
#region Internal Methods
[System.Security.SecurityCritical] // auto-generated
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this));
}
internal byte[] LocalSignature
{
get
{
if (m_localSignature == null)
m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray();
return m_localSignature;
}
}
internal byte[] Exceptions { get { return m_exceptions; } }
internal byte[] Code { get { return m_code; } }
internal int MaxStackSize { get { return m_maxStackSize; } }
#endregion
#region Public ILGenerator Methods
public DynamicMethod DynamicMethod { get { return m_method; } }
internal DynamicScope DynamicScope { get { return m_scope; } }
public void SetCode(byte[] code, int maxStackSize)
{
m_code = (code != null) ? (byte[])code.Clone() : EmptyArray<Byte>.Value;
m_maxStackSize = maxStackSize;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetCode(byte* code, int codeSize, int maxStackSize)
{
if (codeSize < 0)
throw new ArgumentOutOfRangeException("codeSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (codeSize > 0 && code == null)
throw new ArgumentNullException("code");
Contract.EndContractBlock();
m_code = new byte[codeSize];
for (int i = 0; i < codeSize; i++)
{
m_code[i] = *code;
code++;
}
m_maxStackSize = maxStackSize;
}
public void SetExceptions(byte[] exceptions)
{
m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetExceptions(byte* exceptions, int exceptionsSize)
{
if (exceptionsSize < 0)
throw new ArgumentOutOfRangeException("exceptionsSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (exceptionsSize > 0 && exceptions == null)
throw new ArgumentNullException("exceptions");
Contract.EndContractBlock();
m_exceptions = new byte[exceptionsSize];
for (int i = 0; i < exceptionsSize; i++)
{
m_exceptions[i] = *exceptions;
exceptions++;
}
}
public void SetLocalSignature(byte[] localSignature)
{
m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetLocalSignature(byte* localSignature, int signatureSize)
{
if (signatureSize < 0)
throw new ArgumentOutOfRangeException("signatureSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (signatureSize > 0 && localSignature == null)
throw new ArgumentNullException("localSignature");
Contract.EndContractBlock();
m_localSignature = new byte[signatureSize];
for (int i = 0; i < signatureSize; i++)
{
m_localSignature[i] = *localSignature;
localSignature++;
}
}
#endregion
#region Public Scope Methods
[System.Security.SecuritySafeCritical] // auto-generated
public int GetTokenFor(RuntimeMethodHandle method)
{
return DynamicScope.GetTokenFor(method);
}
public int GetTokenFor(DynamicMethod method)
{
return DynamicScope.GetTokenFor(method);
}
public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle contextType)
{
return DynamicScope.GetTokenFor(method, contextType);
}
public int GetTokenFor(RuntimeFieldHandle field)
{
return DynamicScope.GetTokenFor(field);
}
public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle contextType)
{
return DynamicScope.GetTokenFor(field, contextType);
}
public int GetTokenFor(RuntimeTypeHandle type)
{
return DynamicScope.GetTokenFor(type);
}
public int GetTokenFor(string literal)
{
return DynamicScope.GetTokenFor(literal);
}
public int GetTokenFor(byte[] signature)
{
return DynamicScope.GetTokenFor(signature);
}
#endregion
}
internal class DynamicScope
{
#region Private Data Members
internal List<Object> m_tokens;
#endregion
#region Constructor
internal unsafe DynamicScope()
{
m_tokens = new List<Object>();
m_tokens.Add(null);
}
#endregion
#region Internal Methods
internal object this[int token]
{
get
{
token &= 0x00FFFFFF;
if (token < 0 || token > m_tokens.Count)
return null;
return m_tokens[token];
}
}
internal int GetTokenFor(VarArgMethod varArgMethod)
{
m_tokens.Add(varArgMethod);
return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef;
}
internal string GetString(int token) { return this[token] as string; }
internal byte[] ResolveSignature(int token, int fromMethod)
{
if (fromMethod == 0)
return (byte[])this[token];
VarArgMethod vaMethod = this[token] as VarArgMethod;
if (vaMethod == null)
return null;
return vaMethod.m_signature.GetSignature(true);
}
#endregion
#region Public Methods
[System.Security.SecuritySafeCritical] // auto-generated
public int GetTokenFor(RuntimeMethodHandle method)
{
IRuntimeMethodInfo methodReal = method.GetMethodInfo();
RuntimeMethodHandleInternal rmhi = methodReal.Value;
if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi))
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi);
if ((type != null) && RuntimeTypeHandle.HasInstantiation(type))
{
// Do we really need to retrieve this much info just to throw an exception?
MethodBase m = RuntimeType.GetMethodBase(methodReal);
Type t = m.DeclaringType.GetGenericTypeDefinition();
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t));
}
}
m_tokens.Add(method);
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext)
{
m_tokens.Add(new GenericMethodInfo(method, typeContext));
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(DynamicMethod method)
{
m_tokens.Add(method);
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(RuntimeFieldHandle field)
{
m_tokens.Add(field);
return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
}
public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext)
{
m_tokens.Add(new GenericFieldInfo(field, typeContext));
return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
}
public int GetTokenFor(RuntimeTypeHandle type)
{
m_tokens.Add(type);
return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef;
}
public int GetTokenFor(string literal)
{
m_tokens.Add(literal);
return m_tokens.Count - 1 | (int)MetadataTokenType.String;
}
public int GetTokenFor(byte[] signature)
{
m_tokens.Add(signature);
return m_tokens.Count - 1 | (int)MetadataTokenType.Signature;
}
#endregion
}
internal sealed class GenericMethodInfo
{
internal RuntimeMethodHandle m_methodHandle;
internal RuntimeTypeHandle m_context;
internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context)
{
m_methodHandle = methodHandle;
m_context = context;
}
}
internal sealed class GenericFieldInfo
{
internal RuntimeFieldHandle m_fieldHandle;
internal RuntimeTypeHandle m_context;
internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context)
{
m_fieldHandle = fieldHandle;
m_context = context;
}
}
internal sealed class VarArgMethod
{
internal RuntimeMethodInfo m_method;
internal DynamicMethod m_dynamicMethod;
internal SignatureHelper m_signature;
internal VarArgMethod(DynamicMethod dm, SignatureHelper signature)
{
m_dynamicMethod = dm;
m_signature = signature;
}
internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature)
{
m_method = method;
m_signature = signature;
}
}
}
| |
// 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.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.Diagnostics
{
internal static partial class ProcessManager
{
/// <summary>Gets whether the process with the specified ID is currently running.</summary>
/// <param name="processId">The process ID.</param>
/// <returns>true if the process is running; otherwise, false.</returns>
public static bool IsProcessRunning(int processId)
{
return IsProcessRunning(processId, ".");
}
/// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary>
/// <param name="processId">The process ID.</param>
/// <param name="machineName">The machine name.</param>
/// <returns>true if the process is running; otherwise, false.</returns>
public static bool IsProcessRunning(int processId, string machineName)
{
// Performance optimization for the local machine:
// First try to OpenProcess by id, if valid handle is returned, the process is definitely running
// Otherwise enumerate all processes and compare ids
if (!IsRemoteMachine(machineName))
{
using (SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, processId))
{
if (!processHandle.IsInvalid)
{
return true;
}
}
}
return Array.IndexOf(GetProcessIds(machineName), processId) >= 0;
}
/// <summary>Gets process infos for each process on the specified machine.</summary>
/// <param name="machineName">The target machine.</param>
/// <returns>An array of process infos, one per found process.</returns>
public static ProcessInfo[] GetProcessInfos(string machineName)
{
return IsRemoteMachine(machineName) ?
NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true) :
NtProcessInfoHelper.GetProcessInfos();
}
/// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary>
/// <param name="processId">The process ID.</param>
/// <param name="machineName">The machine name.</param>
/// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns>
public static ProcessInfo GetProcessInfo(int processId, string machineName)
{
if (IsRemoteMachine(machineName))
{
// remote case: we take the hit of looping through all results
ProcessInfo[] processInfos = NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true);
foreach (ProcessInfo processInfo in processInfos)
{
if (processInfo.ProcessId == processId)
{
return processInfo;
}
}
}
else
{
// local case: do not use performance counter and also attempt to get the matching (by pid) process only
ProcessInfo[] processInfos = NtProcessInfoHelper.GetProcessInfos(pid => pid == processId);
if (processInfos.Length == 1)
{
return processInfos[0];
}
}
return null;
}
/// <summary>Gets the IDs of all processes on the specified machine.</summary>
/// <param name="machineName">The machine to examine.</param>
/// <returns>An array of process IDs from the specified machine.</returns>
public static int[] GetProcessIds(string machineName)
{
// Due to the lack of support for EnumModules() on coresysserver, we rely
// on PerformanceCounters to get the ProcessIds for both remote desktop
// and the local machine, unlike Desktop on which we rely on PCs only for
// remote machines.
return IsRemoteMachine(machineName) ?
NtProcessManager.GetProcessIds(machineName, true) :
GetProcessIds();
}
/// <summary>Gets the IDs of all processes on the current machine.</summary>
public static int[] GetProcessIds()
{
return NtProcessManager.GetProcessIds();
}
/// <summary>Gets the ID of a process from a handle to the process.</summary>
/// <param name="processHandle">The handle.</param>
/// <returns>The process ID.</returns>
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
return NtProcessManager.GetProcessIdFromHandle(processHandle);
}
/// <summary>Gets an array of module infos for the specified process.</summary>
/// <param name="processId">The ID of the process whose modules should be enumerated.</param>
/// <returns>The array of modules.</returns>
public static ProcessModuleCollection GetModules(int processId)
{
return NtProcessManager.GetModules(processId);
}
private static bool IsRemoteMachineCore(string machineName)
{
string baseName;
if (machineName.StartsWith("\\", StringComparison.Ordinal))
baseName = machineName.Substring(2);
else
baseName = machineName;
if (baseName.Equals(".")) return false;
return !string.Equals(Interop.Kernel32.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
static ProcessManager()
{
// In order to query information (OpenProcess) on some protected processes
// like csrss, we need SeDebugPrivilege privilege.
// After removing the dependency on Performance Counter, we don't have a chance
// to run the code in CLR performance counter to ask for this privilege.
// So we will try to get the privilege here.
// We could fail if the user account doesn't have right to do this, but that's fair.
Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID();
if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid))
{
return;
}
SafeTokenHandle tokenHandle = null;
try
{
if (!Interop.Advapi32.OpenProcessToken(
Interop.Kernel32.GetCurrentProcess(),
Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES,
out tokenHandle))
{
return;
}
Interop.Advapi32.TokenPrivileges tp = new Interop.Advapi32.TokenPrivileges();
tp.Luid = luid;
tp.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED;
// AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned).
Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero);
}
finally
{
if (tokenHandle != null)
{
tokenHandle.Dispose();
}
}
}
public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited)
{
SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(access, false, processId);
int result = Marshal.GetLastWin32Error();
if (!processHandle.IsInvalid)
{
return processHandle;
}
if (processId == 0)
{
throw new Win32Exception(5);
}
// If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true.
// Assume the process is still running if the error was ERROR_ACCESS_DENIED for better performance
if (result != Interop.Errors.ERROR_ACCESS_DENIED && !IsProcessRunning(processId))
{
if (throwIfExited)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
}
else
{
return SafeProcessHandle.InvalidHandle;
}
}
throw new Win32Exception(result);
}
public static SafeThreadHandle OpenThread(int threadId, int access)
{
SafeThreadHandle threadHandle = Interop.Kernel32.OpenThread(access, false, threadId);
int result = Marshal.GetLastWin32Error();
if (threadHandle.IsInvalid)
{
if (result == Interop.Errors.ERROR_INVALID_PARAMETER)
throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture)));
throw new Win32Exception(result);
}
return threadHandle;
}
}
/// <devdoc>
/// This static class provides the process api for the WinNt platform.
/// We use the performance counter api to query process and thread
/// information. Module information is obtained using PSAPI.
/// </devdoc>
/// <internalonly/>
internal static partial class NtProcessManager
{
private const int ProcessPerfCounterId = 230;
private const int ThreadPerfCounterId = 232;
private const string PerfCounterQueryString = "230 232";
internal const int IdleProcessID = 0;
private static readonly Dictionary<String, ValueId> s_valueIds = new Dictionary<string, ValueId>(19)
{
{ "Pool Paged Bytes", ValueId.PoolPagedBytes },
{ "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes },
{ "Elapsed Time", ValueId.ElapsedTime },
{ "Virtual Bytes Peak", ValueId.VirtualBytesPeak },
{ "Virtual Bytes", ValueId.VirtualBytes },
{ "Private Bytes", ValueId.PrivateBytes },
{ "Page File Bytes", ValueId.PageFileBytes },
{ "Page File Bytes Peak", ValueId.PageFileBytesPeak },
{ "Working Set Peak", ValueId.WorkingSetPeak },
{ "Working Set", ValueId.WorkingSet },
{ "ID Thread", ValueId.ThreadId },
{ "ID Process", ValueId.ProcessId },
{ "Priority Base", ValueId.BasePriority },
{ "Priority Current", ValueId.CurrentPriority },
{ "% User Time", ValueId.UserTime },
{ "% Privileged Time", ValueId.PrivilegedTime },
{ "Start Address", ValueId.StartAddress },
{ "Thread State", ValueId.ThreadState },
{ "Thread Wait Reason", ValueId.ThreadWaitReason }
};
internal static int SystemProcessID
{
get
{
const int systemProcessIDOnXP = 4;
return systemProcessIDOnXP;
}
}
public static int[] GetProcessIds(string machineName, bool isRemoteMachine)
{
ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine);
int[] ids = new int[infos.Length];
for (int i = 0; i < infos.Length; i++)
ids[i] = infos[i].ProcessId;
return ids;
}
public static int[] GetProcessIds()
{
int[] processIds = new int[256];
int size;
for (; ; )
{
if (!Interop.Kernel32.EnumProcesses(processIds, processIds.Length * 4, out size))
throw new Win32Exception();
if (size == processIds.Length * 4)
{
processIds = new int[processIds.Length * 2];
continue;
}
break;
}
int[] ids = new int[size / 4];
Array.Copy(processIds, 0, ids, 0, ids.Length);
return ids;
}
public static ProcessModuleCollection GetModules(int processId)
{
return GetModules(processId, firstModuleOnly: false);
}
public static ProcessModule GetFirstModule(int processId)
{
ProcessModuleCollection modules = GetModules(processId, firstModuleOnly: true);
return modules.Count == 0 ? null : modules[0];
}
private static void HandleError()
{
int lastError = Marshal.GetLastWin32Error();
switch (lastError)
{
case Interop.Errors.ERROR_INVALID_HANDLE:
case Interop.Errors.ERROR_PARTIAL_COPY:
// It's possible that another thread caused this module to become
// unloaded (e.g FreeLibrary was called on the module). Ignore it and
// move on.
break;
default:
throw new Win32Exception(lastError);
}
}
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
return Interop.Kernel32.GetProcessId(processHandle);
}
public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine)
{
PerformanceCounterLib library = null;
try
{
library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en"));
return GetProcessInfos(library);
}
catch (Exception e)
{
if (isRemoteMachine)
{
throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e);
}
else
{
throw e;
}
}
// We don't want to call library.Close() here because that would cause us to unload all of the perflibs.
// On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW!
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library)
{
ProcessInfo[] processInfos;
int retryCount = 5;
do
{
try
{
byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString);
processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.CouldntGetProcessInfos, e);
}
--retryCount;
}
while (processInfos.Length == 0 && retryCount != 0);
if (processInfos.Length == 0)
throw new InvalidOperationException(SR.ProcessDisabled);
return processInfos;
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data)
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()");
#endif
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>();
List<ThreadInfo> threadInfos = new List<ThreadInfo>();
GCHandle dataHandle = new GCHandle();
try
{
dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataBlockPtr, dataBlock);
IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
Interop.Advapi32.PERF_INSTANCE_DEFINITION instance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION();
Interop.Advapi32.PERF_COUNTER_BLOCK counterBlock = new Interop.Advapi32.PERF_COUNTER_BLOCK();
for (int i = 0; i < dataBlock.NumObjectTypes; i++)
{
Interop.Advapi32.PERF_OBJECT_TYPE type = new Interop.Advapi32.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(typePtr, type);
IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength);
List<Interop.Advapi32.PERF_COUNTER_DEFINITION> counterList = new List<Interop.Advapi32.PERF_COUNTER_DEFINITION>();
for (int j = 0; j < type.NumCounters; j++)
{
Interop.Advapi32.PERF_COUNTER_DEFINITION counter = new Interop.Advapi32.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(counterPtr, counter);
string counterName = library.GetCounterName(counter.CounterNameTitleIndex);
if (type.ObjectNameTitleIndex == processIndex)
counter.CounterNameTitlePtr = (int)GetValueId(counterName);
else if (type.ObjectNameTitleIndex == threadIndex)
counter.CounterNameTitlePtr = (int)GetValueId(counterName);
counterList.Add(counter);
counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength);
}
Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray();
for (int j = 0; j < type.NumInstances; j++)
{
Marshal.PtrToStructure(instancePtr, instance);
IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset);
string instanceName = Marshal.PtrToStringUni(namePtr);
if (instanceName.Equals("_Total")) continue;
IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength);
Marshal.PtrToStructure(counterBlockPtr, counterBlock);
if (type.ObjectNameTitleIndex == processIndex)
{
ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0)
{
// Sometimes we'll get a process structure that is not completely filled in.
// We can catch some of these by looking for non-"idle" processes that have id 0
// and ignoring those.
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
#endif
}
else
{
if (processInfos.ContainsKey(processInfo.ProcessId))
{
// We've found two entries in the perfcounters that claim to be the
// same process. We throw an exception. Is this really going to be
// helpful to the user? Should we just ignore?
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
#endif
}
else
{
// the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe",
// if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe"
// at the end. If instanceName ends in ".", ".e", or ".ex" we remove it.
string processName = instanceName;
if (processName.Length == 15)
{
if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14);
else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13);
else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12);
}
processInfo.ProcessName = processName;
processInfos.Add(processInfo.ProcessId, processInfo);
}
}
}
else if (type.ObjectNameTitleIndex == threadIndex)
{
ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
if (threadInfo._threadId != 0) threadInfos.Add(threadInfo);
}
instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength);
}
typePtr = (IntPtr)((long)typePtr + type.TotalByteLength);
}
}
finally
{
if (dataHandle.IsAllocated) dataHandle.Free();
}
for (int i = 0; i < threadInfos.Count; i++)
{
ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
ProcessInfo processInfo;
if (processInfos.TryGetValue(threadInfo._processId, out processInfo))
{
processInfo._threadInfoList.Add(threadInfo);
}
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
static ThreadInfo GetThreadInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters)
{
ThreadInfo threadInfo = new ThreadInfo();
for (int i = 0; i < counters.Length; i++)
{
Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i];
long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
switch ((ValueId)counter.CounterNameTitlePtr)
{
case ValueId.ProcessId:
threadInfo._processId = (int)value;
break;
case ValueId.ThreadId:
threadInfo._threadId = (ulong)value;
break;
case ValueId.BasePriority:
threadInfo._basePriority = (int)value;
break;
case ValueId.CurrentPriority:
threadInfo._currentPriority = (int)value;
break;
case ValueId.StartAddress:
threadInfo._startAddress = (IntPtr)value;
break;
case ValueId.ThreadState:
threadInfo._threadState = (ThreadState)value;
break;
case ValueId.ThreadWaitReason:
threadInfo._threadWaitReason = GetThreadWaitReason((int)value);
break;
}
}
return threadInfo;
}
internal static ThreadWaitReason GetThreadWaitReason(int value)
{
switch (value)
{
case 0:
case 7: return ThreadWaitReason.Executive;
case 1:
case 8: return ThreadWaitReason.FreePage;
case 2:
case 9: return ThreadWaitReason.PageIn;
case 3:
case 10: return ThreadWaitReason.SystemAllocation;
case 4:
case 11: return ThreadWaitReason.ExecutionDelay;
case 5:
case 12: return ThreadWaitReason.Suspended;
case 6:
case 13: return ThreadWaitReason.UserRequest;
case 14: return ThreadWaitReason.EventPairHigh; ;
case 15: return ThreadWaitReason.EventPairLow;
case 16: return ThreadWaitReason.LpcReceive;
case 17: return ThreadWaitReason.LpcReply;
case 18: return ThreadWaitReason.VirtualMemory;
case 19: return ThreadWaitReason.PageOut;
default: return ThreadWaitReason.Unknown;
}
}
static ProcessInfo GetProcessInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters)
{
ProcessInfo processInfo = new ProcessInfo();
for (int i = 0; i < counters.Length; i++)
{
Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i];
long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
switch ((ValueId)counter.CounterNameTitlePtr)
{
case ValueId.ProcessId:
processInfo.ProcessId = (int)value;
break;
case ValueId.PoolPagedBytes:
processInfo.PoolPagedBytes = value;
break;
case ValueId.PoolNonpagedBytes:
processInfo.PoolNonPagedBytes = value;
break;
case ValueId.VirtualBytes:
processInfo.VirtualBytes = value;
break;
case ValueId.VirtualBytesPeak:
processInfo.VirtualBytesPeak = value;
break;
case ValueId.WorkingSetPeak:
processInfo.WorkingSetPeak = value;
break;
case ValueId.WorkingSet:
processInfo.WorkingSet = value;
break;
case ValueId.PageFileBytesPeak:
processInfo.PageFileBytesPeak = value;
break;
case ValueId.PageFileBytes:
processInfo.PageFileBytes = value;
break;
case ValueId.PrivateBytes:
processInfo.PrivateBytes = value;
break;
case ValueId.BasePriority:
processInfo.BasePriority = (int)value;
break;
case ValueId.HandleCount:
processInfo.HandleCount = (int)value;
break;
}
}
return processInfo;
}
static ValueId GetValueId(string counterName)
{
if (counterName != null)
{
ValueId id;
if (s_valueIds.TryGetValue(counterName, out id))
return id;
}
return ValueId.Unknown;
}
static long ReadCounterValue(int counterType, IntPtr dataPtr)
{
if ((counterType & Interop.Advapi32.PerfCounterOptions.NtPerfCounterSizeLarge) != 0)
return Marshal.ReadInt64(dataPtr);
else
return (long)Marshal.ReadInt32(dataPtr);
}
enum ValueId
{
Unknown = -1,
HandleCount,
PoolPagedBytes,
PoolNonpagedBytes,
ElapsedTime,
VirtualBytesPeak,
VirtualBytes,
PrivateBytes,
PageFileBytes,
PageFileBytesPeak,
WorkingSetPeak,
WorkingSet,
ThreadId,
ProcessId,
BasePriority,
CurrentPriority,
UserTime,
PrivilegedTime,
StartAddress,
ThreadState,
ThreadWaitReason
}
}
internal static partial class NtProcessInfoHelper
{
private static int GetNewBufferSize(int existingBufferSize, int requiredSize)
{
if (requiredSize == 0)
{
//
// On some old OS like win2000, requiredSize will not be set if the buffer
// passed to NtQuerySystemInformation is not enough.
//
int newSize = existingBufferSize * 2;
if (newSize < existingBufferSize)
{
// In reality, we should never overflow.
// Adding the code here just in case it happens.
throw new OutOfMemoryException();
}
return newSize;
}
else
{
// allocating a few more kilo bytes just in case there are some new process
// kicked in since new call to NtQuerySystemInformation
int newSize = requiredSize + 1024 * 10;
if (newSize < requiredSize)
{
throw new OutOfMemoryException();
}
return newSize;
}
}
// Use a smaller buffer size on debug to ensure we hit the retry path.
#if DEBUG
private const int DefaultCachedBufferSize = 1024;
#else
private const int DefaultCachedBufferSize = 128 * 1024;
#endif
private static unsafe ProcessInfo[] GetProcessInfos(IntPtr dataPtr, Predicate<int> processIdFilter)
{
// Use a dictionary to avoid duplicate entries if any
// 60 is a reasonable number for processes on a normal machine.
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60);
long totalOffset = 0;
while (true)
{
IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
ref SystemProcessInformation pi = ref *(SystemProcessInformation *)(currentPtr);
// Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
var processInfoProcessId = pi.UniqueProcessId.ToInt32();
if (processIdFilter == null || processIdFilter(processInfoProcessId))
{
// get information for a process
ProcessInfo processInfo = new ProcessInfo();
processInfo.ProcessId = processInfoProcessId;
processInfo.SessionId = (int)pi.SessionId;
processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage;
processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage;
processInfo.VirtualBytes = (long)pi.VirtualSize;
processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize;
processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize;
processInfo.WorkingSet = (long)pi.WorkingSetSize;
processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage;
processInfo.PageFileBytes = (long)pi.PagefileUsage;
processInfo.PrivateBytes = (long)pi.PrivatePageCount;
processInfo.BasePriority = pi.BasePriority;
processInfo.HandleCount = (int)pi.HandleCount;
if (pi.ImageName.Buffer == IntPtr.Zero)
{
if (processInfo.ProcessId == NtProcessManager.SystemProcessID)
{
processInfo.ProcessName = "System";
}
else if (processInfo.ProcessId == NtProcessManager.IdleProcessID)
{
processInfo.ProcessName = "Idle";
}
else
{
// for normal process without name, using the process ID.
processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture);
}
}
else
{
string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.ImageName.Buffer, pi.ImageName.Length / sizeof(char)));
processInfo.ProcessName = processName;
}
// get the threads for current process
processInfos[processInfo.ProcessId] = processInfo;
currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
int i = 0;
while (i < pi.NumberOfThreads)
{
ref SystemThreadInformation ti = ref *(SystemThreadInformation *)(currentPtr);
ThreadInfo threadInfo = new ThreadInfo();
threadInfo._processId = (int)ti.ClientId.UniqueProcess;
threadInfo._threadId = (ulong)ti.ClientId.UniqueThread;
threadInfo._basePriority = ti.BasePriority;
threadInfo._currentPriority = ti.Priority;
threadInfo._startAddress = ti.StartAddress;
threadInfo._threadState = (ThreadState)ti.ThreadState;
threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);
processInfo._threadInfoList.Add(threadInfo);
currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
i++;
}
}
if (pi.NextEntryOffset == 0)
{
break;
}
totalOffset += pi.NextEntryOffset;
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
// This function generates the short form of process name.
//
// This is from GetProcessShortName in NT code base.
// Check base\screg\winreg\perfdlls\process\perfsprc.c for details.
internal static string GetProcessShortName(String name)
{
if (String.IsNullOrEmpty(name))
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName");
#endif
return String.Empty;
}
int slash = -1;
int period = -1;
for (int i = 0; i < name.Length; i++)
{
if (name[i] == '\\')
slash = i;
else if (name[i] == '.')
period = i;
}
if (period == -1)
period = name.Length - 1; // set to end of string
else
{
// if a period was found, then see if the extension is
// .EXE, if so drop it, if not, then use end of string
// (i.e. include extension in name)
String extension = name.Substring(period);
if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase))
period--; // point to character before period
else
period = name.Length - 1; // set to end of string
}
if (slash == -1)
slash = 0; // set to start of string
else
slash++; // point to character next to slash
// copy characters between period (or end of string) and
// slash (or start of string) to make image name
return name.Substring(slash, period - slash + 1);
}
// native struct defined in ntexapi.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct SystemProcessInformation
{
internal uint NextEntryOffset;
internal uint NumberOfThreads;
private fixed byte Reserved1[48];
internal Interop.UNICODE_STRING ImageName;
internal int BasePriority;
internal IntPtr UniqueProcessId;
private UIntPtr Reserved2;
internal uint HandleCount;
internal uint SessionId;
private UIntPtr Reserved3;
internal UIntPtr PeakVirtualSize; // SIZE_T
internal UIntPtr VirtualSize;
private uint Reserved4;
internal UIntPtr PeakWorkingSetSize; // SIZE_T
internal UIntPtr WorkingSetSize; // SIZE_T
private UIntPtr Reserved5;
internal UIntPtr QuotaPagedPoolUsage; // SIZE_T
private UIntPtr Reserved6;
internal UIntPtr QuotaNonPagedPoolUsage; // SIZE_T
internal UIntPtr PagefileUsage; // SIZE_T
internal UIntPtr PeakPagefileUsage; // SIZE_T
internal UIntPtr PrivatePageCount; // SIZE_T
private fixed long Reserved7[6];
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct SystemThreadInformation
{
private fixed long Reserved1[3];
private uint Reserved2;
internal IntPtr StartAddress;
internal CLIENT_ID ClientId;
internal int Priority;
internal int BasePriority;
private uint Reserved3;
internal uint ThreadState;
internal uint WaitReason;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CLIENT_ID
{
internal IntPtr UniqueProcess;
internal IntPtr UniqueThread;
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using System.IO;
using System.Reflection;
namespace TNRD.Editor.Serialization {
public class Deserializer {
public static T FromB64<T>( string b64 ) {
var buffer = Convert.FromBase64String( b64 );
return FromBytes<T>( buffer );
}
public static T FromBytes<T>( byte[] bytes ) {
var deserializedObj = ByteDeserializer.Deserialize( bytes );
var value = new Deserializer().ReadClass( deserializedObj );
return (T)value;
}
public static object FromB64( string b64, Type type ) {
var buffer = Convert.FromBase64String( b64 );
return FromBytes( buffer, type );
}
public static object FromBytes( byte[] bytes, Type type ) {
var deserializedObj = ByteDeserializer.Deserialize( bytes );
var value = new Deserializer().ReadClass( deserializedObj );
return Convert.ChangeType( value, type );
}
private Dictionary<int, object> deserializedObjects = new Dictionary<int, object>();
private object ReadClass( SerializedClass value ) {
if ( value.IsNull ) return null;
var type = Type.GetType( value.Type );
object instance = null;
if ( value.IsReference ) {
if ( deserializedObjects.ContainsKey( value.ID ) ) {
return deserializedObjects[value.ID];
}
}
try {
instance = Activator.CreateInstance( type, true );
} catch ( MissingMethodException ) {
// No constructor
deserializedObjects.Add( value.ID, null );
return null;
}
var fields = SerializationHelper.GetFields( type, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic )
.Where( f =>
( f.IsPublic && f.GetCustomAttributes( typeof( IgnoreSerializationAttribute ), false ).Length == 0 ) ||
( f.IsPrivate && f.GetCustomAttributes( typeof( RequireSerializationAttribute ), false ).Length == 1 ) )
.OrderBy( f => f.Name ).ToList();
var properties = SerializationHelper.GetProperties( type, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic )
.Where( p => p.CanRead && p.CanWrite )
.Where( p => p.GetCustomAttributes( typeof( IgnoreSerializationAttribute ), false ).Length == 0 )
.OrderBy( p => p.Name ).ToList();
foreach ( var item in value.Values ) {
var name = item.Key.Substring( 0, item.Key.IndexOf( '|' ) );
object tValue = Read( item.Value );
var field = fields.Where( f => f.Name == name ).FirstOrDefault();
if ( field != null ) {
fields.Remove( field );
try {
field.SetValue( instance, tValue );
} catch ( Exception e ) {
Debug.LogException( e );
}
continue;
}
var property = properties.Where( p => p.Name == name ).FirstOrDefault();
if ( property != null ) {
properties.Remove( property );
try {
property.SetValue( instance, tValue, null );
} catch ( Exception e ) {
Debug.LogException( e );
}
continue;
}
}
if ( instance is FakeType ) {
var ft = (FakeType)instance;
var v = ft.GetValue();
deserializedObjects.Add( value.ID, v );
instance = v;
} else {
deserializedObjects.Add( value.ID, instance );
}
return instance;
}
private object ReadEnum( SerializedEnum value ) {
return value.Value;
}
private object ReadList( SerializedList value ) {
var type = Type.GetType( value.Type );
IList instance = null;
if ( type.IsArray() ) {
instance = Array.CreateInstance( type.GetElementType() ?? typeof( object ), value.Values.Count );
for ( int i = 0; i < value.Values.Count; i++ ) {
var item = value.Values[i];
instance[i] = Read( item );
}
} else {
instance = (IList)Activator.CreateInstance( type );
foreach ( var item in value.Values ) {
instance.Add( Read( item ) );
}
}
return instance;
}
private object ReadPrimitive( SerializedPrimitive value ) {
return value.Value;
}
private object Read( SerializedBase item ) {
switch ( item.Mode ) {
case ESerializableMode.Primitive:
return ReadPrimitive( (SerializedPrimitive)item );
case ESerializableMode.Enum:
return ReadEnum( (SerializedEnum)item );
case ESerializableMode.List:
return ReadList( (SerializedList)item );
case ESerializableMode.Class:
return ReadClass( (SerializedClass)item );
default:
return null;
}
}
private class ByteDeserializer {
public static SerializedClass Deserialize( byte[] bytes ) {
var stream = new MemoryStream( bytes );
var reader = new BinaryReader( stream );
var obj = new ByteDeserializer().DeserializeClass( reader );
return obj;
}
private SerializedBase DeserializeDefaults( BinaryReader reader ) {
var s = new SerializedBase( 0, "" );
s.ID = reader.ReadInt32();
s.IsNull = reader.ReadBoolean();
s.IsReference = reader.ReadBoolean();
s.Mode = (ESerializableMode)reader.ReadInt32();
s.Type = reader.ReadString();
return s;
}
private SerializedClass DeserializeClass( BinaryReader reader ) {
var value = new SerializedClass( DeserializeDefaults( reader ) );
var count = reader.ReadInt32();
for ( int i = 0; i < count; i++ ) {
var name = reader.ReadString();
var mode = (ESerializableMode)reader.ReadInt32();
switch ( mode ) {
case ESerializableMode.Primitive:
value.Add( name, DeserializePrimitive( reader ) );
break;
case ESerializableMode.Enum:
value.Add( name, DeserializeEnum( reader ) );
break;
case ESerializableMode.List:
value.Add( name, DeserializeList( reader ) );
break;
case ESerializableMode.Class:
value.Add( name, DeserializeClass( reader ) );
break;
default:
break;
}
}
return value;
}
private SerializedEnum DeserializeEnum( BinaryReader reader ) {
var value = new SerializedEnum( DeserializeDefaults( reader ) );
value.Value = reader.ReadInt32();
return value;
}
private SerializedList DeserializeList( BinaryReader reader ) {
var value = new SerializedList( DeserializeDefaults( reader ) );
var count = reader.ReadInt32();
for ( int i = 0; i < count; i++ ) {
var mode = (ESerializableMode)reader.ReadInt32();
switch ( mode ) {
case ESerializableMode.Primitive:
value.Add( DeserializePrimitive( reader ) );
break;
case ESerializableMode.Enum:
value.Add( DeserializeEnum( reader ) );
break;
case ESerializableMode.List:
value.Add( DeserializeList( reader ) );
break;
case ESerializableMode.Class:
value.Add( DeserializeClass( reader ) );
break;
default:
break;
}
}
return value;
}
private SerializedPrimitive DeserializePrimitive( BinaryReader reader ) {
var value = new SerializedPrimitive( DeserializeDefaults( reader ) );
var type = Type.GetType( value.Type );
if ( type == typeof( bool ) ) {
value.Value = reader.ReadBoolean();
} else if ( type == typeof( byte ) ) {
value.Value = reader.ReadByte();
} else if ( type == typeof( char ) ) {
value.Value = reader.ReadChar();
} else if ( type == typeof( decimal ) ) {
value.Value = reader.ReadDecimal();
} else if ( type == typeof( double ) ) {
value.Value = reader.ReadDouble();
} else if ( type == typeof( float ) ) {
value.Value = reader.ReadSingle();
} else if ( type == typeof( int ) ) {
value.Value = reader.ReadInt32();
} else if ( type == typeof( long ) ) {
value.Value = reader.ReadInt64();
} else if ( type == typeof( sbyte ) ) {
value.Value = reader.ReadSByte();
} else if ( type == typeof( short ) ) {
value.Value = reader.ReadInt16();
} else if ( type == typeof( string ) ) {
value.Value = reader.ReadString();
} else if ( type == typeof( uint ) ) {
value.Value = reader.ReadUInt32();
} else if ( type == typeof( ulong ) ) {
value.Value = reader.ReadUInt64();
} else if ( type == typeof( ushort ) ) {
value.Value = reader.ReadUInt16();
} else {
Debug.LogErrorFormat( "Found an unknown primitive: {0}", type.Name );
}
return value;
}
}
}
}
#endif
| |
// 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 System.Text;
using Microsoft.CodeAnalysis.Collections;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
// Implementation for "displaying type name as string" aspect of default (C#) Formatter component
internal abstract partial class Formatter
{
/// <returns>The qualified name (i.e. including containing types and namespaces) of a named,
/// pointer, or array type.</returns>
internal string GetTypeName(TypeAndCustomInfo typeAndInfo, bool escapeKeywordIdentifiers, out bool sawInvalidIdentifier)
{
var type = typeAndInfo.Type;
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
var dynamicFlags = DynamicFlagsCustomTypeInfo.Create(typeAndInfo.Info);
var index = 0;
var pooled = PooledStringBuilder.GetInstance();
AppendQualifiedTypeName(pooled.Builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers, out sawInvalidIdentifier);
return pooled.ToStringAndFree();
}
/// <summary>
/// Append the qualified name (i.e. including containing types and namespaces) of a named,
/// pointer, or array type to <paramref name="builder"/>.
/// </summary>
/// <remarks>
/// Keyword strings are appended for primitive types (e.g. "int" for "System.Int32").
/// Question mark syntax is used for <see cref="Nullable{T}"/>.
/// No special handling is required for anonymous types - they are expected to be
/// emitted with <see cref="DebuggerDisplayAttribute.Type"/> set to "<Anonymous Type>.
/// This is fortunate, since we don't have a good way to recognize them in metadata.
/// Does not call itself (directly).
/// </remarks>
protected void AppendQualifiedTypeName(
StringBuilder builder,
Type type,
DynamicFlagsCustomTypeInfo dynamicFlags,
ref int index,
bool escapeKeywordIdentifiers,
out bool sawInvalidIdentifier)
{
Type originalType = type;
// Can have an array of pointers, but not a pointer to an array, so consume these first.
// We'll reconstruct this information later from originalType.
while (type.IsArray)
{
index++;
type = type.GetElementType();
}
int pointerCount = 0;
while (type.IsPointer)
{
index++;
pointerCount++;
type = type.GetElementType();
}
int nullableCount = 0;
Type typeArg;
while ((typeArg = type.GetNullableTypeArgument()) != null)
{
index++;
nullableCount++;
type = typeArg;
}
Debug.Assert(nullableCount < 2, "Benign: someone is nesting nullables.");
Debug.Assert(pointerCount == 0 || nullableCount == 0, "Benign: pointer to nullable?");
int oldLength = builder.Length;
AppendQualifiedTypeNameInternal(builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers, out sawInvalidIdentifier);
string name = builder.ToString(oldLength, builder.Length - oldLength);
builder.Append('?', nullableCount);
builder.Append('*', pointerCount);
type = originalType;
while (type.IsArray)
{
AppendRankSpecifier(builder, type.GetArrayRank());
type = type.GetElementType();
}
}
/// <summary>
/// Append the qualified name (i.e. including containing types and namespaces) of a named type
/// (i.e. not a pointer or array type) to <paramref name="builder"/>.
/// </summary>
/// <remarks>
/// Keyword strings are appended for primitive types (e.g. "int" for "System.Int32").
/// </remarks>
/// <remarks>
/// Does not call itself or <see cref="AppendQualifiedTypeName"/> (directly).
/// </remarks>
private void AppendQualifiedTypeNameInternal(
StringBuilder builder,
Type type,
DynamicFlagsCustomTypeInfo dynamicFlags,
ref int index,
bool escapeKeywordIdentifiers,
out bool sawInvalidIdentifier)
{
var isDynamic = dynamicFlags[index++] && type.IsObject();
if (AppendSpecialTypeName(builder, type, isDynamic))
{
sawInvalidIdentifier = false;
return;
}
Debug.Assert(!isDynamic, $"Dynamic should have been handled by {nameof(AppendSpecialTypeName)}");
Debug.Assert(!IsPredefinedType(type));
if (type.IsGenericParameter)
{
AppendIdentifier(builder, escapeKeywordIdentifiers, type.Name, out sawInvalidIdentifier);
return;
}
// Note: in the Reflection/LMR object model, all type arguments are on the most nested type.
var hasTypeArguments = type.IsGenericType;
var typeArguments = type.IsGenericType
? type.GetGenericArguments()
: null;
Debug.Assert(hasTypeArguments == (typeArguments != null));
var numTypeArguments = hasTypeArguments ? typeArguments.Length : 0;
sawInvalidIdentifier = false;
bool sawSingleInvalidIdentifier;
if (type.IsNested)
{
// Push from inside, out.
var stack = ArrayBuilder<Type>.GetInstance();
{
var containingType = type.DeclaringType;
while (containingType != null)
{
stack.Add(containingType);
containingType = containingType.DeclaringType;
}
}
var lastContainingTypeIndex = stack.Count - 1;
AppendNamespacePrefix(builder, stack[lastContainingTypeIndex], escapeKeywordIdentifiers, out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
var typeArgumentOffset = 0;
// Pop from outside, in.
for (int i = lastContainingTypeIndex; i >= 0; i--)
{
var containingType = stack[i];
// ACASEY: I explored the type in the debugger and couldn't find the arity stored/exposed separately.
int arity = hasTypeArguments ? containingType.GetGenericArguments().Length - typeArgumentOffset : 0;
AppendUnqualifiedTypeName(builder, containingType, dynamicFlags, ref index, escapeKeywordIdentifiers, typeArguments, typeArgumentOffset, arity, out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
builder.Append('.');
typeArgumentOffset += arity;
}
stack.Free();
AppendUnqualifiedTypeName(builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers, typeArguments, typeArgumentOffset, numTypeArguments - typeArgumentOffset, out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
}
else
{
AppendNamespacePrefix(builder, type, escapeKeywordIdentifiers, out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
AppendUnqualifiedTypeName(builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers, typeArguments, 0, numTypeArguments, out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
}
}
/// <summary>
/// Helper for appending the qualified name of the containing namespace of a type.
/// NOTE: Unless the qualified name is empty, there will always be a trailing dot.
/// </summary>
private void AppendNamespacePrefix(StringBuilder builder, Type type, bool escapeKeywordIdentifiers, out bool sawInvalidIdentifier)
{
sawInvalidIdentifier = false;
var @namespace = type.Namespace;
if (!string.IsNullOrEmpty(@namespace))
{
if (@namespace.Contains("."))
{
bool sawSingleInvalidIdentifier;
var pooled = PooledStringBuilder.GetInstance();
var identifierBuilder = pooled.Builder;
foreach (var ch in @namespace)
{
if (ch == '.')
{
AppendIdentifier(builder, escapeKeywordIdentifiers, identifierBuilder.ToString(), out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
builder.Append(ch);
identifierBuilder.Clear();
}
else
{
identifierBuilder.Append(ch);
}
}
AppendIdentifier(builder, escapeKeywordIdentifiers, identifierBuilder.ToString(), out sawSingleInvalidIdentifier);
sawInvalidIdentifier |= sawSingleInvalidIdentifier;
pooled.Free();
}
else
{
AppendIdentifier(builder, escapeKeywordIdentifiers, @namespace, out sawInvalidIdentifier);
}
builder.Append('.');
}
}
/// <summary>
/// Append the name of the type and its type arguments. Do not append the type's containing type or namespace.
/// </summary>
/// <param name="builder">Builder to which the name will be appended.</param>
/// <param name="type">Type, the name of which will be appended.</param>
/// <param name="dynamicFlags">Flags indicating which occurrences of "object" need to be replaced by "dynamic".</param>
/// <param name="index">Current index into <paramref name="dynamicFlags"/>.</param>
/// <param name="escapeKeywordIdentifiers">True if identifiers that are also keywords should be prefixed with '@'.</param>
/// <param name="typeArguments">
/// The type arguments of the type passed to <see cref="AppendQualifiedTypeNameInternal"/>, which might be nested
/// within <paramref name="type"/>. In the Reflection/LMR object model, all type arguments are passed to the
/// most nested type. To get back to the C# model, we have to propagate them out to containing types.
/// </param>
/// <param name="typeArgumentOffset">
/// The first position in <paramref name="typeArguments"/> that is a type argument to <paramref name="type"/>,
/// from a C# perspective.
/// </param>
/// <param name="arity">
/// The number of type parameters of <paramref name="type"/>, from a C# perspective.
/// </param>
/// <param name="sawInvalidIdentifier">True if the name includes an invalid identifier (see <see cref="IsValidIdentifier"/>); false otherwise.</param>
/// <remarks>
/// We're passing the full array plus bounds, rather than a tailored array, to avoid creating a lot of short-lived
/// temporary arrays.
/// </remarks>
private void AppendUnqualifiedTypeName(
StringBuilder builder,
Type type,
DynamicFlagsCustomTypeInfo dynamicFlags,
ref int index,
bool escapeKeywordIdentifiers,
Type[] typeArguments,
int typeArgumentOffset,
int arity,
out bool sawInvalidIdentifier)
{
if (typeArguments == null || arity == 0)
{
AppendIdentifier(builder, escapeKeywordIdentifiers, type.Name, out sawInvalidIdentifier);
return;
}
var mangledName = type.Name;
var separatorIndex = mangledName.IndexOf('`');
var unmangledName = separatorIndex < 0 ? mangledName : mangledName.Substring(0, separatorIndex);
AppendIdentifier(builder, escapeKeywordIdentifiers, unmangledName, out sawInvalidIdentifier);
bool argumentsSawInvalidIdentifier;
AppendGenericTypeArgumentList(builder, typeArguments, typeArgumentOffset, dynamicFlags, ref index, arity, escapeKeywordIdentifiers, out argumentsSawInvalidIdentifier);
sawInvalidIdentifier |= argumentsSawInvalidIdentifier;
}
protected void AppendIdentifier(StringBuilder builder, bool escapeKeywordIdentifiers, string identifier, out bool sawInvalidIdentifier)
{
if (escapeKeywordIdentifiers)
{
AppendIdentifierEscapingPotentialKeywords(builder, identifier, out sawInvalidIdentifier);
}
else
{
sawInvalidIdentifier = !IsValidIdentifier(identifier);
builder.Append(identifier);
}
}
internal string GetIdentifierEscapingPotentialKeywords(string identifier, out bool sawInvalidIdentifier)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
AppendIdentifierEscapingPotentialKeywords(builder, identifier, out sawInvalidIdentifier);
return pooled.ToStringAndFree();
}
#region Language-specific type name formatting behavior
protected abstract void AppendIdentifierEscapingPotentialKeywords(StringBuilder builder, string identifier, out bool sawInvalidIdentifier);
protected abstract void AppendGenericTypeArgumentList(
StringBuilder builder,
Type[] typeArguments,
int typeArgumentOffset,
DynamicFlagsCustomTypeInfo dynamicFlags,
ref int index,
int arity,
bool escapeKeywordIdentifiers,
out bool sawInvalidIdentifier);
protected abstract void AppendRankSpecifier(StringBuilder builder, int rank);
protected abstract bool AppendSpecialTypeName(StringBuilder builder, Type type, bool isDynamic);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Resources;
using System.Reflection;
using System.Collections;
using MarioObjects;
using MarioObjects.Objects.Utils;
namespace MarioLevelEditor
{
public partial class MainForm : Form
{
public Bitmap MainImage = null;
public int CurrentImageIndex;
public List<LevelEditorObject> Objects;
public int Seconds = 0;
string FileName;
public int LX,LY;
public int OX, OY;
public MainForm()
{
InitializeComponent();
}
public void DrawAllObjects()
{
//IDictionaryEnumerator ide = Objects.GetEnumerator();
foreach (LevelEditorObject obj in Objects)
{
Point p = new Point(obj.x, obj.y);
PutBox(p.X*16, MainImage.Height - (p.Y+1)*16, obj.ListIndex,obj.Checked);
}
}
public void PutBox(int x, int y,int ind,Boolean Check)
{
Graphics xGraph = Graphics.FromImage(pictureLevel.Image);
LevelEditorObject le = (LevelEditorObject)list.Items[ind].Tag;
int hOff = (le.height - 16);
xGraph.DrawImage(images.Images[ind], new Rectangle(x, y - hOff, le.width, le.height),new Rectangle(0,0,32,32),GraphicsUnit.Pixel);
if (Check)
{
xGraph.DrawImage(pSelected.Image, new Rectangle(x, y - hOff, le.width, le.height), new Rectangle(0, 0, 12, 12), GraphicsUnit.Pixel);
}
}
public Bitmap ObjectTypeToImage(LevelEditorObject obj)
{
Bitmap tmp = new Bitmap(obj.width, obj.height);
Graphics xGraph = Graphics.FromImage(tmp);
Rectangle Src, Dest;
Dest = new Rectangle(0, 0, obj.width, obj.height);
Src = new Rectangle(obj.width * obj.ImageIndex, 0, obj.width, obj.height);
xGraph.DrawImage(ImageGenerator.GetImage(obj.OT), Dest,Src,GraphicsUnit.Pixel);
xGraph.Dispose();
return tmp;
}
public void LoadEditorObjects()
{
list.SmallImageList = images;
int cnt = 0;
foreach (LevelEditorObject obj in ObjectGenerator.GetEditorObjects())
{
images.Images.Add(ObjectTypeToImage(obj));
ListViewItem item = new ListViewItem(obj.name);
item.Name = obj.name;
item.ImageIndex = cnt;
obj.ListIndex = cnt++;
item.Tag = (LevelEditorObject)obj;
list.Items.Add(item);
}
if (list.Items.Count > 0)
{
list.Items[0].Focused = true;
CurrentImageIndex = 0;
}
}
private void MainForm_Load(object sender, EventArgs e)
{
Objects = new List<LevelEditorObject>();
MainImage = ImageGenerator.GetImage(ObjectType.OT_BG_Block);
Invalidate();
LoadEditorObjects();
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
}
private void pictureLevel_Paint(object sender, PaintEventArgs e)
{
Graphics xGraph;
xGraph = Graphics.FromImage(pictureLevel.Image);
xGraph.DrawImage(MainImage, 0, 0, MainImage.Width, MainImage.Height);
DrawAllObjects();
PutBox(LX, LY, CurrentImageIndex,false);
xGraph.Dispose();
}
private void pictureLevel_MouseMove(object sender, MouseEventArgs e)
{
int Divx,Divy,Divyi;
Divx = (e.X / 16);
Divy = (e.Y / 16);
LX = Divx*16;
LY = Divy*16;
PutBox(LX,LY,CurrentImageIndex,false);
Divyi = (MainImage.Height / 16) - (Divy+1);
OX = Divx;
OY = Divyi;
pictureLevel.Invalidate();
labelx.Text = "X = " + Divx.ToString();
labely.Text = "Y = " + Divyi.ToString();
timerobject.Enabled = true;
Seconds = 0;
objectnamelabel.Text = "";
}
private void pictureLevel_MouseEnter(object sender, EventArgs e)
{
Cursor.Hide();
}
private void pictureLevel_MouseLeave(object sender, EventArgs e)
{
Cursor.Show();
pictureLevel.Invalidate();
}
private void list_ItemActivate(object sender, EventArgs e)
{
int ind = list.FocusedItem.Index;
CurrentImageIndex = ind;
}
private void pictureLevel_MouseDown(object sender, MouseEventArgs e)
{
int Divx, Divy, Divyi;
Divx = (e.X / 16);
Divy = (e.Y / 16);
LX = Divx * 16;
LY = Divy * 16;
//PutBox(LX, LY, CurrentImageIndex);
Divyi = (MainImage.Height / 16) - (Divy + 1);
if (e.Button == MouseButtons.Left)
{
LevelEditorObject le = CheckPosition(Divx, Divyi);
if (le == null)
{
le = new LevelEditorObject((LevelEditorObject)list.Items[CurrentImageIndex].Tag);
le.x = Divx;
le.y = Divyi;
Objects.Add(le);
}
else
{
if (le.ParamTypes != null)
{
FormParams PR = new FormParams(le);
PR.ShowDialog();
if (PR.Update)
le = PR.MainObject;
PR.Dispose();
}
}
}
if (e.Button == MouseButtons.Right)
{
LevelEditorObject le = CheckPosition(Divx, Divyi);
if (le != null)
{
Objects.Remove(le);
pictureLevel.Invalidate();
}
}
}
private void mSave_Click(object sender, EventArgs e)
{
MarioEditorXML.Save_To_XML(FileName,Objects);
}
private void mOpen_Click(object sender, EventArgs e)
{
dOpen.ShowDialog();
if (dOpen.FileName.Length == 0)
return;
FileName = dOpen.FileName;
Objects = MarioEditorXML.Load_From_XML(dOpen.FileName);
SetListIndexToObjects();
}
public void SetListIndexToObjects()
{
foreach (LevelEditorObject le in Objects)
{
LevelEditorObject tmp =
(LevelEditorObject)(list.Items.Find(le.name, false)[0].Tag);
le.ListIndex = tmp.ListIndex;
}
}
public LevelEditorObject CheckPosition(int x, int y)
{
LevelEditorObject Res = null;
for (int i = 0; i < Objects.Count; i++)
if (x == Objects[i].x && y == Objects[i].y)
return Objects[i];
return Res;
}
private void list_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == (int)Keys.Space)
{
LevelEditorObject le = CheckPosition(OX,OY);
if (le != null)
{
le.Checked = !le.Checked;
}
}
}
private void offsetXSelectedToolStripMenuItem_Click(object sender, EventArgs e)
{
string X = Microsoft.VisualBasic.Interaction.InputBox("Enter X Offset", "X Offset", "1",Width/2,Height/2);
try
{
int xVal = System.Convert.ToInt16(X);
foreach (LevelEditorObject le in Objects)
if (le.Checked)
{
le.x = le.x + xVal;
le.Checked = false;
}
pictureLevel.Invalidate();
}
catch
{
MessageBox.Show("Wrong Parameters...");
}
}
private void offsetYSelectedToolStripMenuItem_Click(object sender, EventArgs e)
{
string Y = Microsoft.VisualBasic.Interaction.InputBox("Enter Y Offset", "Y Offset", "1",Width/2,Height/2);
try
{
int yVal = System.Convert.ToInt16(Y);
foreach (LevelEditorObject le in Objects)
if (le.Checked)
{
le.y = le.y - yVal;
le.Checked = false;
}
pictureLevel.Invalidate();
}
catch
{
MessageBox.Show("Wrong Parameters...");
}
}
private void mSaveAs_Click(object sender, EventArgs e)
{
dSave.ShowDialog();
if (dSave.FileName.Length == 0)
return;
MarioEditorXML.Save_To_XML(dSave.FileName, Objects);
}
private void timerobject_Tick(object sender, EventArgs e)
{
Seconds++;
if (Seconds >= 10)
{
LevelEditorObject le = CheckPosition(OX, OY);
if (le != null)
{
objectnamelabel.Text = le.name;
timerobject.Enabled = false;
}
}
}
}
}
| |
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Enums;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using Google.Protobuf;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Threading;
using static Google.Ads.GoogleAds.V10.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.AssetFieldTypeEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.CallConversionReportingStateEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.DayOfWeekEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.MinuteOfHourEnum.Types;
using SystemDayOfWeek = System.DayOfWeek;
using DayOfWeek = Google.Ads.GoogleAds.V10.Enums.DayOfWeekEnum.Types.DayOfWeek;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This example adds a call extension to a specific account.
/// </summary>
public class AddCall : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddCall"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID.")]
public long CustomerId { get; set; }
/// <summary>
/// Optional: The phone number country.
///
/// Specifies the phone country code here or the default specified in <see cref="Main"/>
/// will be used. See supported codes at:
/// https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17
/// </summary>
[Option("phoneCountry", Required = false, HelpText =
"The phone number country.")]
public string PhoneCountry { get; set; }
/// <summary>
/// The phone number itself.
/// </summary>
[Option("phoneNumber", Required = true, HelpText =
"The phone number itself.")]
public string PhoneNumber { get; set; }
/// <summary>
/// Optional: Specifies the conversion action ID to attribute call conversions to. If not set,
/// the default conversion action is used.
/// </summary>
[Option("conversionActionId", Required = false, HelpText =
"The conversion action ID.")]
public long ConversionActionId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The phone number country.
options.PhoneCountry = "US";
// The phone number itself.
options.PhoneNumber = "INSERT_PHONE_NUMBER_HERE";
// The conversion action ID.
options.ConversionActionId = long.Parse("INSERT_CONVERSION_ACTION_ID_HERE");
return 0;
});
AddCall codeExample = new AddCall();
Console.WriteLine(codeExample.Description);
codeExample.Run(
new GoogleAdsClient(),
options.CustomerId,
options.PhoneCountry,
options.PhoneNumber,
options.ConversionActionId
);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This example adds a call ad to a given ad group.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <param name="phoneCountry">The phone number country.</param>
/// <param name="phoneNumber">The phone number itself.</param>
/// <param name="conversionActionId">The conversion action ID or null.</param>
public void Run(
GoogleAdsClient client,
long customerId,
string phoneCountry,
string phoneNumber,
long? conversionActionId)
{
try
{
// Creates the asset for the call extensions.
string assetResourceName = AddExtensionAsset(
client,
customerId,
phoneCountry,
phoneNumber,
conversionActionId
);
// Adds the extensions at the account level, so these will serve in all eligible
// campaigns.
LinkAssetToAccount(client, customerId, assetResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates a new asset for the call.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <param name="phoneCountry">The phone number country.</param>
/// <param name="phoneNumber">The phone number itself.</param>
/// <param name="conversionActionId">The conversion action ID or null.</param>
/// <returns>The resource name of the created call asset</returns>
private string AddExtensionAsset(
GoogleAdsClient client,
long customerId,
string phoneCountry,
string phoneNumber,
long? conversionActionId)
{
// Creates the call asset.
CallAsset callAsset = new CallAsset()
{
// Sets the country code and phone number of the business to call.
CountryCode = phoneCountry,
PhoneNumber = phoneNumber,
// Optional: Specifies all day and time intervals for which the asset may serve.
AdScheduleTargets = {
new AdScheduleInfo()
{
// Sets the day of this schedule as Monday.
DayOfWeek = DayOfWeek.Monday,
// Sets the start hour to 9am.
StartHour = 9,
// Sets the end hour to 5pm.
EndHour = 17,
// Sets the start and end minute of zero, for example: 9:00 and 5:00.
StartMinute = MinuteOfHour.Zero,
EndMinute = MinuteOfHour.Zero
}
}
};
// Sets the conversion action ID to the one provided if any.
if (conversionActionId.HasValue)
{
callAsset.CallConversionAction =
ResourceNames.ConversionAction(customerId, conversionActionId.Value);
callAsset.CallConversionReportingState =
CallConversionReportingState.UseResourceLevelCallConversionAction;
}
// Creates an asset operation wrapping the call asset in an asset.
AssetOperation assetOperation = new AssetOperation()
{
Create = new Asset()
{
CallAsset = callAsset
}
};
AssetServiceClient assetServiceClient =
client.GetService(Services.V10.AssetService);
// Issues a mutate request to add the asset and prints its information.
MutateAssetsResponse response = assetServiceClient.MutateAssets(
customerId.ToString(),
new[] { assetOperation }
);
string createdAssetResourceName = response.Results.First().ResourceName;
Console.WriteLine(
$"Created a call asset with resource name: '{createdAssetResourceName}'."
);
return createdAssetResourceName;
}
/// <summary>
/// Links the call asset at the account level to serve in all eligible campaigns.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <param name="assetResourceName">The resource name of the call asset.</param>
private void LinkAssetToAccount(
GoogleAdsClient client,
long customerId,
string assetResourceName)
{
// Creates a customer asset operation wrapping the call asset in a customer asset.
CustomerAssetOperation customerAssetOperation = new CustomerAssetOperation()
{
Create = new CustomerAsset()
{
Asset = assetResourceName,
FieldType = AssetFieldType.Call
}
};
CustomerAssetServiceClient customerAssetServiceClient =
client.GetService(Services.V10.CustomerAssetService);
// Issues a mutate request to add the customer asset and prints its information.
MutateCustomerAssetsResponse response = customerAssetServiceClient.MutateCustomerAssets(
customerId.ToString(),
new[] { customerAssetOperation }
);
string resourceName = response.Results.First().ResourceName;
Console.WriteLine(
$"Created a customer asset with resource name: '{resourceName}'."
);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NCDO.Catalog;
using NCDO.Definitions;
using NCDO.Events;
using NCDO.Interfaces;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace NCDO
{
/// <summary>
/// CDOSession
/// </summary>
public partial class CDOSession : ICDOSession
{
#region Constructor
public CDOSession(CDOSessionOptions options)
{
Options = options;
Instance = this; //used by cdo when no session object is passed
//init httpclient
HttpClient = new HttpClient(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});
//HttpClient = new HttpClient(new HttpClientHandler() { SslProtocols = _options.SslProtocols }); //this is not supported in older frameworks & problematic in Outlook VSTO
ServicePointManager.SecurityProtocol = Options.SecurityProtocol;
HttpClient.DefaultRequestHeaders.ConnectionClose = false;
HttpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache");
HttpClient.DefaultRequestHeaders.Pragma.Add(NameValueHeaderValue.Parse("no-cache"));
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Task.Factory.StartNew(() =>
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged).Wait();
}
#endregion
public CDOSessionOptions Options { get; private set; }
/// <inheritdoc />
public Uri ServiceURI => Options.ServiceUri;
public string UserName => Options.ClientId;
public HttpClient HttpClient { get; }
private readonly Dictionary<Uri, ICDOCatalog> _catalogs = new Dictionary<Uri, ICDOCatalog>();
private readonly TokenCache _tokenCache = new TokenCache();
private AuthenticationContext _authContext;
/// <summary>
/// Internal ~ Returns the token to pass in the headers for the given challenge
/// </summary>
private async Task<string> GetChallengeToken()
{
switch (AuthenticationModel)
{
case AuthenticationModel.Basic:
if (Options.ClientId == null) throw new ArgumentNullException(nameof(Options.ClientId));
if (Options.ClientSecret == null) throw new ArgumentNullException(nameof(Options.ClientSecret));
return Convert.ToBase64String(
Encoding.UTF8.GetBytes($"{Options.ClientId}:{Options.ClientSecret}"));
case AuthenticationModel.Bearer:
case AuthenticationModel.Bearer_OnBehalf:
if (Options.ClientId == null) throw new ArgumentNullException(nameof(Options.ClientId));
if (Options.ClientSecret == null) throw new ArgumentNullException(nameof(Options.ClientSecret));
if (Options.Authority == null) throw new ArgumentNullException(nameof(Options.Authority));
if (Options.Audience == null) throw new ArgumentNullException(nameof(Options.Audience));
_authContext = new AuthenticationContext(Options.Authority, _tokenCache);
var clientCredential = new ClientCredential(Options.ClientId, Options.ClientSecret);
if (AuthenticationModel == AuthenticationModel.Bearer_OnBehalf)
{
var tokenAssertion = Options.UserAccessToken.Invoke();
var userName = Options.UserName.Invoke();
if (tokenAssertion != null && userName != null)
{
try
{
UserAssertion userAssertion = new UserAssertion(tokenAssertion,
"urn:ietf:params:oauth:grant-type:jwt-bearer", Options.UserName.Invoke());
return (await _authContext.AcquireTokenAsync(Options.Audience, clientCredential,
userAssertion))
.AccessToken;
}
catch
{
//swallow
}
}
}
return (await _authContext.AcquireTokenAsync(Options.Audience, clientCredential)).AccessToken;
case AuthenticationModel.Bearer_WIA:
if (Options.ClientId == null) throw new ArgumentNullException(nameof(Options.ClientId));
if (Options.Authority == null) throw new ArgumentNullException(nameof(Options.Authority));
if (Options.Audience == null) throw new ArgumentNullException(nameof(Options.Audience));
_authContext = new AuthenticationContext(Options.Authority, _tokenCache);
var userCredential = new UserCredential();
return (await _authContext.AcquireTokenAsync(Options.Audience, Options.ClientId, userCredential))
.AccessToken;
}
return null;
}
#pragma warning disable 1998
public virtual async Task OnOpenRequest(HttpClient client, HttpRequestMessage request)
#pragma warning restore 1998
{
//add authorization if needed
if (AuthenticationModel != AuthenticationModel.Anonymous)
{
request.Headers.Authorization =
new AuthenticationHeaderValue(Options.Challenge, await GetChallengeToken());
}
}
public async Task AddCatalog(params Uri[] catalogUris)
{
ThrowIfDisposed();
foreach (var catalogUri in catalogUris)
{
if (!_catalogs.ContainsKey(catalogUri))
{
_catalogs.Add(catalogUri, await CDOCatalog.Load(catalogUri, this));
}
}
}
public void LoadEmbeddedCatalog(Assembly assembly, string catalogResource)
{
ThrowIfDisposed();
using (var stream = assembly.GetManifestResourceStream(catalogResource))
{
var catalogUri = new Uri($"file://{catalogResource}");
if (!_catalogs.ContainsKey(catalogUri))
{
_catalogs.Add(catalogUri, CDOCatalog.Load((JsonObject) JsonValue.Load(stream), this));
}
}
}
protected virtual string _loginURI { get; } = "/static/home.html";
public async Task<SessionStatus> Login(CancellationToken cancellationToken = default(CancellationToken),
bool fromRequest = false)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
try
{
if (Options.AuthenticationModel != AuthenticationModel.Bearer_OnBehalf ||
!string.IsNullOrEmpty(Options.UserName.Invoke()) || fromRequest)
{
var urlBuilder = new StringBuilder(Options.ServiceUri.AbsoluteUri);
using (var request = new HttpRequestMessage())
{
await PrepareLoginRequest(request, urlBuilder);
await OnOpenRequest(HttpClient, request);
var response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead,
cancellationToken);
await ProcessLoginResponse(response);
}
}
}
catch (Exception)
{
//swallow
}
return LoginResult;
}
#pragma warning disable 1998
public virtual async Task ProcessLoginResponse(HttpResponseMessage response)
#pragma warning restore 1998
{
LoginHttpStatus = response.StatusCode;
}
#pragma warning disable 1998
public virtual async Task PrepareLoginRequest(HttpRequestMessage request, StringBuilder urlBuilder)
#pragma warning restore 1998
{
urlBuilder.Append(_loginURI);
request.Method = new HttpMethod("GET");
request.RequestUri = new Uri(urlBuilder.ToString(), UriKind.RelativeOrAbsolute);
}
#pragma warning disable 1998
public async Task Logout()
#pragma warning restore 1998
{
ThrowIfDisposed();
//throw new NotImplementedException();
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
Login().Wait();
Online?.Invoke(this, new CDOEventArgs() {Session = this});
}
else
{
LoginHttpStatus = HttpStatusCode.ServiceUnavailable;
Offline?.Invoke(this, new CDOOfflineEventArgs() {Session = this});
}
}
public event EventHandler<CDOEventArgs> Online;
public event EventHandler<CDOOfflineEventArgs> Offline;
public AuthenticationModel AuthenticationModel => Options.AuthenticationModel;
public ICollection<Uri> CatalogURIs { get; } = new List<Uri>();
public string ClientContextId { get; set; }
public ICloudDataObject[] CDOs { get; set; }
public bool Connected => NetworkInterface.GetIsNetworkAvailable();
public HttpStatusCode LoginHttpStatus { get; private set; } = HttpStatusCode.Ambiguous;
public SessionStatus LoginResult
{
get
{
switch (LoginHttpStatus)
{
case HttpStatusCode.OK:
return SessionStatus.AUTHENTICATION_SUCCESS;
case HttpStatusCode.Unauthorized:
return SessionStatus.AUTHENTICATION_FAILURE;
default:
return SessionStatus.GENERAL_FAILURE;
}
}
}
public IEnumerable<Service> Services
{
get
{
var services = new List<Service>();
foreach (var catalog in _catalogs)
{
services.AddRange(catalog.Value.Services);
}
return services;
}
}
/// <summary>
/// Latest initialized CDOSession
/// </summary>
public static ICDOSession Instance { get; internal set; }
/// <summary>
/// Returns the version of NCDO
/// Can be used by the clientgen to see if the ncdo version is supported.
/// </summary>
public static string Version
{
get
{
var assembly = Assembly.GetExecutingAssembly();
var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
return fileVersionInfo.ProductVersion;
}
}
#region Catalog Extensions
/// <summary>
/// Verify if the resource is available and return the catalog definition for the catalog
/// </summary>
/// <param name="resource"></param>
/// <returns></returns>
public (Service service, Resource resource) VerifyResourceName(string resource)
{
var serviceDefinition = Services.FirstOrDefault(s => s.Resources.Any(r => r.Name.Equals(resource)));
var resourceDefinition = serviceDefinition?.Resources.FirstOrDefault(r => r.Name.Equals(resource));
if (resourceDefinition == null)
throw new NotSupportedException($"Invalid resource name {resource}.");
return (serviceDefinition, resourceDefinition);
}
public Operation VerifyOperation(string resource, string operation,
OperationType operationType = OperationType.Invoke)
{
var resourceDefinition = VerifyResourceName(resource).resource;
var operationDefinition = resourceDefinition?.Operations.FirstOrDefault(o =>
o.Type == operationType && (string.IsNullOrEmpty(operation) || o.Name.Equals(operation)));
if (operationDefinition == null)
throw new NotSupportedException($"Invalid {operationType} operation {operation}.");
return operationDefinition;
}
public string DetermineMainTable(string resource)
{
var resourceDefinition = VerifyResourceName(resource).resource;
return resourceDefinition.Relations != null && resourceDefinition.Relations.Count > 0
? resourceDefinition.Relations.FirstOrDefault().ParentName
: resourceDefinition.Schema?.Properties.FirstOrDefault().Value.Properties.FirstOrDefault().Key;
}
public string DeterminePrimaryKey(string resource, string tableName)
{
var resourceDefinition = VerifyResourceName(resource).resource;
return resourceDefinition.Schema?.Properties.FirstOrDefault().Value.Properties[tableName]
.PrimaryKey.FirstOrDefault();
}
#endregion
#region IDisposable Support
~CDOSession()
{
Dispose(false);
}
private bool _disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || this._disposed)
return;
// HttpClient?.Dispose(); //https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
_disposed = true;
}
/// <summary>Throws if this class has been disposed.</summary>
protected void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
}
}
| |
using System;
using System.Linq;
using MonikTerminal;
using MonikTerminal.Enums;
using MonikTerminal.Interfaces;
using MonikTerminal.ModelsApi;
using Moq;
using NUnit.Framework;
namespace MonicTerminalTests
{
[TestFixture]
public class LogTerminalTests
{
private LogTerminal terminal;
private Mock<IMonikService> monicMock = new Mock<IMonikService>();
private IConfig config = Config.Default();
private Mock<ISourcesCache> cacheMock = new Mock<ISourcesCache>();
[OneTimeSetUp]
public void Inicialise()
{
terminal = new LogTerminal(monicMock.Object, config, cacheMock.Object);
}
[Test]
public void TestGrouping_Empty_Returns_Empty()
{
var logs = new ELog_[0];
var rez = terminal.GroupDuplicatingLogs(logs);
Assert.That(!rez.Any());
}
[Test]
public void TestGrouping_NoDoubling_Returns_TheSameLogs()
{
var curTime = DateTime.Now;
var logs = new[]
{
new ELog_()
{
Created = curTime,
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod+1),
Body = "testBody2",
InstanceID = 2,
Level = (byte)LevelType.Logic,
Severity = (byte)SeverityCutoffType.Error
},
};
var rez = terminal.GroupDuplicatingLogs(logs);
Assert.That(rez, Is.EquivalentTo(logs));
}
[Test]
public void TestGrouping_DoublingInOnlyOneField_Returns_TheSameLogs()
{
var curTime = DateTime.Now;
var logs = new[]
{
new ELog_()
{
Created = curTime,
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod+1),
Body = "testBody2",
InstanceID = 2,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Error
},
};
var rez = terminal.GroupDuplicatingLogs(logs);
Assert.That(rez, Is.EquivalentTo(logs));
}
[Test]
public void TestGrouping_DoublingWithoutTime_Returns_TheSameLogs()
{
var curTime = DateTime.Now;
var logs = new[]
{
new ELog_()
{
Created = curTime,
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod+1),
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
};
var rez = terminal.GroupDuplicatingLogs(logs);
Assert.That(rez, Is.EquivalentTo(logs));
}
[Test]
public void TestGrouping_Doubling_Returns_First()
{
var curTime = DateTime.Now;
var logs = new[]
{
new ELog_()
{
Created = curTime,
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod-1),
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
};
var rez = terminal.GroupDuplicatingLogs(logs);
Assert.That(rez, Is.EquivalentTo(new[] { logs.First() }));
Assert.That(rez.First().Doubled);
}
[Test]
public void TestGrouping_Doubling_and_NotDoubledTime_AndNotDoubling_Returns_Firsts()
{
var curTime = DateTime.Now;
var logs = new[]
{
new ELog_()
{
Created = curTime,
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod-1),
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod+1),
Body = "testBody1",
InstanceID = 1,
Level = (byte)LevelType.Application,
Severity = (byte)SeverityCutoffType.Info
},
new ELog_()
{
Created = curTime.AddSeconds(config.Common.RefreshPeriod+1),
Body = "testBody2",
InstanceID = 2,
Level = (byte)LevelType.Logic,
Severity = (byte)SeverityCutoffType.Error
},
};
var rez = terminal.GroupDuplicatingLogs(logs).ToArray();
Assert.That(rez, Is.EquivalentTo(new[] { logs[0], logs[2], logs[3] }));
Assert.That(rez[0].Doubled);
Assert.That(!rez[1].Doubled);
Assert.That(!rez[2].Doubled);
}
[Test]
public void ExcludeKeywordsTest()
{
config.Log.ExcludeKeywords = new[] {"excludeMe"};
var logs = new[]
{
new ELog_ {Body = "Hoho1"},
new ELog_ {Body = "HohoExClUdEmEHoHo"},
new ELog_ {Body = "Hoho2"},
};
var result = terminal.FilterExcludeKeywords(logs);
Assert.That(result, Is.EquivalentTo(new[] {logs[0], logs[2]}));
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elastictranscoder-2012-09-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticTranscoder.Model
{
/// <summary>
/// Container for the parameters to the UpdatePipeline operation.
/// Use the <code>UpdatePipeline</code> operation to update settings for a pipeline.
/// <important>When you change pipeline settings, your changes take effect immediately.
/// Jobs that you have already submitted and that Elastic Transcoder has not started to
/// process are affected in addition to jobs that you submit after you change settings.
/// </important>
/// </summary>
public partial class UpdatePipelineRequest : AmazonElasticTranscoderRequest
{
private string _awsKmsKeyArn;
private PipelineOutputConfig _contentConfig;
private string _id;
private string _inputBucket;
private string _name;
private Notifications _notifications;
private string _role;
private PipelineOutputConfig _thumbnailConfig;
/// <summary>
/// Gets and sets the property AwsKmsKeyArn.
/// <para>
/// The AWS Key Management Service (AWS KMS) key that you want to use with this pipeline.
/// </para>
///
/// <para>
/// If you use either <code>S3</code> or <code>S3-AWS-KMS</code> as your <code>Encryption:Mode</code>,
/// you don't need to provide a key with your job because a default key, known as an AWS-KMS
/// key, is created for you automatically. You need to provide an AWS-KMS key only if
/// you want to use a non-default AWS-KMS key, or if you are using an <code>Encryption:Mode</code>
/// of <code>AES-PKCS7</code>, <code>AES-CTR</code>, or <code>AES-GCM</code>.
/// </para>
/// </summary>
public string AwsKmsKeyArn
{
get { return this._awsKmsKeyArn; }
set { this._awsKmsKeyArn = value; }
}
// Check to see if AwsKmsKeyArn property is set
internal bool IsSetAwsKmsKeyArn()
{
return this._awsKmsKeyArn != null;
}
/// <summary>
/// Gets and sets the property ContentConfig.
/// <para>
/// The optional <code>ContentConfig</code> object specifies information about the Amazon
/// S3 bucket in which you want Elastic Transcoder to save transcoded files and playlists:
/// which bucket to use, which users you want to have access to the files, the type of
/// access you want users to have, and the storage class that you want to assign to the
/// files.
/// </para>
///
/// <para>
/// If you specify values for <code>ContentConfig</code>, you must also specify values
/// for <code>ThumbnailConfig</code>.
/// </para>
///
/// <para>
/// If you specify values for <code>ContentConfig</code> and <code>ThumbnailConfig</code>,
/// omit the <code>OutputBucket</code> object.
/// </para>
/// <ul> <li> <b>Bucket</b>: The Amazon S3 bucket in which you want Elastic Transcoder
/// to save transcoded files and playlists.</li> <li> <b>Permissions</b> (Optional): The
/// Permissions object specifies which users you want to have access to transcoded files
/// and the type of access you want them to have. You can grant permissions to a maximum
/// of 30 users and/or predefined Amazon S3 groups.</li> <li> <b>Grantee Type</b>: Specify
/// the type of value that appears in the <code>Grantee</code> object: <ul> <li> <b>Canonical</b>:
/// The value in the <code>Grantee</code> object is either the canonical user ID for an
/// AWS account or an origin access identity for an Amazon CloudFront distribution. For
/// more information about canonical user IDs, see Access Control List (ACL) Overview
/// in the Amazon Simple Storage Service Developer Guide. For more information about using
/// CloudFront origin access identities to require that users use CloudFront URLs instead
/// of Amazon S3 URLs, see Using an Origin Access Identity to Restrict Access to Your
/// Amazon S3 Content. <important>A canonical user ID is not the same as an AWS account
/// number.</important> </li> <li> <b>Email</b>: The value in the <code>Grantee</code>
/// object is the registered email address of an AWS account.</li> <li> <b>Group</b>:
/// The value in the <code>Grantee</code> object is one of the following predefined Amazon
/// S3 groups: <code>AllUsers</code>, <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>.</li>
/// </ul> </li> <li> <b>Grantee</b>: The AWS user or group that you want to have access
/// to transcoded files and playlists. To identify the user or group, you can specify
/// the canonical user ID for an AWS account, an origin access identity for a CloudFront
/// distribution, the registered email address of an AWS account, or a predefined Amazon
/// S3 group </li> <li> <b>Access</b>: The permission that you want to give to the AWS
/// user that you specified in <code>Grantee</code>. Permissions are granted on the files
/// that Elastic Transcoder adds to the bucket, including playlists and video files. Valid
/// values include: <ul> <li> <code>READ</code>: The grantee can read the objects and
/// metadata for objects that Elastic Transcoder adds to the Amazon S3 bucket.</li> <li>
/// <code>READ_ACP</code>: The grantee can read the object ACL for objects that Elastic
/// Transcoder adds to the Amazon S3 bucket. </li> <li> <code>WRITE_ACP</code>: The grantee
/// can write the ACL for the objects that Elastic Transcoder adds to the Amazon S3 bucket.</li>
/// <li> <code>FULL_CONTROL</code>: The grantee has <code>READ</code>, <code>READ_ACP</code>,
/// and <code>WRITE_ACP</code> permissions for the objects that Elastic Transcoder adds
/// to the Amazon S3 bucket.</li> </ul> </li> <li> <b>StorageClass</b>: The Amazon S3
/// storage class, <code>Standard</code> or <code>ReducedRedundancy</code>, that you want
/// Elastic Transcoder to assign to the video files and playlists that it stores in your
/// Amazon S3 bucket.</li> </ul>
/// </summary>
public PipelineOutputConfig ContentConfig
{
get { return this._contentConfig; }
set { this._contentConfig = value; }
}
// Check to see if ContentConfig property is set
internal bool IsSetContentConfig()
{
return this._contentConfig != null;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The ID of the pipeline that you want to update.
/// </para>
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property InputBucket.
/// <para>
/// The Amazon S3 bucket in which you saved the media files that you want to transcode
/// and the graphics that you want to use as watermarks.
/// </para>
/// </summary>
public string InputBucket
{
get { return this._inputBucket; }
set { this._inputBucket = value; }
}
// Check to see if InputBucket property is set
internal bool IsSetInputBucket()
{
return this._inputBucket != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the pipeline. We recommend that the name be unique within the AWS account,
/// but uniqueness is not enforced.
/// </para>
///
/// <para>
/// Constraints: Maximum 40 characters
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Notifications.
/// </summary>
public Notifications Notifications
{
get { return this._notifications; }
set { this._notifications = value; }
}
// Check to see if Notifications property is set
internal bool IsSetNotifications()
{
return this._notifications != null;
}
/// <summary>
/// Gets and sets the property Role.
/// <para>
/// The IAM Amazon Resource Name (ARN) for the role that you want Elastic Transcoder to
/// use to transcode jobs for this pipeline.
/// </para>
/// </summary>
public string Role
{
get { return this._role; }
set { this._role = value; }
}
// Check to see if Role property is set
internal bool IsSetRole()
{
return this._role != null;
}
/// <summary>
/// Gets and sets the property ThumbnailConfig.
/// <para>
/// The <code>ThumbnailConfig</code> object specifies several values, including the Amazon
/// S3 bucket in which you want Elastic Transcoder to save thumbnail files, which users
/// you want to have access to the files, the type of access you want users to have, and
/// the storage class that you want to assign to the files.
/// </para>
///
/// <para>
/// If you specify values for <code>ContentConfig</code>, you must also specify values
/// for <code>ThumbnailConfig</code> even if you don't want to create thumbnails.
/// </para>
///
/// <para>
/// If you specify values for <code>ContentConfig</code> and <code>ThumbnailConfig</code>,
/// omit the <code>OutputBucket</code> object.
/// </para>
/// <ul> <li> <b>Bucket</b>: The Amazon S3 bucket in which you want Elastic Transcoder
/// to save thumbnail files.</li> <li> <b>Permissions</b> (Optional): The <code>Permissions</code>
/// object specifies which users and/or predefined Amazon S3 groups you want to have access
/// to thumbnail files, and the type of access you want them to have. You can grant permissions
/// to a maximum of 30 users and/or predefined Amazon S3 groups.</li> <li> <b>GranteeType</b>:
/// Specify the type of value that appears in the Grantee object: <ul> <li> <b>Canonical</b>:
/// The value in the <code>Grantee</code> object is either the canonical user ID for an
/// AWS account or an origin access identity for an Amazon CloudFront distribution. <important>A
/// canonical user ID is not the same as an AWS account number.</important> </li> <li>
/// <b>Email</b>: The value in the <code>Grantee</code> object is the registered email
/// address of an AWS account. </li> <li> <b>Group</b>: The value in the <code>Grantee</code>
/// object is one of the following predefined Amazon S3 groups: <code>AllUsers</code>,
/// <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>.</li> </ul> </li> <li>
/// <b>Grantee</b>: The AWS user or group that you want to have access to thumbnail files.
/// To identify the user or group, you can specify the canonical user ID for an AWS account,
/// an origin access identity for a CloudFront distribution, the registered email address
/// of an AWS account, or a predefined Amazon S3 group. </li> <li> <b>Access</b>: The
/// permission that you want to give to the AWS user that you specified in <code>Grantee</code>.
/// Permissions are granted on the thumbnail files that Elastic Transcoder adds to the
/// bucket. Valid values include: <ul> <li> <code>READ</code>: The grantee can read the
/// thumbnails and metadata for objects that Elastic Transcoder adds to the Amazon S3
/// bucket.</li> <li> <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails
/// that Elastic Transcoder adds to the Amazon S3 bucket. </li> <li> <code>WRITE_ACP</code>:
/// The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the
/// Amazon S3 bucket.</li> <li> <code>FULL_CONTROL</code>: The grantee has <code>READ</code>,
/// <code>READ_ACP</code>, and <code>WRITE_ACP</code> permissions for the thumbnails that
/// Elastic Transcoder adds to the Amazon S3 bucket. </li> </ul> </li> <li> <b>StorageClass</b>:
/// The Amazon S3 storage class, <code>Standard</code> or <code>ReducedRedundancy</code>,
/// that you want Elastic Transcoder to assign to the thumbnails that it stores in your
/// Amazon S3 bucket.</li> </ul>
/// </summary>
public PipelineOutputConfig ThumbnailConfig
{
get { return this._thumbnailConfig; }
set { this._thumbnailConfig = value; }
}
// Check to see if ThumbnailConfig property is set
internal bool IsSetThumbnailConfig()
{
return this._thumbnailConfig != null;
}
}
}
| |
// 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.Reflection;
namespace System.ComponentModel
{
/// <devdoc>
/// This type description provider provides type information through
/// reflection. Unless someone has provided a custom type description
/// provider for a type or instance, or unless an instance implements
/// ICustomTypeDescriptor, any query for type information will go through
/// this class. There should be a single instance of this class associated
/// with "object", as it can provide all type information for any type.
/// </devdoc>
internal sealed class ReflectTypeDescriptionProvider
{
// This is where we store the various converters for the intrinsic types.
//
private static volatile Dictionary<object, object> s_intrinsicConverters;
// For converters, etc that are bound to class attribute data, rather than a class
// type, we have special key sentinel values that we put into the hash table.
//
private static object s_intrinsicNullableKey = new object();
private static object s_syncObject = new object();
/// <devdoc>
/// Creates a new ReflectTypeDescriptionProvider. The type is the
/// type we will obtain type information for.
/// </devdoc>
internal ReflectTypeDescriptionProvider()
{
}
/// <devdoc>
/// This is a table we create for intrinsic types.
/// There should be entries here ONLY for intrinsic
/// types, as all other types we should be able to
/// add attributes directly as metadata.
/// </devdoc>
private static Dictionary<object, object> IntrinsicTypeConverters
{
get
{
// It is not worth taking a lock for this -- worst case of a collision
// would build two tables, one that garbage collects very quickly.
//
if (ReflectTypeDescriptionProvider.s_intrinsicConverters == null)
{
Dictionary<object, object> temp = new Dictionary<object, object>();
// Add the intrinsics
//
temp[typeof(bool)] = typeof(BooleanConverter);
temp[typeof(byte)] = typeof(ByteConverter);
temp[typeof(SByte)] = typeof(SByteConverter);
temp[typeof(char)] = typeof(CharConverter);
temp[typeof(double)] = typeof(DoubleConverter);
temp[typeof(string)] = typeof(StringConverter);
temp[typeof(int)] = typeof(Int32Converter);
temp[typeof(short)] = typeof(Int16Converter);
temp[typeof(long)] = typeof(Int64Converter);
temp[typeof(float)] = typeof(SingleConverter);
temp[typeof(UInt16)] = typeof(UInt16Converter);
temp[typeof(UInt32)] = typeof(UInt32Converter);
temp[typeof(UInt64)] = typeof(UInt64Converter);
temp[typeof(object)] = typeof(TypeConverter);
temp[typeof(void)] = typeof(TypeConverter);
temp[typeof(DateTime)] = typeof(DateTimeConverter);
temp[typeof(DateTimeOffset)] = typeof(DateTimeOffsetConverter);
temp[typeof(Decimal)] = typeof(DecimalConverter);
temp[typeof(TimeSpan)] = typeof(TimeSpanConverter);
temp[typeof(Guid)] = typeof(GuidConverter);
temp[typeof(Array)] = typeof(ArrayConverter);
temp[typeof(ICollection)] = typeof(CollectionConverter);
temp[typeof(Enum)] = typeof(EnumConverter);
// Special cases for things that are not bound to a specific type
//
temp[ReflectTypeDescriptionProvider.s_intrinsicNullableKey] = typeof(NullableConverter);
ReflectTypeDescriptionProvider.s_intrinsicConverters = temp;
}
return ReflectTypeDescriptionProvider.s_intrinsicConverters;
}
}
/// <devdoc>
/// Helper method to create type converters. This checks to see if the
/// type implements a Type constructor, and if it does it invokes that ctor.
/// Otherwise, it just tries to create the type.
/// </devdoc>
private static object CreateInstance(Type objectType, Type parameterType, ref bool noTypeConstructor)
{
ConstructorInfo typeConstructor = null;
noTypeConstructor = true;
foreach (ConstructorInfo constructor in objectType.GetTypeInfo().DeclaredConstructors)
{
if (!constructor.IsPublic)
{
continue;
}
// This is the signature we look for when creating types that are generic, but
// want to know what type they are dealing with. Enums are a good example of this;
// there is one enum converter that can work with all enums, but it needs to know
// the type of enum it is dealing with.
//
ParameterInfo[] parameters = constructor.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.Equals(typeof(Type)))
{
continue;
}
typeConstructor = constructor;
break;
}
if (typeConstructor != null)
{
noTypeConstructor = false;
return typeConstructor.Invoke(new object[] { parameterType });
}
return Activator.CreateInstance(objectType);
}
private static TypeConverterAttribute GetTypeConverterAttributeIfAny(Type type)
{
foreach (TypeConverterAttribute attribute in type.GetTypeInfo().GetCustomAttributes<TypeConverterAttribute>(false))
{
return attribute;
}
return null;
}
/// <devdoc>
/// Gets a type converter for the specified type.
/// </devdoc>
internal static TypeConverter GetConverter(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
// Check the cached TypeConverter dictionary for an exact match of the given type.
object ans = SearchIntrinsicTable_ExactTypeMatch(type);
if (ans != null)
return (TypeConverter)ans;
// Obtaining attributes follows a very critical order: we must take care that
// we merge attributes the right way. Consider this:
//
// [A4]
// interface IBase;
//
// [A3]
// interface IDerived;
//
// [A2]
// class Base : IBase;
//
// [A1]
// class Derived : Base, IDerived
//
// We are retreving attributes in the following order: A1 - A4.
// Interfaces always lose to types, and interfaces and types
// must be looked up in the same order.
TypeConverterAttribute converterAttribute = ReflectTypeDescriptionProvider.GetTypeConverterAttributeIfAny(type);
if (converterAttribute == null)
{
Type baseType = type.GetTypeInfo().BaseType;
while (baseType != null && baseType != typeof(object))
{
converterAttribute = ReflectTypeDescriptionProvider.GetTypeConverterAttributeIfAny(baseType);
if (converterAttribute != null)
{
break;
}
baseType = baseType.GetTypeInfo().BaseType;
}
}
if (converterAttribute == null)
{
IEnumerable<Type> interfaces = type.GetTypeInfo().ImplementedInterfaces;
foreach (Type iface in interfaces)
{
// only do this for public interfaces.
//
if ((iface.GetTypeInfo().Attributes & (TypeAttributes.Public | TypeAttributes.NestedPublic)) != 0)
{
converterAttribute = GetTypeConverterAttributeIfAny(iface);
if (converterAttribute != null)
{
break;
}
}
}
}
if (converterAttribute != null)
{
Type converterType = ReflectTypeDescriptionProvider.GetTypeFromName(converterAttribute.ConverterTypeName, type);
if (converterType != null && typeof(TypeConverter).GetTypeInfo().IsAssignableFrom(converterType.GetTypeInfo()))
{
bool noTypeConstructor = true;
object instance = (TypeConverter)ReflectTypeDescriptionProvider.CreateInstance(converterType, type, ref noTypeConstructor);
if (noTypeConstructor)
ReflectTypeDescriptionProvider.IntrinsicTypeConverters[type] = instance;
return (TypeConverter)instance;
}
}
// We did not get a converter. Traverse up the base class chain until
// we find one in the stock hashtable.
//
return (TypeConverter)ReflectTypeDescriptionProvider.SearchIntrinsicTable(type);
}
/// <devdoc>
/// Retrieve a type from a name, if the name is not a fully qualified assembly name, then
/// look for this type name in the same assembly as the "type" parameter is defined in.
/// </devdoc>
private static Type GetTypeFromName(string typeName, Type type)
{
if (string.IsNullOrEmpty(typeName))
{
return null;
}
int commaIndex = typeName.IndexOf(',');
Type t = null;
if (commaIndex == -1)
{
t = type.GetTypeInfo().Assembly.GetType(typeName);
}
if (t == null)
{
t = Type.GetType(typeName);
}
return t;
}
/// <devdoc>
/// Searches the provided intrinsic hashtable for a match with the object type.
/// At the beginning, the hashtable contains types for the various converters.
/// As this table is searched, the types for these objects
/// are replaced with instances, so we only create as needed. This method
/// does the search up the base class hierarchy and will create instances
/// for types as needed. These instances are stored back into the table
/// for the base type, and for the original component type, for fast access.
/// </devdoc>
private static object SearchIntrinsicTable(Type callingType)
{
object hashEntry = null;
// We take a lock on this table. Nothing in this code calls out to
// other methods that lock, so it should be fairly safe to grab this
// lock. Also, this allows multiple intrinsic tables to be searched
// at once.
//
lock (ReflectTypeDescriptionProvider.s_syncObject)
{
Type baseType = callingType;
while (baseType != null && baseType != typeof(object))
{
if (ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(baseType, out hashEntry) && hashEntry != null)
{
break;
}
baseType = baseType.GetTypeInfo().BaseType;
}
TypeInfo callingTypeInfo = callingType.GetTypeInfo();
// Now make a scan through each value in the table, looking for interfaces.
// If we find one, see if the object implements the interface.
//
if (hashEntry == null)
{
foreach (object key in ReflectTypeDescriptionProvider.IntrinsicTypeConverters.Keys)
{
Type keyType = key as Type;
if (keyType != null)
{
TypeInfo keyTypeInfo = keyType.GetTypeInfo();
if (keyTypeInfo.IsInterface && keyTypeInfo.IsAssignableFrom(callingTypeInfo))
{
ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(key, out hashEntry);
string converterTypeString = hashEntry as string;
if (converterTypeString != null)
{
hashEntry = Type.GetType(converterTypeString);
if (hashEntry != null)
{
ReflectTypeDescriptionProvider.IntrinsicTypeConverters[callingType] = hashEntry;
}
}
if (hashEntry != null)
{
break;
}
}
}
}
}
// Special case converter
//
if (hashEntry == null)
{
if (callingTypeInfo.IsGenericType && callingTypeInfo.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// Check if it is a nullable value
ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(ReflectTypeDescriptionProvider.s_intrinsicNullableKey, out hashEntry);
}
}
// Interfaces do not derive from object, so we
// must handle the case of no hash entry here.
//
if (hashEntry == null)
{
ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(typeof(object), out hashEntry);
}
// If the entry is a type, create an instance of it and then
// replace the entry. This way we only need to create once.
// We can only do this if the object doesn't want a type
// in its constructor.
//
Type type = hashEntry as Type;
if (type != null)
{
bool noTypeConstructor = true;
hashEntry = ReflectTypeDescriptionProvider.CreateInstance(type, callingType, ref noTypeConstructor);
if (noTypeConstructor)
{
ReflectTypeDescriptionProvider.IntrinsicTypeConverters[callingType] = hashEntry;
}
}
}
return hashEntry;
}
private static object SearchIntrinsicTable_ExactTypeMatch(Type callingType)
{
object hashEntry = null;
// We take a lock on this table. Nothing in this code calls out to
// other methods that lock, so it should be fairly safe to grab this
// lock. Also, this allows multiple intrinsic tables to be searched
// at once.
//
lock (s_syncObject)
{
if (callingType != null && !IntrinsicTypeConverters.TryGetValue(callingType, out hashEntry))
return null;
// If the entry is a type, create an instance of it and then
// replace the entry. This way we only need to create once.
// We can only do this if the object doesn't want a type
// in its constructor.
Type type = hashEntry as Type;
if (type != null)
{
bool noTypeConstructor = true;
hashEntry = CreateInstance(type, callingType, ref noTypeConstructor);
if (noTypeConstructor)
IntrinsicTypeConverters[callingType] = hashEntry;
}
}
return hashEntry;
}
}
}
| |
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
<<<<<<< Updated upstream
// Generated from: ManagementResponse.proto
// Note: requires additional types generated from: Exception.proto
namespace Alachisoft.NosDB.Common.Protobuf.ManagementCommands
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ManagementResponse")]
public partial class ManagementResponse : global::ProtoBuf.IExtensible
{
public ManagementResponse() {}
=======
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Alachisoft.NoSDB.Common.Protobuf.ManagementCommands {
namespace Proto {
>>>>>>> Stashed changes
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class ManagementResponse {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.Builder> internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static ManagementResponse() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChhNYW5hZ2VtZW50UmVzcG9uc2UucHJvdG8SM0FsYWNoaXNvZnQuTm9TREIu",
"Q29tbW9uLlByb3RvYnVmLk1hbmFnZW1lbnRDb21tYW5kcxoPRXhjZXB0aW9u",
"LnByb3RvIrIBChJNYW5hZ2VtZW50UmVzcG9uc2USEQoJcmVxdWVzdElkGAEg",
"ASgDElEKCWV4Y2VwdGlvbhgCIAEoCzI+LkFsYWNoaXNvZnQuTm9TREIuQ29t",
"bW9uLlByb3RvYnVmLk1hbmFnZW1lbnRDb21tYW5kcy5FeGNlcHRpb24SDwoH",
"dmVyc2lvbhgDIAEoBRIRCglyZXR1cm5WYWwYBCABKAwSEgoKbWV0aG9kTmFt",
"ZRgFIAEoCUJCCiRjb20uYWxhY2hpc29mdC5ub3NkYi5jb21tb24ucHJvdG9i",
"dWZCGk1hbmFnZW1lbnRSZXNwb25zZVByb3RvY29s"));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__Descriptor = Descriptor.MessageTypes[0];
internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.Builder>(internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__Descriptor,
new string[] { "RequestId", "Exception", "Version", "ReturnVal", "MethodName", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.Exception.Descriptor,
}, assigner);
}
#endregion
}
<<<<<<< Updated upstream
private Alachisoft.NosDB.Common.Protobuf.ManagementCommands.Exception _exception = null;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"exception", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public Alachisoft.NosDB.Common.Protobuf.ManagementCommands.Exception exception
{
get { return _exception; }
set { _exception = value; }
=======
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ManagementResponse : pb::GeneratedMessage<ManagementResponse, ManagementResponse.Builder> {
private ManagementResponse() { }
private static readonly ManagementResponse defaultInstance = new ManagementResponse().MakeReadOnly();
private static readonly string[] _managementResponseFieldNames = new string[] { "exception", "methodName", "requestId", "returnVal", "version" };
private static readonly uint[] _managementResponseFieldTags = new uint[] { 18, 42, 8, 34, 24 };
public static ManagementResponse DefaultInstance {
get { return defaultInstance; }
>>>>>>> Stashed changes
}
public override ManagementResponse DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ManagementResponse ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementResponse.internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ManagementResponse, ManagementResponse.Builder> InternalFieldAccessors {
get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementResponse.internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementResponse__FieldAccessorTable; }
}
public const int RequestIdFieldNumber = 1;
private bool hasRequestId;
private long requestId_;
public bool HasRequestId {
get { return hasRequestId; }
}
public long RequestId {
get { return requestId_; }
}
public const int ExceptionFieldNumber = 2;
private bool hasException;
private global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception exception_;
public bool HasException {
get { return hasException; }
}
public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception Exception {
get { return exception_ ?? global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception.DefaultInstance; }
}
public const int VersionFieldNumber = 3;
private bool hasVersion;
private int version_;
public bool HasVersion {
get { return hasVersion; }
}
public int Version {
get { return version_; }
}
public const int ReturnValFieldNumber = 4;
private bool hasReturnVal;
private pb::ByteString returnVal_ = pb::ByteString.Empty;
public bool HasReturnVal {
get { return hasReturnVal; }
}
public pb::ByteString ReturnVal {
get { return returnVal_; }
}
public const int MethodNameFieldNumber = 5;
private bool hasMethodName;
private string methodName_ = "";
public bool HasMethodName {
get { return hasMethodName; }
}
public string MethodName {
get { return methodName_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _managementResponseFieldNames;
if (hasRequestId) {
output.WriteInt64(1, field_names[2], RequestId);
}
if (hasException) {
output.WriteMessage(2, field_names[0], Exception);
}
if (hasVersion) {
output.WriteInt32(3, field_names[4], Version);
}
if (hasReturnVal) {
output.WriteBytes(4, field_names[3], ReturnVal);
}
if (hasMethodName) {
output.WriteString(5, field_names[1], MethodName);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasRequestId) {
size += pb::CodedOutputStream.ComputeInt64Size(1, RequestId);
}
if (hasException) {
size += pb::CodedOutputStream.ComputeMessageSize(2, Exception);
}
if (hasVersion) {
size += pb::CodedOutputStream.ComputeInt32Size(3, Version);
}
if (hasReturnVal) {
size += pb::CodedOutputStream.ComputeBytesSize(4, ReturnVal);
}
if (hasMethodName) {
size += pb::CodedOutputStream.ComputeStringSize(5, MethodName);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ManagementResponse ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ManagementResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ManagementResponse ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ManagementResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ManagementResponse ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ManagementResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ManagementResponse ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ManagementResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ManagementResponse ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ManagementResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ManagementResponse MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ManagementResponse prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ManagementResponse, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ManagementResponse cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ManagementResponse result;
private ManagementResponse PrepareBuilder() {
if (resultIsReadOnly) {
ManagementResponse original = result;
result = new ManagementResponse();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ManagementResponse MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.Descriptor; }
}
public override ManagementResponse DefaultInstanceForType {
get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.DefaultInstance; }
}
public override ManagementResponse BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ManagementResponse) {
return MergeFrom((ManagementResponse) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ManagementResponse other) {
if (other == global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.DefaultInstance) return this;
PrepareBuilder();
if (other.HasRequestId) {
RequestId = other.RequestId;
}
if (other.HasException) {
MergeException(other.Exception);
}
if (other.HasVersion) {
Version = other.Version;
}
if (other.HasReturnVal) {
ReturnVal = other.ReturnVal;
}
if (other.HasMethodName) {
MethodName = other.MethodName;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_managementResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _managementResponseFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasRequestId = input.ReadInt64(ref result.requestId_);
break;
}
case 18: {
global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception.Builder subBuilder = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception.CreateBuilder();
if (result.hasException) {
subBuilder.MergeFrom(Exception);
}
input.ReadMessage(subBuilder, extensionRegistry);
Exception = subBuilder.BuildPartial();
break;
}
case 24: {
result.hasVersion = input.ReadInt32(ref result.version_);
break;
}
case 34: {
result.hasReturnVal = input.ReadBytes(ref result.returnVal_);
break;
}
case 42: {
result.hasMethodName = input.ReadString(ref result.methodName_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasRequestId {
get { return result.hasRequestId; }
}
public long RequestId {
get { return result.RequestId; }
set { SetRequestId(value); }
}
public Builder SetRequestId(long value) {
PrepareBuilder();
result.hasRequestId = true;
result.requestId_ = value;
return this;
}
public Builder ClearRequestId() {
PrepareBuilder();
result.hasRequestId = false;
result.requestId_ = 0L;
return this;
}
public bool HasException {
get { return result.hasException; }
}
public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception Exception {
get { return result.Exception; }
set { SetException(value); }
}
public Builder SetException(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasException = true;
result.exception_ = value;
return this;
}
public Builder SetException(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasException = true;
result.exception_ = builderForValue.Build();
return this;
}
public Builder MergeException(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasException &&
result.exception_ != global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception.DefaultInstance) {
result.exception_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Exception.CreateBuilder(result.exception_).MergeFrom(value).BuildPartial();
} else {
result.exception_ = value;
}
result.hasException = true;
return this;
}
public Builder ClearException() {
PrepareBuilder();
result.hasException = false;
result.exception_ = null;
return this;
}
public bool HasVersion {
get { return result.hasVersion; }
}
public int Version {
get { return result.Version; }
set { SetVersion(value); }
}
public Builder SetVersion(int value) {
PrepareBuilder();
result.hasVersion = true;
result.version_ = value;
return this;
}
public Builder ClearVersion() {
PrepareBuilder();
result.hasVersion = false;
result.version_ = 0;
return this;
}
public bool HasReturnVal {
get { return result.hasReturnVal; }
}
public pb::ByteString ReturnVal {
get { return result.ReturnVal; }
set { SetReturnVal(value); }
}
public Builder SetReturnVal(pb::ByteString value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasReturnVal = true;
result.returnVal_ = value;
return this;
}
public Builder ClearReturnVal() {
PrepareBuilder();
result.hasReturnVal = false;
result.returnVal_ = pb::ByteString.Empty;
return this;
}
public bool HasMethodName {
get { return result.hasMethodName; }
}
public string MethodName {
get { return result.MethodName; }
set { SetMethodName(value); }
}
public Builder SetMethodName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasMethodName = true;
result.methodName_ = value;
return this;
}
public Builder ClearMethodName() {
PrepareBuilder();
result.hasMethodName = false;
result.methodName_ = "";
return this;
}
}
static ManagementResponse() {
object.ReferenceEquals(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementResponse.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.PetstoreV2AllSync
{
using Models;
/// <summary>
/// This is a sample server Petstore server. You can find out more about
/// Swagger at <a
/// href="http://swagger.io">http://swagger.io</a> or on
/// irc.freenode.net, #swagger. For this sample, you can use the api key
/// "special-key" to test the authorization filters
/// </summary>
public partial interface ISwaggerPetstoreV2 : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(System.Collections.Generic.IList<string> status, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use
/// tag1, tag2, tag3 for testing.
/// </remarks>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(System.Collections.Generic.IList<string> tags, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10.
/// Other values will generated exceptions
/// </remarks>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything
/// above 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(System.Collections.Generic.IList<User> body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(System.Collections.Generic.IList<User> body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> LogoutUserWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
/*
* 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 CompareInfo = System.Globalization.CompareInfo;
using Term = Lucene.Net.Index.Term;
using TermEnum = Lucene.Net.Index.TermEnum;
using IndexReader = Lucene.Net.Index.IndexReader;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
namespace Lucene.Net.Search
{
/// <summary> A Query that matches documents within an exclusive range. A RangeQuery
/// is built by QueryParser for input like <code>[010 TO 120]</code> but only if the QueryParser has
/// the useOldRangeQuery property set to true. The QueryParser default behaviour is to use
/// the newer ConstantScoreRangeQuery class. This is generally preferable because:
/// <ul>
/// <li>It is faster than RangeQuery</li>
/// <li>Unlike RangeQuery, it does not cause a BooleanQuery.TooManyClauses exception if the range of values is large</li>
/// <li>Unlike RangeQuery it does not influence scoring based on the scarcity of individual terms that may match</li>
/// </ul>
///
///
/// </summary>
/// <seealso cref="ConstantScoreRangeQuery"/>
[Serializable]
public class RangeQuery : Query
{
private Term lowerTerm;
private Term upperTerm;
private bool inclusive;
private CompareInfo collator;
/// <summary>Constructs a query selecting all terms greater than
/// <code>lowerTerm</code> but less than <code>upperTerm</code>.
/// There must be at least one term and either term may be null,
/// in which case there is no bound on that side, but if there are
/// two terms, both terms <b>must</b> be for the same field.
/// </summary>
/// <param name="lowerTerm">term at the lower end of the range</param>
/// <param name="upperTerm">term at the upper end of the range</param>
/// <param name="inclusive">if true, both lowerTerm and upperTerm will be included in the range</param>
public RangeQuery(Term lowerTerm, Term upperTerm, bool inclusive)
{
if (lowerTerm == null && upperTerm == null)
{
throw new System.ArgumentException("At least one term must be non-null");
}
if (lowerTerm != null && upperTerm != null && lowerTerm.Field() != upperTerm.Field())
{
throw new System.ArgumentException("Both terms must be for the same field");
}
// if we have a lowerTerm, start there. otherwise, start at beginning
if (lowerTerm != null)
{
this.lowerTerm = lowerTerm;
}
else
{
this.lowerTerm = new Term(upperTerm.Field());
}
this.upperTerm = upperTerm;
this.inclusive = inclusive;
}
public RangeQuery(Term lowerTerm, Term upperTerm, bool inclusive, CompareInfo collator)
: this(lowerTerm, upperTerm, inclusive)
{
this.collator = collator;
}
public override Query Rewrite(IndexReader reader)
{
BooleanQuery query = new BooleanQuery(true);
string testField = GetField();
if (collator != null)
{
TermEnum enumerator = reader.Terms(new Term(testField, ""));
string lowerTermText = lowerTerm != null ? lowerTerm.Text() : null;
string upperTermText = upperTerm != null ? upperTerm.Text() : null;
try
{
do
{
Term term = enumerator.Term();
if (term != null && term.Field() == testField) // interned comparison
{
if ((lowerTermText == null ||
(inclusive ? collator.Compare(term.Text(), lowerTermText) >= 0 : collator.Compare(term.Text(), lowerTermText) > 0))
&&
(upperTermText == null ||
(inclusive ? collator.Compare(term.Text(), upperTermText) <= 0 : collator.Compare(term.Text(), upperTermText) < 0))
)
{
AddTermToQuery(term, query);
}
}
}
while (enumerator.Next());
}
finally
{
enumerator.Close();
}
}
else
{
TermEnum enumerator = reader.Terms(lowerTerm);
try
{
bool checkLower = false;
if (!inclusive)
// make adjustments to set to exclusive
checkLower = true;
do
{
Term term = enumerator.Term();
if (term != null && term.Field() == testField)
{
// interned comparison
if (!checkLower || String.CompareOrdinal(term.Text(), lowerTerm.Text()) > 0)
{
checkLower = false;
if (upperTerm != null)
{
int compare = String.CompareOrdinal(upperTerm.Text(), term.Text());
/* if beyond the upper term, or is exclusive and
* this is equal to the upper term, break out */
if ((compare < 0) || (!inclusive && compare == 0))
break;
}
AddTermToQuery(term, query); // Found a match
}
}
else
{
break;
}
}
while (enumerator.Next());
}
finally
{
enumerator.Close();
}
}
return query;
}
private void AddTermToQuery(Term term, BooleanQuery query)
{
TermQuery tq = new TermQuery(term); // found a match
tq.SetBoost(GetBoost()); // set the boost
query.Add(tq, BooleanClause.Occur.SHOULD); // add to query
}
/// <summary>Returns the field name for this query </summary>
public virtual System.String GetField()
{
return (lowerTerm != null ? lowerTerm.Field() : upperTerm.Field());
}
/// <summary>Returns the lower term of this range query </summary>
public virtual Term GetLowerTerm()
{
return lowerTerm;
}
/// <summary>Returns the upper term of this range query </summary>
public virtual Term GetUpperTerm()
{
return upperTerm;
}
/// <summary>Returns <code>true</code> if the range query is inclusive </summary>
public virtual bool IsInclusive()
{
return inclusive;
}
/// <summary>
/// Returns the collator used to determine range inclusion, if any.
/// </summary>
/// <returns></returns>
public CompareInfo GetCollator()
{
return collator;
}
/// <summary>Prints a user-readable version of this query. </summary>
public override System.String ToString(System.String field)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
if (!GetField().Equals(field))
{
buffer.Append(GetField());
buffer.Append(":");
}
buffer.Append(inclusive ? "[" : "{");
buffer.Append(lowerTerm != null ? lowerTerm.Text() : "null");
buffer.Append(" TO ");
buffer.Append(upperTerm != null ? upperTerm.Text() : "null");
buffer.Append(inclusive ? "]" : "}");
buffer.Append(ToStringUtils.Boost(GetBoost()));
return buffer.ToString();
}
/// <summary>Returns true iff <code>o</code> is equal to this. </summary>
public override bool Equals(object o)
{
if (this == o)
return true;
if (!(o is RangeQuery))
return false;
RangeQuery other = (RangeQuery) o;
if (this.GetBoost() != other.GetBoost())
return false;
if (this.inclusive != other.inclusive)
return false;
if (this.collator != null && !this.collator.Equals(other.collator))
return false;
// one of lowerTerm and upperTerm can be null
if (this.lowerTerm != null ? !this.lowerTerm.Equals(other.lowerTerm) : other.lowerTerm != null)
return false;
if (this.upperTerm != null ? !this.upperTerm.Equals(other.upperTerm) : other.upperTerm != null)
return false;
return true;
}
/// <summary>Returns a hash code value for this object.</summary>
public override int GetHashCode()
{
int h = BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0);
h ^= (lowerTerm != null ? lowerTerm.GetHashCode() : 0);
// reversible mix to make lower and upper position dependent and
// to prevent them from cancelling out.
h ^= ((h << 25) | (h >> 8));
h ^= (upperTerm != null ? upperTerm.GetHashCode() : 0);
h ^= (this.inclusive ? 0x2742E74A : 0);
h ^= collator != null ? collator.GetHashCode() : 0;
return h;
}
}
}
| |
//
// WindowFrame.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// WindowFrame.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.ComponentModel;
using Xwt.Drawing;
using Xwt.Motion;
namespace Xwt
{
[BackendType (typeof(IWindowFrameBackend))]
public class WindowFrame: XwtComponent, IAnimatable
{
EventHandler boundsChanged;
EventHandler shown;
EventHandler hidden;
CloseRequestedHandler closeRequested;
EventHandler closed;
Point location;
Size size;
bool pendingReallocation;
Image icon;
WindowFrame transientFor;
protected class WindowBackendHost: BackendHost<WindowFrame,IWindowFrameBackend>, IWindowFrameEventSink
{
protected override void OnBackendCreated ()
{
Backend.Initialize (this);
base.OnBackendCreated ();
Parent.location = Backend.Bounds.Location;
Parent.size = Backend.Bounds.Size;
Backend.EnableEvent (WindowFrameEvent.BoundsChanged);
}
public void OnBoundsChanged (Rectangle bounds)
{
Parent.OnBoundsChanged (new BoundsChangedEventArgs () { Bounds = bounds });
}
public virtual void OnShown ()
{
Parent.OnShown ();
}
public virtual void OnHidden ()
{
Parent.OnHidden ();
}
public virtual bool OnCloseRequested ()
{
return Parent.OnCloseRequested ();
}
public virtual void OnClosed ()
{
Parent.OnClosed ();
}
}
static WindowFrame ()
{
MapEvent (WindowFrameEvent.Shown, typeof(WindowFrame), "OnShown");
MapEvent (WindowFrameEvent.Hidden, typeof(WindowFrame), "OnHidden");
MapEvent (WindowFrameEvent.CloseRequested, typeof(WindowFrame), "OnCloseRequested");
MapEvent (WindowFrameEvent.Closed, typeof(WindowFrame), "OnClosed");
}
public WindowFrame ()
{
if (!(base.BackendHost is WindowBackendHost))
throw new InvalidOperationException ("CreateBackendHost for WindowFrame did not return a WindowBackendHost instance");
}
public WindowFrame (string title): this ()
{
Backend.Title = title;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
// Don't dispose the backend if this object is being finalized
// The backend has to handle the finalizing on its own
if (disposing && BackendHost.BackendCreated)
Backend.Dispose ();
}
IWindowFrameBackend Backend {
get { return (IWindowFrameBackend) BackendHost.Backend; }
}
protected override BackendHost CreateBackendHost ()
{
return new WindowBackendHost ();
}
protected new WindowBackendHost BackendHost {
get { return (WindowBackendHost) base.BackendHost; }
}
public Rectangle ScreenBounds {
get {
return BackendBounds;
}
set {
if (value.Width < 0)
value.Width = 0;
if (value.Height < 0)
value.Height = 0;
BackendBounds = value;
if (Visible)
AdjustSize ();
}
}
public double X {
get { return BackendBounds.X; }
set { SetBackendLocation (value, Y); }
}
public double Y {
get { return BackendBounds.Y; }
set { SetBackendLocation (X, value); }
}
public double Width {
get { return BackendBounds.Width; }
set {
if (value < 0)
value = 0;
SetBackendSize (value, -1);
if (Visible)
AdjustSize ();
}
}
public double Height {
get { return BackendBounds.Height; }
set {
if (value < 0)
value = 0;
SetBackendSize (-1, value);
if (Visible)
AdjustSize ();
}
}
/// <summary>
/// Size of the window, not including the decorations
/// </summary>
/// <value>The size.</value>
public Size Size {
get { return BackendBounds.Size; }
set {
if (value.Width < 0)
value.Width = 0;
if (value.Height < 0)
value.Height = 0;
SetBackendSize (value.Width, value.Height);
if (Visible)
AdjustSize ();
}
}
public Point Location {
get { return BackendBounds.Location; }
set { SetBackendLocation (value.X, value.Y); }
}
public string Title {
get { return Backend.Title; }
set { Backend.Title = value; }
}
public Image Icon {
get { return icon; }
set { icon = value; Backend.SetIcon (icon != null ? icon.ImageDescription : ImageDescription.Null); }
}
public bool Decorated {
get { return Backend.Decorated; }
set { Backend.Decorated = value; }
}
public bool ShowInTaskbar {
get { return Backend.ShowInTaskbar; }
set { Backend.ShowInTaskbar = value; }
}
public WindowFrame TransientFor {
get { return transientFor; }
set {
transientFor = value;
Backend.SetTransientFor ((IWindowFrameBackend)(value as IFrontend).Backend);
}
}
public bool Resizable {
get { return Backend.Resizable; }
set { Backend.Resizable = value; }
}
public bool Visible {
get { return Backend.Visible; }
set { Backend.Visible = value; }
}
public double Opacity {
get { return Backend.Opacity; }
set { Backend.Opacity = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this window is in full screen mode
/// </summary>
/// <value><c>true</c> if the window is in full screen mode; otherwise, <c>false</c>.</value>
public bool FullScreen {
get { return Backend.FullScreen; }
set { Backend.FullScreen = value; }
}
/// <summary>
/// Gets the screen on which most of the area of this window is placed
/// </summary>
/// <value>The screen.</value>
public Screen Screen {
get {
if (!Visible)
throw new InvalidOperationException ("The window is not visible");
return Desktop.GetScreen (Backend.Screen);
}
}
public void Show ()
{
if (!Visible) {
AdjustSize ();
Visible = true;
}
}
internal virtual void AdjustSize ()
{
}
/// <summary>
/// Presents a window to the user. This may mean raising the window in the stacking order,
/// deiconifying it, moving it to the current desktop, and/or giving it the keyboard focus
/// </summary>
public void Present ()
{
Backend.Present ();
}
protected virtual void OnShown ()
{
if(shown != null)
shown (this, EventArgs.Empty);
}
public void Hide ()
{
Visible = false;
}
protected virtual void OnHidden ()
{
if (hidden != null)
hidden (this, EventArgs.Empty);
}
/// <summary>
/// Closes the window
/// </summary>
/// <remarks>>
/// Closes the window like if the user clicked on the close window button.
/// The CloseRequested event is fired and subscribers can cancel the closing,
/// so there is no guarantee that the window will actually close.
/// This method doesn't dispose the window. The Dispose method has to be called.
/// </remarks>
public bool Close ()
{
return Backend.Close ();
}
/// <summary>
/// Called to check if the window can be closed
/// </summary>
/// <returns><c>true</c> if the window can be closed, <c>false</c> otherwise</returns>
protected virtual bool OnCloseRequested ()
{
if (closeRequested == null)
return true;
var eventArgs = new CloseRequestedEventArgs();
closeRequested (this, eventArgs);
return eventArgs.AllowClose;
}
/// <summary>
/// Called when the window has been closed by the user, or by a call to Close
/// </summary>
/// <remarks>
/// This method is not called when the window is disposed, only when explicitly closed (either by code or by the user)
/// </remarks>
protected virtual void OnClosed ()
{
if (closed != null)
closed (this, EventArgs.Empty);
}
internal virtual void SetBackendSize (double width, double height)
{
Backend.SetSize (width, height);
}
internal virtual void SetBackendLocation (double x, double y)
{
location = new Point (x, y);
Backend.Move (x, y);
}
internal virtual Rectangle BackendBounds {
get {
BackendHost.EnsureBackendLoaded ();
return new Rectangle (location, size);
}
set {
size = value.Size;
location = value.Location;
Backend.Bounds = value;
}
}
protected virtual void OnBoundsChanged (BoundsChangedEventArgs a)
{
var bounds = new Rectangle (location, size);
if (bounds != a.Bounds) {
size = a.Bounds.Size;
location = a.Bounds.Location;
Reallocate ();
if (boundsChanged != null)
boundsChanged (this, a);
}
}
internal void Reallocate ()
{
if (!pendingReallocation) {
pendingReallocation = true;
BackendHost.ToolkitEngine.QueueExitAction (delegate {
pendingReallocation = false;
OnReallocate ();
});
}
}
protected virtual void OnReallocate ()
{
}
void IAnimatable.BatchBegin ()
{
}
void IAnimatable.BatchCommit ()
{
}
public event EventHandler BoundsChanged {
add {
boundsChanged += value;
}
remove {
boundsChanged -= value;
}
}
public event EventHandler Shown {
add {
BackendHost.OnBeforeEventAdd (WindowFrameEvent.Shown, shown);
shown += value;
}
remove {
shown -= value;
BackendHost.OnAfterEventRemove (WindowFrameEvent.Shown, shown);
}
}
public event EventHandler Hidden {
add {
BackendHost.OnBeforeEventAdd (WindowFrameEvent.Hidden, hidden);
hidden += value;
}
remove {
hidden -= value;
BackendHost.OnAfterEventRemove (WindowFrameEvent.Hidden, hidden);
}
}
public event CloseRequestedHandler CloseRequested {
add {
BackendHost.OnBeforeEventAdd (WindowFrameEvent.CloseRequested, closeRequested);
closeRequested += value;
}
remove {
closeRequested -= value;
BackendHost.OnAfterEventRemove (WindowFrameEvent.CloseRequested, closeRequested);
}
}
/// <summary>
/// Raised when the window has been closed by the user, or by a call to Close
/// </summary>
/// <remarks>
/// This event is not raised when the window is disposed, only when explicitly closed (either by code or by the user)
/// </remarks>
public event EventHandler Closed {
add {
BackendHost.OnBeforeEventAdd (WindowFrameEvent.Closed, closed);
closed += value;
}
remove {
closed -= value;
BackendHost.OnAfterEventRemove (WindowFrameEvent.Closed, closed);
}
}
}
public class BoundsChangedEventArgs: EventArgs
{
public Rectangle Bounds { get; set; }
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Choice(Name = "AlternateAccessSelection")]
public class AlternateAccessSelection : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(AlternateAccessSelection));
private SelectAccessChoiceType selectAccess_;
private bool selectAccess_selected;
private SelectAlternateAccessSequenceType selectAlternateAccess_;
private bool selectAlternateAccess_selected;
[ASN1Element(Name = "selectAlternateAccess", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public SelectAlternateAccessSequenceType SelectAlternateAccess
{
get
{
return selectAlternateAccess_;
}
set
{
selectSelectAlternateAccess(value);
}
}
[ASN1Element(Name = "selectAccess", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public SelectAccessChoiceType SelectAccess
{
get
{
return selectAccess_;
}
set
{
selectSelectAccess(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isSelectAlternateAccessSelected()
{
return selectAlternateAccess_selected;
}
public void selectSelectAlternateAccess(SelectAlternateAccessSequenceType val)
{
selectAlternateAccess_ = val;
selectAlternateAccess_selected = true;
selectAccess_selected = false;
}
public bool isSelectAccessSelected()
{
return selectAccess_selected;
}
public void selectSelectAccess(SelectAccessChoiceType val)
{
selectAccess_ = val;
selectAccess_selected = true;
selectAlternateAccess_selected = false;
}
[ASN1PreparedElement]
[ASN1Choice(Name = "selectAccess")]
public class SelectAccessChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(SelectAccessChoiceType));
private NullObject allElements_;
private bool allElements_selected;
private Identifier component_;
private bool component_selected;
private IndexRangeSequenceType indexRange_;
private bool indexRange_selected;
private Unsigned32 index_;
private bool index_selected;
[ASN1Element(Name = "component", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public Identifier Component
{
get
{
return component_;
}
set
{
selectComponent(value);
}
}
[ASN1Element(Name = "index", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public Unsigned32 Index
{
get
{
return index_;
}
set
{
selectIndex(value);
}
}
[ASN1Element(Name = "indexRange", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public IndexRangeSequenceType IndexRange
{
get
{
return indexRange_;
}
set
{
selectIndexRange(value);
}
}
[ASN1Null(Name = "allElements")]
[ASN1Element(Name = "allElements", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public NullObject AllElements
{
get
{
return allElements_;
}
set
{
selectAllElements(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isComponentSelected()
{
return component_selected;
}
public void selectComponent(Identifier val)
{
component_ = val;
component_selected = true;
index_selected = false;
indexRange_selected = false;
allElements_selected = false;
}
public bool isIndexSelected()
{
return index_selected;
}
public void selectIndex(Unsigned32 val)
{
index_ = val;
index_selected = true;
component_selected = false;
indexRange_selected = false;
allElements_selected = false;
}
public bool isIndexRangeSelected()
{
return indexRange_selected;
}
public void selectIndexRange(IndexRangeSequenceType val)
{
indexRange_ = val;
indexRange_selected = true;
component_selected = false;
index_selected = false;
allElements_selected = false;
}
public bool isAllElementsSelected()
{
return allElements_selected;
}
public void selectAllElements()
{
selectAllElements(new NullObject());
}
public void selectAllElements(NullObject val)
{
allElements_ = val;
allElements_selected = true;
component_selected = false;
index_selected = false;
indexRange_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "indexRange", IsSet = false)]
public class IndexRangeSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(IndexRangeSequenceType));
private Unsigned32 lowIndex_;
private Unsigned32 numberOfElements_;
[ASN1Element(Name = "lowIndex", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Unsigned32 LowIndex
{
get
{
return lowIndex_;
}
set
{
lowIndex_ = value;
}
}
[ASN1Element(Name = "numberOfElements", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public Unsigned32 NumberOfElements
{
get
{
return numberOfElements_;
}
set
{
numberOfElements_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "selectAlternateAccess", IsSet = false)]
public class SelectAlternateAccessSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(SelectAlternateAccessSequenceType));
private AccessSelectionChoiceType accessSelection_;
private AlternateAccess alternateAccess_;
[ASN1Element(Name = "accessSelection", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public AccessSelectionChoiceType AccessSelection
{
get
{
return accessSelection_;
}
set
{
accessSelection_ = value;
}
}
[ASN1Element(Name = "alternateAccess", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public AlternateAccess AlternateAccess
{
get
{
return alternateAccess_;
}
set
{
alternateAccess_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "accessSelection")]
public class AccessSelectionChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(AccessSelectionChoiceType));
private NullObject allElements_;
private bool allElements_selected;
private Identifier component_;
private bool component_selected;
private IndexRangeSequenceType indexRange_;
private bool indexRange_selected;
private Unsigned32 index_;
private bool index_selected;
[ASN1Element(Name = "component", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Identifier Component
{
get
{
return component_;
}
set
{
selectComponent(value);
}
}
[ASN1Element(Name = "index", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public Unsigned32 Index
{
get
{
return index_;
}
set
{
selectIndex(value);
}
}
[ASN1Element(Name = "indexRange", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public IndexRangeSequenceType IndexRange
{
get
{
return indexRange_;
}
set
{
selectIndexRange(value);
}
}
[ASN1Null(Name = "allElements")]
[ASN1Element(Name = "allElements", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public NullObject AllElements
{
get
{
return allElements_;
}
set
{
selectAllElements(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isComponentSelected()
{
return component_selected;
}
public void selectComponent(Identifier val)
{
component_ = val;
component_selected = true;
index_selected = false;
indexRange_selected = false;
allElements_selected = false;
}
public bool isIndexSelected()
{
return index_selected;
}
public void selectIndex(Unsigned32 val)
{
index_ = val;
index_selected = true;
component_selected = false;
indexRange_selected = false;
allElements_selected = false;
}
public bool isIndexRangeSelected()
{
return indexRange_selected;
}
public void selectIndexRange(IndexRangeSequenceType val)
{
indexRange_ = val;
indexRange_selected = true;
component_selected = false;
index_selected = false;
allElements_selected = false;
}
public bool isAllElementsSelected()
{
return allElements_selected;
}
public void selectAllElements()
{
selectAllElements(new NullObject());
}
public void selectAllElements(NullObject val)
{
allElements_ = val;
allElements_selected = true;
component_selected = false;
index_selected = false;
indexRange_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "indexRange", IsSet = false)]
public class IndexRangeSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(IndexRangeSequenceType));
private Unsigned32 lowIndex_;
private Unsigned32 numberOfElements_;
[ASN1Element(Name = "lowIndex", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Unsigned32 LowIndex
{
get
{
return lowIndex_;
}
set
{
lowIndex_ = value;
}
}
[ASN1Element(Name = "numberOfElements", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public Unsigned32 NumberOfElements
{
get
{
return numberOfElements_;
}
set
{
numberOfElements_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
}
}
}
| |
using System;
using Xunit;
using Medo.Math;
namespace Tests.Medo.Math {
public class WeightedMovingAverageTests {
[Fact(DisplayName = "WeightedMovingAverage: Example (1)")]
public void Example1() {
var stats = new WeightedMovingAverage();
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(12.1, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (2)")]
public void Example2() {
var stats = new WeightedMovingAverage();
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000012.1, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (3)")]
public void Example3() {
var stats = new WeightedMovingAverage();
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000012.1000001, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (4)")]
public void Example4() {
var stats = new WeightedMovingAverage();
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(2.3, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (5)")]
public void Example5() {
var stats = new WeightedMovingAverage(new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(4.9, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (6)")]
public void Example6() {
var stats = new WeightedMovingAverage();
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(5.944444444444445, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (7)")]
public void Example7() {
var stats = new WeightedMovingAverage();
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(6.963636363636364, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (8)")]
public void Example8() {
var stats = new WeightedMovingAverage();
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(52.02, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (9)")]
public void Example9() {
var stats = new WeightedMovingAverage();
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(0.333333333333333, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (10)")]
public void Example10() {
var stats = new WeightedMovingAverage();
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(0.333333333333333, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (11)")]
public void Example11() {
var stats = new WeightedMovingAverage(3);
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(13.5, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (12)")]
public void Example12() {
var stats = new WeightedMovingAverage(3);
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000013.5, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (13)")]
public void Example13() {
var stats = new WeightedMovingAverage(3);
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000013.5, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (14)")]
public void Example14() {
var stats = new WeightedMovingAverage(3);
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(1.833333333333333, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (15)")]
public void Example15() {
var stats = new WeightedMovingAverage(3, new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(5.5, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (16)")]
public void Example16() {
var stats = new WeightedMovingAverage(3);
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(7.666666666666667, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (17)")]
public void Example17() {
var stats = new WeightedMovingAverage(3);
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(6, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (18)")]
public void Example18() {
var stats = new WeightedMovingAverage(3);
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(51.9, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (19)")]
public void Example19() {
var stats = new WeightedMovingAverage(3);
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(1.666666666666667, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: Example (20)")]
public void Example20() {
var stats = new WeightedMovingAverage(3);
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(0.333333333333333, stats.Average, 15);
}
[Fact(DisplayName = "WeightedMovingAverage: No values")]
public void NoValue() {
var stats = new WeightedMovingAverage();
Assert.Equal(0, stats.Count);
Assert.Equal(double.NaN, stats.Average);
}
[Fact(DisplayName = "WeightedMovingAverage: One value")]
public void OneValue() {
var stats = new WeightedMovingAverage();
stats.Add(1);
Assert.Equal(1, stats.Count);
Assert.Equal(1, stats.Average);
}
[Fact(DisplayName = "WeightedMovingAverage: No infinities")]
public void NoInfinity() {
var stats = new WeightedMovingAverage();
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.NegativeInfinity);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.PositiveInfinity);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.NaN);
});
}
[Fact(DisplayName = "WeightedMovingAverage: No null collection")]
public void NoNullCollection() {
Assert.Throws<ArgumentNullException>(delegate {
var stats = new WeightedMovingAverage(null);
});
Assert.Throws<ArgumentNullException>(delegate {
var stats = new WeightedMovingAverage(10, null);
});
Assert.Throws<ArgumentNullException>(delegate {
var stats = new WeightedMovingAverage();
stats.AddRange(null);
});
}
[Fact(DisplayName = "WeightedMovingAverage: No count out of range")]
public void NoCountOutOfRange() {
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new WeightedMovingAverage(0);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new WeightedMovingAverage(0, new double[] { 0 });
});
}
}
}
| |
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 WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions;
using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models;
namespace WebAPI_NG_TokenbasedAuth.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);
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
namespace Alachisoft.NCache.Common
{
public class MemoryUtil
{
public const int KB = 1024;
//24 Bytes overhead for every .net class in x64
public const int NetOverHead = 24;
public const int NetHashtableOverHead = 45;
public const int NetListOverHead = 8;
public const int NetClassOverHead = 16;
public const int NetIntSize = 4;
public const int NetEnumSize = 4;
public const int NetByteSize = 1;
public const int NetShortSize = 2;
public const int NetStringCharSize = 16;
public const int NetLongSize = 8;
public const int NetDateTimeSize = 8;
public const int NetReferenceSize = 8;
#region Dot Net Primitive Tyes String Constants
public const String Net_bool = "bool";
public const String Net_System_Boolean = "System.Boolean";
public const String Net_char = "char";
public const String Net_System_Char = "System.Char";
public const String Net_string = "string";
public const String Net_System_String = "System.String";
public const String Net_float = "float";
public const String Net_System_Single = "System.Single";
public const String Net_double = "double";
public const String Net_System_Double = "System.Double";
public const String Net_short = "short";
public const String Net_ushort = "ushort";
public const String Net_System_Int16 = "System.Int16";
public const String Net_System_UInt16 = "System.UInt16";
public const String Net_int = "int";
public const String Net_System_Int32 = "System.Int32";
public const String Net_uint = "uint";
public const String Net_System_UInt32 = "System.UInt32";
public const String Net_long = "long";
public const String Net_System_Int64 = "System.Int64";
public const String Net_ulong = "ulong";
public const String Net_SystemUInt64 = "System.UInt64";
public const String Net_byte = "byte";
public const String Net_System_Byte = "System.Byte";
public const String Net_sbyte = "sbyte";
public const String Net_System_SByte = "System.SByte";
public const String Net_System_Object = "System.Object";
public const String Net_System_DateTime = "System.DateTime";
public const String Net_decimal = "decimal";
public const String Net_System_Decimal = "System.Decimal";
#endregion
#region Java Primitive Types String Constants
public const String Java_Lang_Boolean = "java.lang.Boolean";// True/false value
public const String Java_Lang_Character = "java.lang.Character";// Unicode character (16 bit;
public const String Java_Lang_String = "java.lang.String";// Unicode String
public const String Java_Lang_Float = "java.lang.Float";// IEEE 32-bit float
public const String Java_Lang_Double = "java.lang.Double";// IEEE 64-bit float
public const String Java_Lang_Short = "java.lang.Short";// Signed 16-bit integer
public const String Java_Lang_Integer = "java.lang.Integer";// Signed 32-bit integer
public const String Java_Lang_Long = "java.lang.Long";// Signed 32-bit integer
public const String Java_Lang_Byte = "java.lang.Byte";// Unsigned 8-bit integer
public const String Java_Lang_Object = "java.lang.Object";// Base class for all objects
public const String Java_Util_Date = "java.util.Date";// Dates will always be serialized (passed by value); according to .NET Remoting
public const String Java_Match_BigDecimal = "java.math.BigDecimal";// Will always be serialized (passed by value); according to .NET Remoting
#endregion
/// <summary>
/// Hashcode algorithm returning same hash code for both 32bit and 64 bit apps.
/// Used for data distribution under por/partitioned topologies.
/// </summary>
/// <param name="strArg"></param>
/// <returns></returns>
public static int GetStringSize(object key)
{
if (key != null && key is String)
{
//size of .net charater is 2 bytes so multiply by 2 length of key, 24 bytes are extra overhead(header) of each instance
return (2 * ((String)key).Length) + Common.MemoryUtil.NetOverHead;
}
return 0;
}
/// <summary>
/// Returns memory occupied in bytes by string instance without .NET overhead.
/// </summary>
/// <param name="arg">String value whose size without .NET overhead is to be determined.</param>
/// <returns>Integer representing size of string instance without .NET overhead. 0 value corresponds to null or non-string argument.</returns>
public static int GetStringSizeWithoutNetOverhead(object arg)
{
if (arg != null && arg is String)
{
//size of .net charater is 2 bytes so multiply by 2 length of key
return (2 * ((String)arg).Length);
}
return 0;
}
/// <summary>
/// Hashcode algorithm returning same hash code for both 32bit and 64 bit apps.
/// Used for data distribution under por/partitioned topologies.
/// </summary>
/// <param name="strArg"></param>
/// <returns></returns>
public static int GetStringSize(object[] keys)
{
int totalSize = 0;
if (keys != null)
{
foreach (object key in keys)
{
//size of .net charater is 2 bytes so multiply by 2 length of key, 24 bytes are extra overhead(header) of each instance
totalSize += (2 * ((String)key).Length) + Common.MemoryUtil.NetOverHead;
}
}
return totalSize;
}
/// <summary>
/// Used to get DataType Size for provided AttributeSize.
/// </summary>
/// <param name="strArg"></param>
/// <returns></returns>
public static int GetTypeSize(AttributeTypeSize type)
{
switch(type)
{
case AttributeTypeSize.Byte1:
return 1;
case AttributeTypeSize.Byte2:
return 2;
case AttributeTypeSize.Byte4:
return 4;
case AttributeTypeSize.Byte8:
return 8;
case AttributeTypeSize.Byte16:
return 16;
}
return 0;
}
public static AttributeTypeSize GetAttributeTypeSize(String type)
{
switch (type)
{
case Net_bool:
case Net_byte:
case Net_System_Byte:
case Net_sbyte:
case Net_System_SByte:
case Net_System_Boolean:
case Java_Lang_Boolean:
case Java_Lang_Byte: return AttributeTypeSize.Byte1;
case Net_char:
case Net_short:
case Net_ushort:
case Net_System_Int16:
case Net_System_UInt16:
case Net_System_Char:
case Java_Lang_Character:
case Java_Lang_Float:
case Java_Lang_Short: return AttributeTypeSize.Byte2;
case Net_float:
case Net_int:
case Net_System_Int32:
case Net_uint:
case Net_System_UInt32:
case Net_System_Single:
case Java_Lang_Integer: return AttributeTypeSize.Byte4;
case Net_double:
case Net_System_Double:
case Net_long:
case Net_System_Int64:
case Net_ulong:
case Net_System_DateTime:
case Net_SystemUInt64:
case Java_Lang_Double:
case Java_Lang_Long:
case Java_Util_Date: return AttributeTypeSize.Byte8;
case Net_decimal:
case Net_System_Decimal:
case Java_Match_BigDecimal: return AttributeTypeSize.Byte16;
}
return AttributeTypeSize.Variable ;
}
public static Type GetDataType(string typeName)
{
switch (typeName)
{
case Net_string: return typeof(string);
case Net_System_String: return typeof(System.String);
case Java_Lang_String: return typeof(string);
case Net_bool: return typeof(bool);
case Net_byte: return typeof(byte);
case Net_System_Byte: return typeof(Byte);
case Net_sbyte: return typeof(sbyte);
case Net_System_SByte: return typeof(SByte);
case Net_System_Boolean: return typeof(Boolean);
case Java_Lang_Boolean: return typeof(Boolean);
case Java_Lang_Byte: return typeof(Byte);
case Net_char: return typeof(char);
case Net_short: return typeof(short);
case Net_ushort: return typeof(ushort);
case Net_System_Int16: return typeof(Int16);
case Net_System_UInt16: return typeof(UInt16);
case Net_System_Char: return typeof(Char);
case Java_Lang_Character: return typeof(Char);
case Java_Lang_Float: return typeof(float);
case Java_Lang_Short: return typeof(short);
case Net_float: return typeof(float);
case Net_int: return typeof(int);
case Net_System_Int32: return typeof(Int32);
case Net_uint: return typeof(uint);
case Net_System_UInt32: return typeof(UInt32);
case Net_System_Single: return typeof(Single);
case Java_Lang_Integer: return typeof(int);
case Net_double: return typeof(double);
case Net_System_Double: return typeof(Double);
case Net_long: return typeof(long);
case Net_System_Int64: return typeof(Int64);
case Net_ulong: return typeof(ulong);
case Net_System_DateTime: return typeof(DateTime);
case Net_SystemUInt64: return typeof(UInt64);
case Java_Lang_Double: return typeof(Double);
case Java_Lang_Long: return typeof(long);
case Java_Util_Date: return typeof(DateTime);
case Net_decimal: return typeof(decimal);
case Net_System_Decimal: return typeof(Decimal);
case Java_Match_BigDecimal: return typeof(Decimal);
default: return null;
}
}
public static int GetInMemoryInstanceSize(int actualDataBytes)
{
int temp = MemoryUtil.NetClassOverHead;
ushort remainder = (ushort)(actualDataBytes & 7);
if (remainder != 0)
remainder = (ushort)(8 - remainder);
temp += actualDataBytes + remainder;
return temp;
}
public static long GetInMemoryInstanceSize(long actualDataBytes)
{
long temp = MemoryUtil.NetClassOverHead;
ushort remainder = (ushort)(actualDataBytes & 7);
if (remainder != 0)
remainder = (ushort)(8 - remainder);
temp += actualDataBytes + remainder;
return temp;
}
public static ArraySegment<TReturn>[] GetArraySegments<TReturn>(IList list)
{
ArraySegment<TReturn>[] segments = new ArraySegment<TReturn>[list.Count];
for (int i = 0; i < list.Count; i++)
{
TReturn[] array = (TReturn[])list[i];
segments[i] = new ArraySegment<TReturn>(array);
}
return segments;
}
/// <summary>
/// Returns .Net's LOH safe generic collection count...
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static int GetSafeCollectionCount<T>(long length)
{
Type genericType = typeof (T);
int sizeOfReference;
if (genericType.IsValueType){
sizeOfReference = System.Runtime.InteropServices.Marshal.SizeOf(genericType);
}
else
{
sizeOfReference = IntPtr.Size;
}
int safeLength = (81920 / sizeOfReference);
return ((length > safeLength) ? safeLength : (int)length);
}
/// <summary>
/// Returns .Net's LOH safe generic collection count...
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static int GetSafeByteCollectionCount(long length)
{
return ((length > 81920) ? 81920 : (int)length);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BunniesCraft.Services.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);
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
using NLog.Internal.Fakeables;
using System.Reflection;
#if SILVERLIGHT && !__IOS__ && !__ANDROID__
using System.Windows;
#endif
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public class LogFactory : IDisposable
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private const int ReconfigAfterFileChangedTimeout = 1000;
private Timer reloadTimer;
private readonly MultiFileWatcher watcher;
#endif
private static TimeSpan defaultFlushTimeout = TimeSpan.FromSeconds(15);
private static IAppDomain currentAppDomain;
private readonly object syncRoot = new object();
private LoggingConfiguration config;
private LogLevel globalThreshold = LogLevel.MinLevel;
private bool configLoaded;
// TODO: logsEnabled property might be possible to be encapsulated into LogFactory.LogsEnabler class.
private int logsEnabled;
private readonly LoggerCache loggerCache = new LoggerCache();
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
public LogFactory()
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
this.watcher = new MultiFileWatcher();
this.watcher.OnChange += this.ConfigFileChanged;
CurrentAppDomain.DomainUnload += currentAppDomain_DomainUnload;
#endif
}
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
/// <param name="config">The config.</param>
public LogFactory(LoggingConfiguration config)
: this()
{
this.Configuration = config;
}
/// <summary>
/// Gets the current <see cref="IAppDomain"/>.
/// </summary>
public static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set { currentAppDomain = value; }
}
/// <summary>
/// Gets or sets a value indicating whether exceptions should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>By default exceptions are not thrown under any circumstances.</remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets or sets the current logging configuration. After setting this property all
/// existing loggers will be re-configured, so that there is no need to call <see cref="ReconfigExistingLoggers" />
/// manually.
/// </summary>
public LoggingConfiguration Configuration
{
get
{
lock (this.syncRoot)
{
if (this.configLoaded)
{
return this.config;
}
this.configLoaded = true;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (this.config == null)
{
// Try to load default configuration.
this.config = XmlLoggingConfiguration.AppConfig;
}
#endif
// Retest the condition as we might have loaded a config.
if (this.config == null)
{
foreach (string configFile in GetCandidateConfigFileNames())
{
#if SILVERLIGHT
Uri configFileUri = new Uri(configFile, UriKind.Relative);
if (Application.GetResourceStream(configFileUri) != null)
{
LoadLoggingConfiguration(configFile);
break;
}
#else
if (File.Exists(configFile))
{
LoadLoggingConfiguration(configFile);
break;
}
#endif
}
}
if (this.config != null)
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
config.Dump();
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Warn(exception, "Cannot start file watching. File watching is disabled");
//TODO NLog 5: check "MustBeRethrown"
}
#endif
this.config.InitializeAll();
LogConfigurationInitialized();
}
return this.config;
}
}
set
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
try
{
this.watcher.StopWatching();
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Cannot stop file watching.");
if (exception.MustBeRethrown())
{
throw;
}
}
#endif
lock (this.syncRoot)
{
LoggingConfiguration oldConfig = this.config;
if (oldConfig != null)
{
InternalLogger.Info("Closing old configuration.");
#if !SILVERLIGHT
this.Flush();
#endif
oldConfig.Close();
}
this.config = value;
this.configLoaded = true;
if (this.config != null)
{
config.Dump();
this.config.InitializeAll();
this.ReconfigExistingLoggers();
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
//ToArray needed for .Net 3.5
InternalLogger.Warn(exception, "Cannot start file watching: {0}", string.Join(",", this.config.FileNamesToWatch.ToArray()));
if (exception.MustBeRethrown())
{
throw;
}
}
#endif
}
this.OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, oldConfig));
}
}
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public LogLevel GlobalThreshold
{
get
{
return this.globalThreshold;
}
set
{
lock (this.syncRoot)
{
this.globalThreshold = value;
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Gets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>.
/// </summary>
/// <value>
/// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/>
/// </value>
[CanBeNull]
public CultureInfo DefaultCultureInfo
{
get
{
var configuration = this.Configuration;
return configuration != null ? configuration.DefaultCultureInfo : null;
}
}
private void LogConfigurationInitialized()
{
InternalLogger.Info("Configuration initialized.");
InternalLogger.LogAssemblyVersion(typeof(ILogger).Assembly);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting
/// unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger instance.</returns>
public Logger CreateNullLogger()
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
Logger newLogger = new Logger();
newLogger.Initialize(string.Empty, new LoggerConfiguration(targetsByLevel, false), this);
return newLogger;
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
var frame = new StackFrame(1);
#else
var frame = new StackFrame(1, false);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The type of the logger to create. The type must inherit from
/// NLog.Logger.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method. Make sure you are not calling this method in a
/// loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger(Type loggerType)
{
#if !SILVERLIGHT
var frame = new StackFrame(1, false);
#else
var frame = new StackFrame(1);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName, loggerType);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument
/// are not guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name)
{
return this.GetLogger(new LoggerCacheKey(name, typeof(Logger)));
}
/// <summary>
/// Gets the specified named logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The type of the logger to create. The type must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the
/// same argument aren't guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name, Type loggerType)
{
return this.GetLogger(new LoggerCacheKey(name, loggerType));
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger and recalculates their
/// target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public void ReconfigExistingLoggers()
{
if (this.config != null)
{
this.config.InitializeAll();
}
//new list to avoid "Collection was modified; enumeration operation may not execute"
var loggers = new List<Logger>(loggerCache.Loggers);
foreach (var logger in loggers)
{
logger.SetConfiguration(this.GetConfigurationForLogger(logger.Name, this.config));
}
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public void Flush()
{
this.Flush(defaultFlushTimeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time
/// will be discarded.</param>
public void Flush(TimeSpan timeout)
{
try
{
AsyncHelpers.RunSynchronously(cb => this.Flush(cb, timeout));
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error with flush.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(int timeoutMilliseconds)
{
this.Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
this.Flush(asyncContinuation, TimeSpan.MaxValue);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
this.Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
try
{
InternalLogger.Trace("LogFactory.Flush({0})", timeout);
var loggingConfiguration = this.Configuration;
if (loggingConfiguration != null)
{
InternalLogger.Trace("Flushing all targets...");
loggingConfiguration.FlushAllTargets(AsyncHelpers.WithTimeout(asyncContinuation, timeout));
}
else
{
asyncContinuation(null);
}
}
catch (Exception ex)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(ex, "Error with flush.");
}
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
[Obsolete("Use SuspendLogging() instead.")]
public IDisposable DisableLogging()
{
return SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.</remarks>
[Obsolete("Use ResumeLogging() instead.")]
public void EnableLogging()
{
ResumeLogging();
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public IDisposable SuspendLogging()
{
lock (this.syncRoot)
{
this.logsEnabled--;
if (this.logsEnabled == -1)
{
this.ReconfigExistingLoggers();
}
}
return new LogEnabler(this);
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public void ResumeLogging()
{
lock (this.syncRoot)
{
this.logsEnabled++;
if (this.logsEnabled == 0)
{
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public bool IsLoggingEnabled()
{
return this.logsEnabled >= 0;
}
/// <summary>
/// Invoke the Changed event; called whenever list changes
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e)
{
var changed = this.ConfigurationChanged;
if (changed != null)
{
changed(this, e);
}
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
internal void ReloadConfigOnTimer(object state)
{
LoggingConfiguration configurationToReload = (LoggingConfiguration)state;
InternalLogger.Info("Reloading configuration...");
lock (this.syncRoot)
{
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
if (IsDisposing)
{
//timer was disposed already.
this.watcher.Dispose();
return;
}
this.watcher.StopWatching();
try
{
if (this.Configuration != configurationToReload)
{
throw new NLogConfigurationException("Config changed in between. Not reloading.");
}
LoggingConfiguration newConfig = configurationToReload.Reload();
//problem: XmlLoggingConfiguration.Initialize eats exception with invalid XML. ALso XmlLoggingConfiguration.Reload never returns null.
//therefor we check the InitializeSucceeded property.
var xmlConfig = newConfig as XmlLoggingConfiguration;
if (xmlConfig != null)
{
if (!xmlConfig.InitializeSucceeded.HasValue || !xmlConfig.InitializeSucceeded.Value)
{
throw new NLogConfigurationException("Configuration.Reload() failed. Invalid XML?");
}
}
if (newConfig != null)
{
this.Configuration = newConfig;
if (this.ConfigurationReloaded != null)
{
this.ConfigurationReloaded(this, new LoggingConfigurationReloadedEventArgs(true, null));
}
}
else
{
throw new NLogConfigurationException("Configuration.Reload() returned null. Not reloading.");
}
}
catch (Exception exception)
{
//special case, don't rethrow NLogConfigurationException
if (exception is NLogConfigurationException)
{
InternalLogger.Warn(exception, "NLog configuration while reloading");
}
else if (exception.MustBeRethrown())
{
throw;
}
this.watcher.Watch(configurationToReload.FileNamesToWatch);
var configurationReloadedDelegate = this.ConfigurationReloaded;
if (configurationReloadedDelegate != null)
{
configurationReloadedDelegate(this, new LoggingConfigurationReloadedEventArgs(false, exception));
}
}
}
}
#endif
private void GetTargetsByLevelForLogger(string name, IEnumerable<LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels)
{
//no "System.InvalidOperationException: Collection was modified"
var loggingRules = new List<LoggingRule>(rules);
foreach (LoggingRule rule in loggingRules)
{
if (!rule.NameMatches(name))
{
continue;
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (i < this.GlobalThreshold.Ordinal || suppressedLevels[i] || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
{
continue;
}
if (rule.Final)
suppressedLevels[i] = true;
foreach (Target target in rule.Targets.ToList())
{
var awf = new TargetWithFilterChain(target, rule.Filters);
if (lastTargetsByLevel[i] != null)
{
lastTargetsByLevel[i].NextInChain = awf;
}
else
{
targetsByLevel[i] = awf;
}
lastTargetsByLevel[i] = awf;
}
}
// Recursively analyze the child rules.
this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
TargetWithFilterChain tfc = targetsByLevel[i];
if (tfc != null)
{
tfc.PrecalculateStackTraceUsage();
}
}
}
internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration)
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];
if (configuration != null && this.IsLoggingEnabled())
{
this.GetTargetsByLevelForLogger(name, configuration.LoggingRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
InternalLogger.Debug("Targets for {0} by level:", name);
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
if (afc.FilterChain.Count > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
}
}
InternalLogger.Debug(sb.ToString());
}
#pragma warning disable 618
return new LoggerConfiguration(targetsByLevel, configuration != null && configuration.ExceptionLoggingOldStyle);
#pragma warning restore 618
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>True</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (disposing)
{
this.watcher.Dispose();
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
}
#endif
}
private static IEnumerable<string> GetCandidateConfigFileNames()
{
#if SILVERLIGHT
yield return "NLog.config";
#else
// NLog.config from application directory
if (CurrentAppDomain.BaseDirectory != null)
{
yield return Path.Combine(CurrentAppDomain.BaseDirectory, "NLog.config");
}
// Current config file with .config renamed to .nlog
string cf = CurrentAppDomain.ConfigurationFile;
if (cf != null)
{
yield return Path.ChangeExtension(cf, ".nlog");
// .nlog file based on the non-vshost version of the current config file
const string vshostSubStr = ".vshost.";
if (cf.Contains(vshostSubStr))
{
yield return Path.ChangeExtension(cf.Replace(vshostSubStr, "."), ".nlog");
}
IEnumerable<string> privateBinPaths = CurrentAppDomain.PrivateBinPath;
if (privateBinPaths != null)
{
foreach (var path in privateBinPaths)
{
if (path != null)
{
yield return Path.Combine(path, "NLog.config");
}
}
}
}
// Get path to NLog.dll.nlog only if the assembly is not in the GAC
var nlogAssembly = typeof(LogFactory).Assembly;
if (!nlogAssembly.GlobalAssemblyCache)
{
if (!string.IsNullOrEmpty(nlogAssembly.Location))
{
yield return nlogAssembly.Location + ".nlog";
}
}
#endif
}
private Logger GetLogger(LoggerCacheKey cacheKey)
{
lock (this.syncRoot)
{
Logger existingLogger = loggerCache.Retrieve(cacheKey);
if (existingLogger != null)
{
// Logger is still in cache and referenced.
return existingLogger;
}
Logger newLogger;
if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger))
{
var fullName = cacheKey.ConcreteType.FullName;
try
{
//creating instance of static class isn't possible, and also not wanted (it cannot inherited from Logger)
if (cacheKey.ConcreteType.IsStaticClass())
{
var errorMessage = string.Format("GetLogger / GetCurrentClassLogger is '{0}' as loggerType can be a static class and should inherit from Logger",
fullName);
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
throw new NLogRuntimeException(errorMessage);
}
newLogger = CreateDefaultLogger(ref cacheKey);
}
else
{
var instance = FactoryHelper.CreateInstance(cacheKey.ConcreteType);
newLogger = instance as Logger;
if (newLogger == null)
{
//well, it's not a Logger, and we should return a Logger.
var errorMessage = string.Format("GetLogger / GetCurrentClassLogger got '{0}' as loggerType which doesn't inherit from Logger", fullName);
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
throw new NLogRuntimeException(errorMessage);
}
// Creating default instance of logger if instance of specified type cannot be created.
newLogger = CreateDefaultLogger(ref cacheKey);
}
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, "GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default contructor. ", fullName);
if (ex.MustBeRethrown())
{
throw;
}
// Creating default instance of logger if instance of specified type cannot be created.
newLogger = CreateDefaultLogger(ref cacheKey);
}
}
else
{
newLogger = new Logger();
}
if (cacheKey.ConcreteType != null)
{
newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this);
}
// TODO: Clarify what is the intention when cacheKey.ConcreteType = null.
// At the moment, a logger typeof(Logger) will be created but the ConcreteType
// will remain null and inserted into the cache.
// Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers?
loggerCache.InsertOrUpdate(cacheKey, newLogger);
return newLogger;
}
}
private static Logger CreateDefaultLogger(ref LoggerCacheKey cacheKey)
{
cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger));
var newLogger = new Logger();
return newLogger;
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private void ConfigFileChanged(object sender, EventArgs args)
{
InternalLogger.Info("Configuration file change detected! Reloading in {0}ms...", LogFactory.ReconfigAfterFileChangedTimeout);
// In the rare cases we may get multiple notifications here,
// but we need to reload config only once.
//
// The trick is to schedule the reload in one second after
// the last change notification comes in.
lock (this.syncRoot)
{
if (this.reloadTimer == null)
{
this.reloadTimer = new Timer(
this.ReloadConfigOnTimer,
this.Configuration,
LogFactory.ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
else
{
this.reloadTimer.Change(
LogFactory.ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
}
}
#endif
private void LoadLoggingConfiguration(string configFile)
{
InternalLogger.Debug("Loading config from {0}", configFile);
this.config = new XmlLoggingConfiguration(configFile);
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Currenty this logfactory is disposing?
/// </summary>
private bool IsDisposing;
private void currentAppDomain_DomainUnload(object sender, EventArgs e)
{
//stop timer on domain unload, otherwise:
//Exception: System.AppDomainUnloadedException
//Message: Attempted to access an unloaded AppDomain.
lock (this.syncRoot)
{
IsDisposing = true;
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
}
}
#endif
/// <summary>
/// Logger cache key.
/// </summary>
internal class LoggerCacheKey : IEquatable<LoggerCacheKey>
{
public string Name { get; private set; }
public Type ConcreteType { get; private set; }
public LoggerCacheKey(string name, Type concreteType)
{
this.Name = name;
this.ConcreteType = concreteType;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return this.ConcreteType.GetHashCode() ^ this.Name.GetHashCode();
}
/// <summary>
/// Determines if two objects are equal in value.
/// </summary>
/// <param name="obj">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
LoggerCacheKey key = obj as LoggerCacheKey;
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
/// <summary>
/// Determines if two objects of the same type are equal in value.
/// </summary>
/// <param name="key">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public bool Equals(LoggerCacheKey key)
{
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
}
/// <summary>
/// Logger cache.
/// </summary>
private class LoggerCache
{
// The values of WeakReferences are of type Logger i.e. Directory<LoggerCacheKey, Logger>.
private readonly Dictionary<LoggerCacheKey, WeakReference> loggerCache =
new Dictionary<LoggerCacheKey, WeakReference>();
/// <summary>
/// Inserts or updates.
/// </summary>
/// <param name="cacheKey"></param>
/// <param name="logger"></param>
public void InsertOrUpdate(LoggerCacheKey cacheKey, Logger logger)
{
loggerCache[cacheKey] = new WeakReference(logger);
}
public Logger Retrieve(LoggerCacheKey cacheKey)
{
WeakReference loggerReference;
if (loggerCache.TryGetValue(cacheKey, out loggerReference))
{
// logger in the cache and still referenced
return loggerReference.Target as Logger;
}
return null;
}
public IEnumerable<Logger> Loggers
{
get { return GetLoggers(); }
}
private IEnumerable<Logger> GetLoggers()
{
// TODO: Test if loggerCache.Values.ToList<Logger>() can be used for the conversion instead.
List<Logger> values = new List<Logger>(loggerCache.Count);
foreach (WeakReference loggerReference in loggerCache.Values)
{
Logger logger = loggerReference.Target as Logger;
if (logger != null)
{
values.Add(logger);
}
}
return values;
}
}
/// <summary>
/// Enables logging in <see cref="IDisposable.Dispose"/> implementation.
/// </summary>
private class LogEnabler : IDisposable
{
private LogFactory factory;
/// <summary>
/// Initializes a new instance of the <see cref="LogEnabler" /> class.
/// </summary>
/// <param name="factory">The factory.</param>
public LogEnabler(LogFactory factory)
{
this.factory = factory;
}
/// <summary>
/// Enables logging.
/// </summary>
void IDisposable.Dispose()
{
this.factory.ResumeLogging();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.