context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// ReSharper disable UnusedParameter.Local
// ReSharper disable UnusedMember.Global
// ReSharper disable EmptyConstructor
namespace Gu.Inject.Benchmarks.Types
{
using System.Collections.Generic;
using System.Linq;
public static class Graph50
{
public class Node1 : INode
{
public Node1(
Node2 node2,
Node7 node7,
Node10 node10,
Node16 node16,
Node18 node18,
Node24 node24,
Node26 node26,
Node27 node27,
Node29 node29,
Node32 node32)
{
this.Children = new INode[]
{
node2,
node7,
node10,
node16,
node18,
node24,
node26,
node27,
node29,
node32,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node2 : INode
{
public Node2(
Node4 node4,
Node8 node8,
Node16 node16,
Node48 node48)
{
this.Children = new INode[]
{
node4,
node8,
node16,
node48,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node3 : INode
{
public Node3(
Node33 node33)
{
this.Children = new INode[]
{
node33,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node4 : INode
{
public Node4(
Node8 node8,
Node32 node32,
Node36 node36)
{
this.Children = new INode[]
{
node8,
node32,
node36,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node5 : INode
{
public Node5(
Node30 node30)
{
this.Children = new INode[]
{
node30,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node6 : INode
{
public Node6(
Node18 node18,
Node30 node30)
{
this.Children = new INode[]
{
node18,
node30,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node7 : INode
{
public Node7(
Node35 node35,
Node49 node49)
{
this.Children = new INode[]
{
node35,
node49,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node8 : INode
{
public Node8()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node9 : INode
{
public Node9(
Node18 node18)
{
this.Children = new INode[]
{
node18,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node10 : INode
{
public Node10()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node11 : INode
{
public Node11(
Node22 node22)
{
this.Children = new INode[]
{
node22,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node12 : INode
{
public Node12(
Node24 node24,
Node48 node48)
{
this.Children = new INode[]
{
node24,
node48,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node13 : INode
{
public Node13(
Node39 node39)
{
this.Children = new INode[]
{
node39,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node14 : INode
{
public Node14(
Node28 node28)
{
this.Children = new INode[]
{
node28,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node15 : INode
{
public Node15(
Node30 node30)
{
this.Children = new INode[]
{
node30,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node16 : INode
{
public Node16()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node17 : INode
{
public Node17()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node18 : INode
{
public Node18()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node19 : INode
{
public Node19()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node20 : INode
{
public Node20()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node21 : INode
{
public Node21()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node22 : INode
{
public Node22()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node23 : INode
{
public Node23()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node24 : INode
{
public Node24(
Node48 node48)
{
this.Children = new INode[]
{
node48,
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node25 : INode
{
public Node25()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node26 : INode
{
public Node26()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node27 : INode
{
public Node27()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node28 : INode
{
public Node28()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node29 : INode
{
public Node29()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node30 : INode
{
public Node30()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node31 : INode
{
public Node31()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node32 : INode
{
public Node32()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node33 : INode
{
public Node33()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node34 : INode
{
public Node34()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node35 : INode
{
public Node35()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node36 : INode
{
public Node36()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node37 : INode
{
public Node37()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node38 : INode
{
public Node38()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node39 : INode
{
public Node39()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node40 : INode
{
public Node40()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node41 : INode
{
public Node41()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node42 : INode
{
public Node42()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node43 : INode
{
public Node43()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node44 : INode
{
public Node44()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node45 : INode
{
public Node45()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node46 : INode
{
public Node46()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node47 : INode
{
public Node47()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node48 : INode
{
public Node48()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
public class Node49 : INode
{
public Node49()
{
this.Children = new INode[]
{
};
}
public IReadOnlyList<INode> Children { get; }
public IEnumerable<INode> AllChildren => this.Children.Concat(this.Children.SelectMany(c => c.AllChildren));
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Serialization;
namespace Orleans
{
internal class InvokableObjectManager : IDisposable
{
private readonly CancellationTokenSource disposed = new CancellationTokenSource();
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
private readonly IRuntimeClient runtimeClient;
private readonly ILogger logger;
private readonly SerializationManager serializationManager;
private readonly Func<object, Task> dispatchFunc;
public InvokableObjectManager(IRuntimeClient runtimeClient, SerializationManager serializationManager, ILogger<InvokableObjectManager> logger)
{
this.runtimeClient = runtimeClient;
this.serializationManager = serializationManager;
this.logger = logger;
this.dispatchFunc = o =>
this.LocalObjectMessagePumpAsync((LocalObjectData) o);
}
public bool TryRegister(IAddressable obj, GuidId objectId, IGrainMethodInvoker invoker)
{
return this.localObjects.TryAdd(objectId, new LocalObjectData(obj, objectId, invoker));
}
public bool TryDeregister(GuidId objectId)
{
return this.localObjects.TryRemove(objectId, out LocalObjectData ignored);
}
public void Dispatch(Message message)
{
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
this.logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound_2,
string.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message));
return;
}
if (this.localObjects.TryGetValue(observerId, out var objectData))
{
this.Invoke(objectData, message);
}
else
{
this.logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void Invoke(LocalObjectData objectData, Message message)
{
var obj = (IAddressable)objectData.LocalObject.Target;
if (obj == null)
{
//// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore.
this.logger.Warn(
ErrorCode.Runtime_Error_100162,
string.Format(
"Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}",
objectData.ObserverId,
message));
// Try to remove. If it's not there, we don't care.
this.TryDeregister(objectData.ObserverId);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace($"InvokeLocalObjectAsync {message} start {start}");
if (start)
{
// we want to ensure that the message pump operates asynchronously
// with respect to the current thread. see
// http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74
// at position 54:45.
//
// according to the information posted at:
// http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr
// this idiom is dependent upon the a TaskScheduler not implementing the
// override QueueTask as task inlining (as opposed to queueing). this seems
// implausible to the author, since none of the .NET schedulers do this and
// it is considered bad form (the OrleansTaskScheduler does not do this).
//
// if, for some reason this doesn't hold true, we can guarantee what we
// want by passing a placeholder continuation token into Task.StartNew()
// instead. i.e.:
//
// return Task.StartNew(() => ..., new CancellationToken());
// We pass these options to Task.Factory.StartNew as they make the call identical
// to Task.Run. See: https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/
Task.Factory.StartNew(
this.dispatchFunc,
objectData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default).Ignore();
}
}
private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData)
{
while (true)
{
try
{
Message message;
lock (objectData.Messages)
{
if (objectData.Messages.Count == 0)
{
objectData.Running = false;
break;
}
message = objectData.Messages.Dequeue();
}
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke))
continue;
RequestContextExtensions.Import(message.RequestContextData);
InvokeMethodRequest request = null;
try
{
request = (InvokeMethodRequest) message.GetDeserializedBody(this.serializationManager);
}
catch (Exception deserializationException)
{
if (this.logger.IsEnabled(LogLevel.Warning))
{
this.logger.LogWarning(
"Exception during message body deserialization in " + nameof(LocalObjectMessagePumpAsync) + " for message: {Message}, Exception: {Exception}",
message,
deserializationException);
}
this.runtimeClient.SendResponse(message, Response.ExceptionResponse(deserializationException));
continue;
}
var targetOb = (IAddressable)objectData.LocalObject.Target;
object resultObject = null;
Exception caught = null;
try
{
// exceptions thrown within this scope are not considered to be thrown from user code
// and not from runtime code.
var resultPromise = objectData.Invoker.Invoke(targetOb, request);
if (resultPromise != null) // it will be null for one way messages
{
resultObject = await resultPromise;
}
}
catch (Exception exc)
{
// the exception needs to be reported in the log or propagated back to the caller.
caught = exc;
}
if (caught != null)
this.ReportException(message, caught);
else if (message.Direction != Message.Directions.OneWay)
this.SendResponseAsync(message, resultObject);
}
catch (Exception outerException)
{
// ignore, keep looping.
this.logger.LogWarning("Exception in " + nameof(LocalObjectMessagePumpAsync) + ": {Exception}", outerException);
}
finally
{
RequestContext.Clear();
}
}
}
private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase)
{
if (message.IsExpired)
{
message.DropExpiredMessage(phase);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void SendResponseAsync(Message message, object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
{
return;
}
object deepCopy;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = this.serializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
this.runtimeClient.SendResponse(message, Response.ExceptionResponse(exc2));
this.logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.",
exc2);
return;
}
// the deep-copy succeeded.
this.runtimeClient.SendResponse(message, new Response(deepCopy));
return;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager);
switch (message.Direction)
{
case Message.Directions.OneWay:
{
this.logger.Error(
ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
String.Format(
"Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
request.MethodId,
request.InterfaceId),
exception);
break;
}
case Message.Directions.Request:
{
Exception deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = (Exception)this.serializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
this.runtimeClient.SendResponse(message, Response.ExceptionResponse(ex2));
this.logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
this.runtimeClient.SendResponse(message, response);
break;
}
default:
throw new InvalidOperationException($"Unrecognized direction for message {message}, request {request}, which resulted in exception: {exception}");
}
}
public class LocalObjectData
{
internal WeakReference LocalObject { get; }
internal IGrainMethodInvoker Invoker { get; }
internal GuidId ObserverId { get; }
internal Queue<Message> Messages { get; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
this.LocalObject = new WeakReference(obj);
this.ObserverId = observerId;
this.Invoker = invoker;
this.Messages = new Queue<Message>();
this.Running = false;
}
}
public void Dispose()
{
var tokenSource = this.disposed;
Utils.SafeExecute(() => tokenSource?.Cancel(false));
Utils.SafeExecute(() => tokenSource?.Dispose());
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Adult Group Members Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SGAMDataSet : EduHubDataSet<SGAM>
{
/// <inheritdoc />
public override string Name { get { return "SGAM"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SGAMDataSet(EduHubContext Context)
: base(Context)
{
Index_SGAMKEY = new Lazy<Dictionary<string, IReadOnlyList<SGAM>>>(() => this.ToGroupedDictionary(i => i.SGAMKEY));
Index_TID = new Lazy<Dictionary<int, SGAM>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SGAM" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SGAM" /> fields for each CSV column header</returns>
internal override Action<SGAM, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SGAM, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "SGAMKEY":
mapper[i] = (e, v) => e.SGAMKEY = v;
break;
case "ADULT_PERSON_TYPE":
mapper[i] = (e, v) => e.ADULT_PERSON_TYPE = v;
break;
case "PERSON_LINK":
mapper[i] = (e, v) => e.PERSON_LINK = v;
break;
case "DF_PARTICIPATION":
mapper[i] = (e, v) => e.DF_PARTICIPATION = v;
break;
case "RESPONSIBLE":
mapper[i] = (e, v) => e.RESPONSIBLE = v;
break;
case "START_DATE":
mapper[i] = (e, v) => e.START_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "END_DATE":
mapper[i] = (e, v) => e.END_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "OTHER_COMMENTS":
mapper[i] = (e, v) => e.OTHER_COMMENTS = v;
break;
case "GROUP_ROLE":
mapper[i] = (e, v) => e.GROUP_ROLE = v;
break;
case "SG_TYPE":
mapper[i] = (e, v) => e.SG_TYPE = v;
break;
case "HOUSE_HG":
mapper[i] = (e, v) => e.HOUSE_HG = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SGAM" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SGAM" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SGAM" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SGAM}"/> of entities</returns>
internal override IEnumerable<SGAM> ApplyDeltaEntities(IEnumerable<SGAM> Entities, List<SGAM> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SGAMKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.SGAMKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, IReadOnlyList<SGAM>>> Index_SGAMKEY;
private Lazy<Dictionary<int, SGAM>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find SGAM by SGAMKEY field
/// </summary>
/// <param name="SGAMKEY">SGAMKEY value used to find SGAM</param>
/// <returns>List of related SGAM entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SGAM> FindBySGAMKEY(string SGAMKEY)
{
return Index_SGAMKEY.Value[SGAMKEY];
}
/// <summary>
/// Attempt to find SGAM by SGAMKEY field
/// </summary>
/// <param name="SGAMKEY">SGAMKEY value used to find SGAM</param>
/// <param name="Value">List of related SGAM entities</param>
/// <returns>True if the list of related SGAM entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySGAMKEY(string SGAMKEY, out IReadOnlyList<SGAM> Value)
{
return Index_SGAMKEY.Value.TryGetValue(SGAMKEY, out Value);
}
/// <summary>
/// Attempt to find SGAM by SGAMKEY field
/// </summary>
/// <param name="SGAMKEY">SGAMKEY value used to find SGAM</param>
/// <returns>List of related SGAM entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SGAM> TryFindBySGAMKEY(string SGAMKEY)
{
IReadOnlyList<SGAM> value;
if (Index_SGAMKEY.Value.TryGetValue(SGAMKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SGAM by TID field
/// </summary>
/// <param name="TID">TID value used to find SGAM</param>
/// <returns>Related SGAM entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SGAM FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find SGAM by TID field
/// </summary>
/// <param name="TID">TID value used to find SGAM</param>
/// <param name="Value">Related SGAM entity</param>
/// <returns>True if the related SGAM entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out SGAM Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find SGAM by TID field
/// </summary>
/// <param name="TID">TID value used to find SGAM</param>
/// <returns>Related SGAM entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SGAM TryFindByTID(int TID)
{
SGAM value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SGAM table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SGAM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SGAM](
[TID] int IDENTITY NOT NULL,
[SGAMKEY] varchar(12) NOT NULL,
[ADULT_PERSON_TYPE] varchar(2) NULL,
[PERSON_LINK] varchar(10) NULL,
[DF_PARTICIPATION] varchar(1) NULL,
[RESPONSIBLE] varchar(1) NULL,
[START_DATE] datetime NULL,
[END_DATE] datetime NULL,
[OTHER_COMMENTS] varchar(MAX) NULL,
[GROUP_ROLE] varchar(30) NULL,
[SG_TYPE] varchar(1) NULL,
[HOUSE_HG] varchar(10) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SGAM_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE CLUSTERED INDEX [SGAM_Index_SGAMKEY] ON [dbo].[SGAM]
(
[SGAMKEY] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGAM]') AND name = N'SGAM_Index_TID')
ALTER INDEX [SGAM_Index_TID] ON [dbo].[SGAM] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGAM]') AND name = N'SGAM_Index_TID')
ALTER INDEX [SGAM_Index_TID] ON [dbo].[SGAM] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SGAM"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SGAM"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SGAM> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[SGAM] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SGAM data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SGAM data set</returns>
public override EduHubDataSetDataReader<SGAM> GetDataSetDataReader()
{
return new SGAMDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SGAM data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SGAM data set</returns>
public override EduHubDataSetDataReader<SGAM> GetDataSetDataReader(List<SGAM> Entities)
{
return new SGAMDataReader(new EduHubDataSetLoadedReader<SGAM>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SGAMDataReader : EduHubDataSetDataReader<SGAM>
{
public SGAMDataReader(IEduHubDataSetReader<SGAM> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 15; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // SGAMKEY
return Current.SGAMKEY;
case 2: // ADULT_PERSON_TYPE
return Current.ADULT_PERSON_TYPE;
case 3: // PERSON_LINK
return Current.PERSON_LINK;
case 4: // DF_PARTICIPATION
return Current.DF_PARTICIPATION;
case 5: // RESPONSIBLE
return Current.RESPONSIBLE;
case 6: // START_DATE
return Current.START_DATE;
case 7: // END_DATE
return Current.END_DATE;
case 8: // OTHER_COMMENTS
return Current.OTHER_COMMENTS;
case 9: // GROUP_ROLE
return Current.GROUP_ROLE;
case 10: // SG_TYPE
return Current.SG_TYPE;
case 11: // HOUSE_HG
return Current.HOUSE_HG;
case 12: // LW_DATE
return Current.LW_DATE;
case 13: // LW_TIME
return Current.LW_TIME;
case 14: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // ADULT_PERSON_TYPE
return Current.ADULT_PERSON_TYPE == null;
case 3: // PERSON_LINK
return Current.PERSON_LINK == null;
case 4: // DF_PARTICIPATION
return Current.DF_PARTICIPATION == null;
case 5: // RESPONSIBLE
return Current.RESPONSIBLE == null;
case 6: // START_DATE
return Current.START_DATE == null;
case 7: // END_DATE
return Current.END_DATE == null;
case 8: // OTHER_COMMENTS
return Current.OTHER_COMMENTS == null;
case 9: // GROUP_ROLE
return Current.GROUP_ROLE == null;
case 10: // SG_TYPE
return Current.SG_TYPE == null;
case 11: // HOUSE_HG
return Current.HOUSE_HG == null;
case 12: // LW_DATE
return Current.LW_DATE == null;
case 13: // LW_TIME
return Current.LW_TIME == null;
case 14: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // SGAMKEY
return "SGAMKEY";
case 2: // ADULT_PERSON_TYPE
return "ADULT_PERSON_TYPE";
case 3: // PERSON_LINK
return "PERSON_LINK";
case 4: // DF_PARTICIPATION
return "DF_PARTICIPATION";
case 5: // RESPONSIBLE
return "RESPONSIBLE";
case 6: // START_DATE
return "START_DATE";
case 7: // END_DATE
return "END_DATE";
case 8: // OTHER_COMMENTS
return "OTHER_COMMENTS";
case 9: // GROUP_ROLE
return "GROUP_ROLE";
case 10: // SG_TYPE
return "SG_TYPE";
case 11: // HOUSE_HG
return "HOUSE_HG";
case 12: // LW_DATE
return "LW_DATE";
case 13: // LW_TIME
return "LW_TIME";
case 14: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "SGAMKEY":
return 1;
case "ADULT_PERSON_TYPE":
return 2;
case "PERSON_LINK":
return 3;
case "DF_PARTICIPATION":
return 4;
case "RESPONSIBLE":
return 5;
case "START_DATE":
return 6;
case "END_DATE":
return 7;
case "OTHER_COMMENTS":
return 8;
case "GROUP_ROLE":
return 9;
case "SG_TYPE":
return 10;
case "HOUSE_HG":
return 11;
case "LW_DATE":
return 12;
case "LW_TIME":
return 13;
case "LW_USER":
return 14;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.IO;
using CK.Core;
using System.IO.Compression;
using static CK.Testing.BasicTestHelper;
namespace CK.Globbing.Tests
{
[TestFixture]
public class ZipTests
{
static string ZipTestsFolder = Path.Combine( TestHelper.TestProjectFolder, @"ZipTests\" );
[Test]
public void writing_and_reading_a_very_small_zip_file()
{
string path = Path.Combine( ZipTestsFolder, @"writing_a_very_small_zip_file.zip" );
var bytesWrite = new byte[] { 30, 21, 36, 4, 248, 5,
60, 11, 52, 43, 186, 200,
0, 91, 68, 234, 215 };
File.Delete( path );
using( var file = File.OpenWrite( path ) )
using( var zip = new ZipArchive( file, ZipArchiveMode.Create ) )
{
var c = zip.CreateEntry( "SimpleEntry.cs" );
using( var content = c.Open() )
{
content.Write( bytesWrite, 0, bytesWrite.Length );
}
}
using( var file = File.OpenRead( path ) )
using( var zip = new ZipArchive( file, ZipArchiveMode.Read ) )
{
var c = zip.GetEntry( "SimpleEntry.cs" );
using( var content = c.Open() )
{
var bytesRead = new byte[100];
Assert.That( content.Read( bytesRead, 0, bytesRead.Length ) == bytesWrite.Length );
}
}
File.Delete( path );
}
[Test]
public void transparently_enumerating_files_from_a_zip()
{
using( var s = new VirtualFileStorage() )
{
string root = Path.Combine( ZipTestsFolder, "Folder/FolderHasBeenZipped.zip" );
var fInZip = s.EnumerateFiles( root ).ToList();
ContainsFolderHasBeenZipped( fInZip, root );
}
}
[Test]
public void transparently_enumerating_files_from_a_zip_is_recursive()
{
using( var s = new VirtualFileStorage() )
{
{
string root = Path.Combine( ZipTestsFolder, "Folder" );
var fInFolder = s.EnumerateFiles( root ).ToList();
ContainsFolder( fInFolder, root, hasFolderHasBeenZipped:true );
}
{
string root = ZipTestsFolder;
var fInFolder = s.EnumerateFiles( root ).ToList();
ContainsZipTests( fInFolder, root );
}
}
}
[Test]
public void transparently_enumerating_files_from_inside_a_zip()
{
using( var s = new VirtualFileStorage() )
{
{
string root = Path.Combine( ZipTestsFolder, "Folder/FolderHasBeenZipped.zip/Folder" );
var fInZip = s.EnumerateFiles( root ).ToList();
ContainsFolder( fInZip, root, hasFolderHasBeenZipped: false );
}
{
string root = Path.Combine( ZipTestsFolder, "src.zip/Bootstrapper" );
var fInZip = s.EnumerateFiles( root ).ToList();
ContainsBootstrapper( fInZip, root );
}
}
}
[Test]
public void reading_file_data_can_be_transparently_done_from_a_zip_file()
{
using( var s = new VirtualFileStorage() )
{
{
string file = Path.Combine( ZipTestsFolder, "Folder/AnotherTextInFolder.txt" );
string text = ReadText( s, file );
Assert.That( text == "A" );
}
{
string file = Path.Combine( ZipTestsFolder, "Folder/Sub/NewDoc.txt" );
string text = ReadText( s, file );
Assert.That( text == "NewDoc" );
}
{
string file = Path.Combine( ZipTestsFolder, "Folder/FolderHasBeenZipped.zip/ANewTextDocument.txt" );
string text = ReadText( s, file );
Assert.That( text == "A2" );
}
{
string file = Path.Combine( ZipTestsFolder, "Folder/FolderHasBeenZipped.zip/Folder/Sub/NewDoc.txt" );
string text = ReadText( s, file );
Assert.That( text == "NewDoc" );
}
{
string file = Path.Combine( ZipTestsFolder, "src.zip/Bootstrapper/DataServicePackage.cs" );
string text = ReadText( s, file );
Assert.That( text == "File is DataServicePackage" );
}
}
}
string ReadText( IVirtualFileStorage s, string file )
{
using( var stream = s.OpenRead( file ) )
using( var reader = new StreamReader( stream ) )
{
return reader.ReadToEnd();
}
}
void ContainsFolderHasBeenZipped( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"ANewTextDocument.txt" ) );
Assert.That( files.Contains( prefix + @"TextDocument.txt" ) );
ContainsFolder( files, prefix + "Folder", hasFolderHasBeenZipped: false );
}
void ContainsFolder( IEnumerable<string> files, string prefix, bool hasFolderHasBeenZipped )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"Sub\NewDoc.txt" ) );
Assert.That( files.Contains( prefix + @"AnotherTextInFolder.txt" ) );
Assert.That( files.Contains( prefix + @"TextInFolder.txt" ) );
if( hasFolderHasBeenZipped )
{
Assert.That( files.Contains( prefix + @"FolderHasBeenZipped.zip" ) );
ContainsFolderHasBeenZipped( files, prefix + @"FolderHasBeenZipped.zip" );
}
else
{
Assert.That( files.Contains( prefix + @"FolderHasBeenZipped.zip" ) == false );
}
}
void ContainsBootstrapper( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"Properties\AssemblyInfo.cs" ) );
Assert.That( files.Contains( prefix + @"NuGetResources.resx" ) );
Assert.That( files.Contains( prefix + @"Bootstrapper.csproj" ) );
Assert.That( files.Contains( prefix + @"DataServicePackage.cs" ) );
}
void ContainsPackageManagerUIConverter( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"BooleanToVisibilityConverter.cs" ) );
Assert.That( files.Contains( prefix + @"CountToVisibilityConverter.cs" ) );
Assert.That( files.Contains( prefix + @"DescriptionLabelConverter.cs" ) );
Assert.That( files.Contains( prefix + @"FixUrlConverter.cs" ) );
}
void ContainsPackageManagerUI( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"packageicon.png" ) );
Assert.That( files.Contains( prefix + @"IProgressWindowOpener.cs" ) );
Assert.That( files.Contains( prefix + @"ISelectedProviderSettings.cs" ) );
Assert.That( files.Contains( prefix + @"IUserNotifierServices.cs" ) );
ContainsPackageManagerUIConverter( files, prefix + "Converter" );
}
void ContainsDialogServices( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"Properties\AssemblyInfo.cs" ) );
Assert.That( files.Contains( prefix + @"DialogServices.csproj" ) );
Assert.That( files.Contains( prefix + @"WindowSizePersistenceHelper.cs" ) );
Assert.That( files.Contains( prefix + @"NativeMethods.cs" ) );
ContainsPackageManagerUI( files, "PackageManagerUI" );
}
void ContainsSrcZip( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
ContainsBootstrapper( files, prefix + "Bootstrapper" );
}
void ContainsZipTests( IEnumerable<string> files, string prefix )
{
prefix = FileUtil.NormalizePathSeparator( prefix, true );
Assert.That( files.Contains( prefix + @"ANewTextDocument.txt" ) );
Assert.That( files.Contains( prefix + @"TextDocument.txt" ) );
Assert.That( files.Contains( prefix + @"src.zip" ) );
ContainsSrcZip( files, prefix + "src.zip" );
ContainsFolder( files, prefix + "Folder", hasFolderHasBeenZipped: true );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using ServiceStack.Common;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Support;
namespace ServiceStack.WebHost.Endpoints.Extensions
{
/**
*
Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment
Some HttpRequest path and URL properties:
Request.ApplicationPath: /Cambia3
Request.CurrentExecutionFilePath: /Cambia3/Temp/Test.aspx
Request.FilePath: /Cambia3/Temp/Test.aspx
Request.Path: /Cambia3/Temp/Test.aspx/path/info
Request.PathInfo: /path/info
Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\Cambia3\
Request.QueryString: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.AbsolutePath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.AbsoluteUri: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Fragment:
Request.Url.Host: localhost
Request.Url.LocalPath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.PathAndQuery: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Port: 96
Request.Url.Query: ?query=arg
Request.Url.Scheme: http
Request.Url.Segments: /
Cambia3/
Temp/
Test.aspx/
path/
info
* */
public static class HttpRequestExtensions
{
private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions));
private static string WebHostDirectoryName = "";
static HttpRequestExtensions()
{
WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath());
}
public static string GetOperationName(this HttpRequest request)
{
var pathInfo = request.GetLastPathInfo();
return GetOperationNameFromLastPathInfo(pathInfo);
}
public static string GetOperationNameFromLastPathInfo(string lastPathInfo)
{
if (String.IsNullOrEmpty(lastPathInfo)) return null;
var operationName = lastPathInfo.Substring("/".Length);
return operationName;
}
private static string GetLastPathInfoFromRawUrl(string rawUrl)
{
var pathInfo = rawUrl.IndexOf("?") != -1
? rawUrl.Substring(0, rawUrl.IndexOf("?"))
: rawUrl;
pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/"));
return pathInfo;
}
public static string GetLastPathInfo(this HttpRequest request)
{
var pathInfo = request.PathInfo;
if (String.IsNullOrEmpty(pathInfo))
{
pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl);
}
//Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}",
// request.PathInfo, request.RawUrl, pathInfo);
return pathInfo;
}
public static string GetUrlHostName(this HttpRequest request)
{
//TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host'
try
{
return request.Url.Host;
}
catch (Exception ex)
{
Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex);
return request.UserHostName;
}
}
// http://localhost/ServiceStack.Examples.Host.Web/Public/Public/Soap12/Wsdl =>
// http://localhost/ServiceStack.Examples.Host.Web/Public/Soap12/
public static string GetParentBaseUrl(this HttpRequest request)
{
var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); // /Cambia3/Temp/Test.aspx/path
return GetAuthority(request) + endpointsPath;
}
public static string GetParentBaseUrl(this IHttpRequest request){
var rawUrl = request.RawUrl;
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1);
return new Uri(request.AbsoluteUri).GetLeftPart(UriPartial.Authority) + endpointsPath;
}
public static string GetBaseUrl(this HttpRequest request)
{
return GetAuthority(request) + request.RawUrl;
}
//=> http://localhost:96 ?? ex=> http://localhost
private static string GetAuthority(HttpRequest request)
{
try
{
return request.Url.GetLeftPart(UriPartial.Authority);
}
catch (Exception ex)
{
Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex);
return "http://" + request.UserHostName;
}
}
public static string GetOperationName(this HttpListenerRequest request)
{
return request.Url.Segments[request.Url.Segments.Length - 1];
}
public static string GetLastPathInfo(this HttpListenerRequest request)
{
return GetLastPathInfoFromRawUrl(request.RawUrl);
}
public static string GetPathInfo(this HttpRequest request)
{
if (!String.IsNullOrEmpty(request.PathInfo)) return request.PathInfo.TrimEnd('/');
var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath;
var appPath = String.IsNullOrEmpty(request.ApplicationPath)
? WebHostDirectoryName
: request.ApplicationPath.TrimStart('/');
//mod_mono: /CustomPath35/api//default.htm
var path = Env.IsMono ? request.Path.Replace("//", "/") : request.Path;
return GetPathInfo(path, mode, appPath);
}
public static string GetPathInfo(string fullPath, string mode, string appPath)
{
var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
if (!String.IsNullOrEmpty(pathInfo)) return pathInfo;
//Wildcard mode relies on this to work out the handlerPath
pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
if (!String.IsNullOrEmpty(pathInfo)) return pathInfo;
return fullPath;
}
public static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
{
if (mappedPathRoot == null) return null;
var sbPathInfo = new StringBuilder();
var fullPathParts = fullPath.Split('/');
var mappedPathRootParts = mappedPathRoot.Split('/');
var fullPathIndexOffset = mappedPathRootParts.Length - 1;
var pathRootFound = false;
for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++) {
if (pathRootFound) {
sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
} else if (fullPathIndex - fullPathIndexOffset >= 0) {
pathRootFound = true;
for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++) {
if (!String.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.InvariantCultureIgnoreCase)) {
pathRootFound = false;
break;
}
}
}
}
if (!pathRootFound) return null;
var path = sbPathInfo.ToString();
return path.Length > 1 ? path.TrimEnd('/') : "/";
}
public static bool IsContentType(this IHttpRequest request, string contentType)
{
return request.ContentType.StartsWith(contentType, StringComparison.InvariantCultureIgnoreCase);
}
public static bool HasAnyOfContentTypes(this IHttpRequest request, params string[] contentTypes)
{
if (contentTypes == null || request.ContentType == null) return false;
foreach (var contentType in contentTypes)
{
if (IsContentType(request, contentType)) return true;
}
return false;
}
public static IHttpRequest GetHttpRequest(this HttpRequest request)
{
return new HttpRequestWrapper(null, request);
}
public static IHttpRequest GetHttpRequest(this HttpListenerRequest request)
{
return new HttpListenerRequestWrapper(null, request);
}
public static Dictionary<string, string> GetRequestParams(this IHttpRequest request)
{
var map = new Dictionary<string, string>();
foreach (var name in request.QueryString.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.QueryString[name];
}
if ((request.HttpMethod == HttpMethods.Post || request.HttpMethod == HttpMethods.Put)
&& request.FormData != null)
{
foreach (var name in request.FormData.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.FormData[name];
}
}
return map;
}
public static string GetQueryStringContentType(this IHttpRequest httpReq)
{
var callback = httpReq.QueryString["callback"];
if (!String.IsNullOrEmpty(callback)) return ContentType.Json;
var format = httpReq.QueryString["format"];
if (format == null)
{
const int formatMaxLength = 4;
var pi = httpReq.PathInfo;
if (pi == null || pi.Length <= formatMaxLength) return null;
if (pi[0] == '/') pi = pi.Substring(1);
format = pi.SplitOnFirst('/')[0];
if (format.Length > formatMaxLength) return null;
}
format = format.SplitOnFirst('.')[0].ToLower();
if (format.Contains("json")) return ContentType.Json;
if (format.Contains("xml")) return ContentType.Xml;
if (format.Contains("jsv")) return ContentType.Jsv;
string contentType;
EndpointHost.ContentTypeFilter.ContentTypeFormats.TryGetValue(format, out contentType);
return contentType;
}
public static string[] PreferredContentTypes = new[] {
ContentType.Html, ContentType.Json, ContentType.Xml, ContentType.Jsv
};
/// <summary>
/// Use this to treat Request.Items[] as a cache by returning pre-computed items to save
/// calculating them multiple times.
/// </summary>
public static object ResolveItem(this IHttpRequest httpReq,
string itemKey, Func<IHttpRequest, object> resolveFn)
{
object cachedItem;
if (httpReq.Items.TryGetValue(itemKey, out cachedItem))
return cachedItem;
var item = resolveFn(httpReq);
httpReq.Items[itemKey] = item;
return item;
}
public static string GetResponseContentType(this IHttpRequest httpReq)
{
var specifiedContentType = GetQueryStringContentType(httpReq);
if (!String.IsNullOrEmpty(specifiedContentType)) return specifiedContentType;
var acceptContentTypes = httpReq.AcceptTypes;
var defaultContentType = httpReq.ContentType;
if (httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData))
{
defaultContentType = EndpointHost.Config.DefaultContentType;
}
var customContentTypes = EndpointHost.ContentTypeFilter.ContentTypeFormats.Values;
var acceptsAnything = false;
var hasDefaultContentType = !String.IsNullOrEmpty(defaultContentType);
if (acceptContentTypes != null)
{
var hasPreferredContentTypes = new bool[PreferredContentTypes.Length];
foreach (var contentType in acceptContentTypes)
{
acceptsAnything = acceptsAnything || contentType == "*/*";
for (var i = 0; i < PreferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) continue;
var preferredContentType = PreferredContentTypes[i];
hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);
//Prefer Request.ContentType if it is also a preferredContentType
if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
return preferredContentType;
}
}
for (var i = 0; i < PreferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) return PreferredContentTypes[i];
}
if (acceptsAnything && hasDefaultContentType) return defaultContentType;
foreach (var contentType in acceptContentTypes)
{
foreach (var customContentType in customContentTypes)
{
if (contentType.StartsWith(customContentType)) return customContentType;
}
}
}
//We could also send a '406 Not Acceptable', but this is allowed also
return EndpointHost.Config.DefaultContentType;
}
public static void SetView(this IHttpRequest httpReq, string viewName)
{
httpReq.SetItem("View", viewName);
}
public static string GetView(this IHttpRequest httpReq)
{
return httpReq.GetItem("View") as string;
}
public static void SetTemplate(this IHttpRequest httpReq, string templateName)
{
httpReq.SetItem("Template", templateName);
}
public static string GetTemplate(this IHttpRequest httpReq)
{
return httpReq.GetItem("Template") as string;
}
public static string ResolveAbsoluteUrl(this IHttpRequest httpReq, string url)
{
return EndpointHost.AppHost.ResolveAbsoluteUrl(url, httpReq);
}
public static string ResolveBaseUrl(this IHttpRequest httpReq)
{
return EndpointHost.AppHost.ResolveAbsoluteUrl("~/", httpReq);
}
public static string GetAbsoluteUrl(this IHttpRequest httpReq, string url)
{
if (url.SafeSubstring(0, 2) == "~/")
{
url = httpReq.GetBaseUrl().CombineWith(url.Substring(2));
}
return url;
}
public static string GetBaseUrl(this IHttpRequest httpReq)
{
var baseUrl = ServiceStackHttpHandlerFactory.GetBaseUrl();
if (baseUrl != null) return baseUrl;
var handlerPath = EndpointHost.Config.ServiceStackHandlerFactoryPath;
if (handlerPath != null)
{
var pos = httpReq.AbsoluteUri.IndexOf(handlerPath, StringComparison.InvariantCultureIgnoreCase);
if (pos >= 0)
{
baseUrl = httpReq.AbsoluteUri.Substring(0, pos + handlerPath.Length);
return baseUrl;
}
return "/" + handlerPath;
}
return "/"; //Can't infer Absolute Uri, fallback to root relative path
}
public static EndpointAttributes ToEndpointAttributes(string[] attrNames)
{
var attrs = EndpointAttributes.None;
foreach (var simulatedAttr in attrNames)
{
var attr = (EndpointAttributes)Enum.Parse(typeof(EndpointAttributes), simulatedAttr, true);
attrs |= attr;
}
return attrs;
}
public static EndpointAttributes GetAttributes(this IHttpRequest request)
{
if (EndpointHost.DebugMode
&& request.QueryString != null) //Mock<IHttpRequest>
{
var simulate = request.QueryString["simulate"];
if (simulate != null)
{
return ToEndpointAttributes(simulate.Split(','));
}
}
var portRestrictions = EndpointAttributes.None;
portRestrictions |= HttpMethods.GetEndpointAttribute(request.HttpMethod);
portRestrictions |= request.IsSecureConnection ? EndpointAttributes.Secure : EndpointAttributes.InSecure;
if (request.UserHostAddress != null)
{
var isIpv4Address = request.UserHostAddress.IndexOf('.') != -1
&& request.UserHostAddress.IndexOf("::", StringComparison.InvariantCulture) == -1;
string ipAddressNumber = null;
if (isIpv4Address)
{
ipAddressNumber = request.UserHostAddress.SplitOnFirst(":")[0];
}
else
{
if (request.UserHostAddress.Contains("]:"))
{
ipAddressNumber = request.UserHostAddress.SplitOnLast(":")[0];
}
else
{
ipAddressNumber = request.UserHostAddress.LastIndexOf("%", StringComparison.InvariantCulture) > 0 ?
request.UserHostAddress.SplitOnLast(":")[0] :
request.UserHostAddress;
}
}
try
{
ipAddressNumber = ipAddressNumber.SplitOnFirst(',')[0];
var ipAddress = ipAddressNumber.StartsWith("::1")
? IPAddress.IPv6Loopback
: IPAddress.Parse(ipAddressNumber);
portRestrictions |= GetAttributes(ipAddress);
}
catch (Exception ex)
{
throw new ArgumentException("Could not parse Ipv{0} Address: {1} / {2}"
.Fmt((isIpv4Address ? 4 : 6), request.UserHostAddress, ipAddressNumber), ex);
}
}
return portRestrictions;
}
public static EndpointAttributes GetAttributes(IPAddress ipAddress)
{
if (IPAddress.IsLoopback(ipAddress))
return EndpointAttributes.Localhost;
return IsInLocalSubnet(ipAddress)
? EndpointAttributes.LocalSubnet
: EndpointAttributes.External;
}
public static bool IsInLocalSubnet(IPAddress ipAddress)
{
var ipAddressBytes = ipAddress.GetAddressBytes();
switch (ipAddress.AddressFamily)
{
case AddressFamily.InterNetwork:
foreach (var localIpv4AddressAndMask in EndpointHandlerBase.NetworkInterfaceIpv4Addresses)
{
if (ipAddressBytes.IsInSameIpv4Subnet(localIpv4AddressAndMask.Key, localIpv4AddressAndMask.Value))
{
return true;
}
}
break;
case AddressFamily.InterNetworkV6:
foreach (var localIpv6Address in EndpointHandlerBase.NetworkInterfaceIpv6Addresses)
{
if (ipAddressBytes.IsInSameIpv6Subnet(localIpv6Address))
{
return true;
}
}
break;
}
return false;
}
public static IHttpRequest ToRequest(this HttpRequest aspnetHttpReq, string operationName=null)
{
return new HttpRequestWrapper(aspnetHttpReq) {
OperationName = operationName,
DependencyService = AppHostBase.Instance != null ? AppHostBase.Instance.DependencyService : null
};
}
public static IHttpRequest ToRequest(this HttpListenerRequest listenerHttpReq, string operationName = null)
{
return new HttpListenerRequestWrapper(listenerHttpReq) {
OperationName = operationName,
DependencyService = AppHostBase.Instance != null ? AppHostBase.Instance.DependencyService : null
};
}
public static IHttpResponse ToResponse(this HttpResponse aspnetHttpRes)
{
return new HttpResponseWrapper(aspnetHttpRes);
}
public static IHttpResponse ToResponse(this HttpListenerResponse listenerHttpRes)
{
return new HttpListenerResponseWrapper(listenerHttpRes);
}
public static void SetOperationName(this IHttpRequest httpReq, string operationName)
{
if (httpReq.OperationName == null)
{
var aspReq = httpReq as HttpRequestWrapper;
if (aspReq != null)
{
aspReq.OperationName = operationName;
return;
}
var listenerReq = httpReq as HttpListenerRequestWrapper;
if (listenerReq != null)
{
listenerReq.OperationName = operationName;
}
}
}
public static System.ServiceModel.Channels.Message GetSoapMessage(this IHttpRequest httpReq)
{
return httpReq.Items["SoapMessage"] as System.ServiceModel.Channels.Message;
}
}
}
| |
#if UNITY_2017_1_OR_NEWER
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine.Formats.Alembic.Importer;
using UnityEngine.Formats.Alembic.Sdk;
using Object = UnityEngine.Object;
namespace UnityEditor.Formats.Alembic.Importer
{
internal class AlembicAssetModificationProcessor : UnityEditor.AssetModificationProcessor
{
public static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions rao)
{
if (string.IsNullOrEmpty(assetPath))
{
return AssetDeleteResult.DidNotDelete;
}
if (Path.GetExtension(assetPath.ToLower()) != ".abc")
return AssetDeleteResult.DidNotDelete;
AlembicStream.DisconnectStreamsWithPath(assetPath);
return AssetDeleteResult.DidNotDelete;
}
public static AssetMoveResult OnWillMoveAsset(string from, string to)
{
if (string.IsNullOrEmpty(from))
{
return AssetMoveResult.DidNotMove;
}
if (Path.GetExtension(from.ToLower()) != ".abc")
return AssetMoveResult.DidNotMove;
var importer = AssetImporter.GetAtPath(from) as AlembicImporter;
if (importer != null)
{
var so =new SerializedObject(importer);
var prop = so.FindProperty("rootGameObjectName");
if (prop != null && string.IsNullOrEmpty(prop.stringValue))
{
prop.stringValue = Path.GetFileNameWithoutExtension(from);
so.ApplyModifiedPropertiesWithoutUndo();
}
prop = so.FindProperty("rootGameObjectId");
if (prop != null && string.IsNullOrEmpty(prop.stringValue))
{
prop.stringValue = Path.GetFileNameWithoutExtension(from);
so.ApplyModifiedPropertiesWithoutUndo();
}
AssetDatabase.WriteImportSettingsIfDirty(from);
}
AlembicStream.DisconnectStreamsWithPath(from);
AlembicStream.RemapStreamsWithPath(from, to);
AssetDatabase.Refresh(ImportAssetOptions.Default);
AlembicStream.ReconnectStreamsWithPath(to);
return AssetMoveResult.DidNotMove;
}
}
[ScriptedImporter(6, "abc")]
internal class AlembicImporter : ScriptedImporter
{
[SerializeField]
#pragma warning disable 0649
private string rootGameObjectId;
[SerializeField]
private string rootGameObjectName;
#pragma warning restore 0649
[SerializeField]
private AlembicStreamSettings streamSettings = new AlembicStreamSettings();
public AlembicStreamSettings StreamSettings
{
get { return streamSettings; }
set { streamSettings = value; }
}
[SerializeField]
private double abcStartTime; // read only
public double AbcStartTime
{
get { return abcStartTime; }
}
[SerializeField]
private double abcEndTime; // read only
public double AbcEndTime
{
get { return abcEndTime; }
}
[SerializeField]
private double startTime = double.MinValue;
public double StartTime
{
get { return startTime; }
set { startTime = value; }
}
[SerializeField]
private double endTime = double.MaxValue;
public double EndTime
{
get { return endTime; }
set { endTime = value; }
}
[SerializeField]
private string importWarning;
public string ImportWarning
{
get { return importWarning; }
set { importWarning = value; }
}
[SerializeField]
private List<string> varyingTopologyMeshNames = new List<string>();
public List<string> VaryingTopologyMeshNames
{
get { return varyingTopologyMeshNames; }
}
[SerializeField]
private List<string> splittingMeshNames = new List<string>();
public List<string> SplittingMeshNames
{
get { return splittingMeshNames; }
}
[SerializeField] bool firstImport = true;
void OnValidate()
{
if (!firstImport)
{
if (startTime < abcStartTime)
startTime = abcStartTime;
if (endTime > abcEndTime)
endTime = abcStartTime;
}
}
public override void OnImportAsset(AssetImportContext ctx)
{
if (ctx == null)
{
return;
}
var path = ctx.assetPath;
AlembicStream.DisconnectStreamsWithPath(path);
var fileName = Path.GetFileNameWithoutExtension(path);
var previousGoName = fileName;
if (!string.IsNullOrEmpty(rootGameObjectName))
{
previousGoName = rootGameObjectName;
}
var go = new GameObject(previousGoName);
var streamDescriptor = ScriptableObject.CreateInstance<AlembicStreamDescriptor>();
streamDescriptor.name = go.name + "_ABCDesc";
streamDescriptor.PathToAbc = path;
streamDescriptor.Settings = StreamSettings;
using (var abcStream = new AlembicStream(go, streamDescriptor))
{
abcStream.AbcLoad(true, true);
abcStream.GetTimeRange(ref abcStartTime, ref abcEndTime);
if (firstImport)
{
startTime = abcStartTime;
endTime = abcEndTime;
}
streamDescriptor.abcStartTime = abcStartTime;
streamDescriptor.abcEndTime = abcEndTime;
var streamPlayer = go.AddComponent<AlembicStreamPlayer>();
streamPlayer.StreamDescriptor = streamDescriptor;
streamPlayer.StartTime = StartTime;
streamPlayer.EndTime = EndTime;
var subassets = new Subassets(ctx);
subassets.Add(streamDescriptor.name, streamDescriptor);
GenerateSubAssets(subassets, abcStream.abcTreeRoot, streamDescriptor);
AlembicStream.ReconnectStreamsWithPath(path);
var prevIdName = fileName;
if (!string.IsNullOrEmpty(rootGameObjectId))
{
prevIdName = rootGameObjectId;
}
ctx.AddObjectToAsset(prevIdName, go);
ctx.SetMainObject(go);
}
firstImport = false;
}
class Subassets
{
AssetImportContext m_ctx;
Material m_defaultMaterial;
Material m_defaultPointsMaterial;
Material m_defaultPointsMotionVectorMaterial;
public Subassets(AssetImportContext ctx)
{
m_ctx = ctx;
}
public Material defaultMaterial
{
get
{
if (m_defaultMaterial == null)
{
m_defaultMaterial = GetMaterial("Standard.shader");
m_defaultMaterial.hideFlags = HideFlags.NotEditable;
m_defaultMaterial.name = "Default Material";
Add("Default Material", m_defaultMaterial);
}
return m_defaultMaterial;
}
}
public Material pointsMaterial
{
get
{
if (m_defaultPointsMaterial == null)
{
m_defaultPointsMaterial = GetMaterial("StandardInstanced.shader");
m_defaultPointsMaterial.hideFlags = HideFlags.NotEditable;
m_defaultPointsMaterial.name = "Default Points";
Add("Default Points", m_defaultPointsMaterial);
}
return m_defaultPointsMaterial;
}
}
public Material pointsMotionVectorMaterial
{
get
{
if (m_defaultPointsMotionVectorMaterial == null)
{
m_defaultPointsMotionVectorMaterial = GetMaterial("AlembicPointsMotionVectors.shader");
m_defaultPointsMotionVectorMaterial.hideFlags = HideFlags.NotEditable;
m_defaultPointsMotionVectorMaterial.name = "Points Motion Vector";
Add("Points Motion Vector", m_defaultPointsMotionVectorMaterial);
}
return m_defaultPointsMotionVectorMaterial;
}
}
public void Add(string identifier, Object asset)
{
#if UNITY_2017_3_OR_NEWER
m_ctx.AddObjectToAsset(identifier, asset);
#else
m_ctx.AddSubAsset(identifier, asset);
#endif
}
Material GetMaterial(string shaderFile)
{
var path = Path.Combine("Packages/com.unity.formats.alembic/Runtime/Shaders", shaderFile);
m_ctx.DependsOnSourceAsset(path);
var shader =
AssetDatabase.LoadAssetAtPath<Shader>(path);
return new Material(shader);
}
}
void GenerateSubAssets(Subassets subassets, AlembicTreeNode root, AlembicStreamDescriptor streamDescr)
{
if (streamDescr.duration > 0)
{
// AnimationClip for time
{
var frames = new Keyframe[2];
frames[0].value = 0.0f;
frames[0].time = 0.0f;
frames[0].outTangent = 1.0f;
frames[1].value = (float)streamDescr.duration;
frames[1].time = (float)streamDescr.duration;
frames[1].inTangent = 1.0f;
var curve = new AnimationCurve(frames);
AnimationUtility.SetKeyLeftTangentMode(curve, 0, AnimationUtility.TangentMode.Linear);
AnimationUtility.SetKeyRightTangentMode(curve, 1, AnimationUtility.TangentMode.Linear);
var clip = new AnimationClip();
clip.SetCurve("", typeof(AlembicStreamPlayer), "currentTime", curve);
clip.name = root.gameObject.name + "_Time";
clip.hideFlags = HideFlags.NotEditable;
subassets.Add("Default Animation", clip);
}
// AnimationClip for frame events
{
var abc = root.stream.abcContext;
var n = abc.timeSamplingCount;
for (int i = 1; i < n; ++i)
{
var clip = new AnimationClip();
if (AddFrameEvents(clip, abc.GetTimeSampling(i)))
{
var name = root.gameObject.name + "_Frames";
if (n > 2)
name += i.ToString();
clip.name = name;
subassets.Add(clip.name, clip);
}
}
}
}
varyingTopologyMeshNames = new List<string>();
splittingMeshNames = new List<string>();
CollectSubAssets(subassets, root);
streamDescr.HasVaryingTopology = VaryingTopologyMeshNames.Count > 0;
}
void CollectSubAssets(Subassets subassets, AlembicTreeNode node)
{
var mesh = node.GetAlembicObj<AlembicMesh>();
if (mesh != null)
{
var sum = mesh.summary;
if (mesh.summary.topologyVariance == aiTopologyVariance.Heterogeneous)
VaryingTopologyMeshNames.Add(node.gameObject.name);
else if (mesh.sampleSummary.splitCount > 1)
SplittingMeshNames.Add(node.gameObject.name);
}
int submeshCount = 0;
var meshFilter = node.gameObject.GetComponent<MeshFilter>();
if (meshFilter != null)
{
var m = meshFilter.sharedMesh;
submeshCount = m.subMeshCount;
m.name = node.gameObject.name;
subassets.Add(node.abcObject.abcObject.fullname, m);
}
var renderer = node.gameObject.GetComponent<MeshRenderer>();
if (renderer != null)
{
var mats = new Material[submeshCount];
for (int i = 0; i < submeshCount; ++i)
mats[i] = subassets.defaultMaterial;
renderer.sharedMaterials = mats;
}
var apr = node.gameObject.GetComponent<AlembicPointsRenderer>();
if (apr != null)
{
var cubeGO = GameObject.CreatePrimitive(PrimitiveType.Cube);
apr.sharedMesh = cubeGO.GetComponent<MeshFilter>().sharedMesh;
DestroyImmediate(cubeGO);
apr.SetSharedMaterials(new Material[] { subassets.pointsMaterial });
apr.motionVectorMaterial = subassets.pointsMotionVectorMaterial;
}
foreach (var child in node.Children)
CollectSubAssets(subassets, child);
}
bool AddFrameEvents(AnimationClip clip, aiTimeSampling ts)
{
int n = ts.sampleCount;
if (n <= 0)
return false;
var events = new AnimationEvent[n];
for (int i = 0; i < n; ++i)
{
var ev = new AnimationEvent();
ev.time = (float)ts.GetTime(i);
ev.intParameter = i;
ev.functionName = "AbcOnFrameChange";
events[i] = ev;
}
AnimationUtility.SetAnimationEvents(clip, events);
return true;
}
}
}
#endif
| |
// <copyright file="AndroidTokenClient.cs" company="Google Inc.">
// Copyright (C) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if UNITY_ANDROID
namespace GooglePlayGames.Android
{
using System;
using System.Linq;
using BasicApi;
using OurUtils;
using UnityEngine;
using System.Collections.Generic;
internal class AndroidTokenClient : TokenClient
{
private const string HelperFragmentClass = "com.google.games.bridge.HelperFragment";
// These are the configuration values.
private bool requestEmail;
private bool requestAuthCode;
private bool requestIdToken;
private List<string> oauthScopes;
private string webClientId;
private bool forceRefresh;
private bool hidePopups;
private string accountName;
// These are the results
private AndroidJavaObject account;
private string email;
private string authCode;
private string idToken;
public void SetRequestAuthCode(bool flag, bool forceRefresh)
{
requestAuthCode = flag;
this.forceRefresh = forceRefresh;
}
public void SetRequestEmail(bool flag)
{
requestEmail = flag;
}
public void SetRequestIdToken(bool flag)
{
requestIdToken = flag;
}
public void SetWebClientId(string webClientId)
{
this.webClientId = webClientId;
}
public void SetHidePopups(bool flag)
{
this.hidePopups = flag;
}
public void SetAccountName(string accountName)
{
this.accountName = accountName;
}
public void AddOauthScopes(params string[] scopes)
{
if (scopes != null)
{
if (oauthScopes == null)
{
oauthScopes = new List<string>();
}
oauthScopes.AddRange(scopes);
}
}
public void Signout()
{
account = null;
authCode = null;
email = null;
idToken = null;
PlayGamesHelperObject.RunOnGameThread(() =>
{
Debug.Log("Calling Signout in token client");
AndroidJavaClass cls = new AndroidJavaClass(HelperFragmentClass);
cls.CallStatic("signOut", AndroidHelperFragment.GetActivity());
});
}
/// <summary>Gets the email selected by the current player.</summary>
/// <remarks>This is not necessarily the email address of the player. It
/// is just the account selected by the player from a list of accounts
/// present on the device.
/// </remarks>
/// <returns>A string representing the email.</returns>
public string GetEmail()
{
return email;
}
public string GetAuthCode()
{
return authCode;
}
/// <summary>Gets the OpenID Connect ID token for authentication with a server backend.</summary>
/// <param name="serverClientId">Server client ID from console.developers.google.com or the Play Games
/// services console.</param>
/// <param name="idTokenCallback"> A callback to be invoked after token is retrieved. Will be passed null value
/// on failure. </param>
public string GetIdToken()
{
return idToken;
}
public void FetchTokens(bool silent, Action<int> callback)
{
PlayGamesHelperObject.RunOnGameThread(() => DoFetchToken(silent, callback));
}
public void RequestPermissions(string[] scopes, Action<SignInStatus> callback)
{
using (var bridgeClass = new AndroidJavaClass(HelperFragmentClass))
using (var currentActivity = AndroidHelperFragment.GetActivity())
using (var task =
bridgeClass.CallStatic<AndroidJavaObject>("showRequestPermissionsUi", currentActivity,
oauthScopes.Union(scopes).ToArray()))
{
AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>(task, /* disposeResult= */ false,
accountWithNewScopes =>
{
if (accountWithNewScopes == null)
{
callback(SignInStatus.InternalError);
return;
}
account = accountWithNewScopes;
email = account.Call<string>("getEmail");
idToken = account.Call<string>("getIdToken");
authCode = account.Call<string>("getServerAuthCode");
oauthScopes = oauthScopes.Union(scopes).ToList();
callback(SignInStatus.Success);
});
AndroidTaskUtils.AddOnFailureListener(task, e =>
{
if (!Misc.IsApiException(e)) {
OurUtils.Logger.e("Exception requesting new permissions" +
e.Call<string>("toString"));
return;
}
var failCode = SignInHelper.ToSignInStatus(e.Call<int>("getStatusCode"));
OurUtils.Logger.e("Exception requesting new permissions: " + failCode);
callback(failCode);
});
}
}
/// <summary>Returns whether or not user has given permissions for given scopes.</summary>
/// <param name="scopes">array of scopes</param>
/// <returns><c>true</c>, if given, <c>false</c> otherwise.</returns>
public bool HasPermissions(string[] scopes)
{
using (var bridgeClass = new AndroidJavaClass(HelperFragmentClass))
using (var currentActivity = AndroidHelperFragment.GetActivity())
{
return bridgeClass.CallStatic<bool>("hasPermissions", currentActivity, scopes);
}
}
private void DoFetchToken(bool silent, Action<int> callback)
{
try
{
using (var bridgeClass = new AndroidJavaClass(HelperFragmentClass))
using (var currentActivity = AndroidHelperFragment.GetActivity())
using (var pendingResult = bridgeClass.CallStatic<AndroidJavaObject>(
"fetchToken",
currentActivity,
silent,
requestAuthCode,
requestEmail,
requestIdToken,
webClientId,
forceRefresh,
oauthScopes.ToArray(),
hidePopups,
accountName))
{
pendingResult.Call("setResultCallback", new ResultCallbackProxy(
tokenResult =>
{
account = tokenResult.Call<AndroidJavaObject>("getAccount");
authCode = tokenResult.Call<string>("getAuthCode");
email = tokenResult.Call<string>("getEmail");
idToken = tokenResult.Call<string>("getIdToken");
callback(tokenResult.Call<int>("getStatusCode"));
}));
}
}
catch (Exception e)
{
OurUtils.Logger.e("Exception launching token request: " + e.Message);
OurUtils.Logger.e(e.ToString());
}
}
public AndroidJavaObject GetAccount()
{
return account;
}
/// <summary>
/// Gets another server auth code.
/// </summary>
/// <remarks>This method should be called after authenticating, and exchanging
/// the initial server auth code for a token. This is implemented by signing in
/// silently, which if successful returns almost immediately and with a new
/// server auth code.
/// </remarks>
/// <param name="reAuthenticateIfNeeded">Calls Authenticate if needed when
/// retrieving another auth code. </param>
/// <param name="callback">Callback.</param>
public void GetAnotherServerAuthCode(bool reAuthenticateIfNeeded, Action<string> callback)
{
PlayGamesHelperObject.RunOnGameThread(() => DoGetAnotherServerAuthCode(reAuthenticateIfNeeded, callback));
}
private void DoGetAnotherServerAuthCode(bool reAuthenticateIfNeeded, Action<string> callback)
{
try
{
using (var bridgeClass = new AndroidJavaClass(HelperFragmentClass))
using (var currentActivity = AndroidHelperFragment.GetActivity())
using (var pendingResult = bridgeClass.CallStatic<AndroidJavaObject>(
"fetchToken",
currentActivity,
/* silent= */ reAuthenticateIfNeeded,
/* requestAuthCode= */ true,
/* requestEmail= */ false,
/* requestIdToken= */ false,
webClientId,
/* forceRefresh= */ false,
oauthScopes.ToArray(),
/* hidePopups= */ true,
/* accountName= */ ""))
{
pendingResult.Call("setResultCallback", new ResultCallbackProxy(
tokenResult => { callback(tokenResult.Call<string>("getAuthCode")); }));
}
}
catch (Exception e)
{
OurUtils.Logger.e("Exception launching token request: " + e.Message);
OurUtils.Logger.e(e.ToString());
}
}
private class ResultCallbackProxy : AndroidJavaProxy
{
private Action<AndroidJavaObject> mCallback;
public ResultCallbackProxy(Action<AndroidJavaObject> callback)
: base("com/google/android/gms/common/api/ResultCallback")
{
mCallback = callback;
}
public void onResult(AndroidJavaObject tokenResult)
{
mCallback(tokenResult);
}
}
}
}
#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.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Roslyn.Utilities;
using ShellInterop = Microsoft.VisualStudio.Shell.Interop;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
using VsThreading = Microsoft.VisualStudio.Threading;
using Document = Microsoft.CodeAnalysis.Document;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue
{
internal sealed class VsENCRebuildableProjectImpl
{
private readonly AbstractProject _vsProject;
// number of projects that are in the debug state:
private static int s_debugStateProjectCount;
// number of projects that are in the break state:
private static int s_breakStateProjectCount;
// projects that entered the break state:
private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>();
// active statements of projects that entered the break state:
private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>();
private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker;
internal static readonly TraceLog log = new TraceLog(2048, "EnC");
private static Solution s_breakStateEntrySolution;
private static EncDebuggingSessionInfo s_encDebuggingSessionInfo;
private readonly IEditAndContinueWorkspaceService _encService;
private readonly IActiveStatementTrackingService _trackingService;
private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider;
private readonly IDebugEncNotify _debugEncNotify;
private readonly INotificationService _notifications;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
#region Per Project State
private bool _changesApplied;
// maps VS Active Statement Id, which is unique within this project, to our id
private Dictionary<uint, ActiveStatementId> _activeStatementIds;
private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
private HashSet<uint> _activeMethods;
private List<VsExceptionRegion> _exceptionRegions;
private EmitBaseline _committedBaseline;
private EmitBaseline _pendingBaseline;
private Project _projectBeingEmitted;
private ImmutableArray<DocumentId> _documentsWithEmitError;
/// <summary>
/// Initialized when the project switches to debug state.
/// Null if the project has no output file or we can't read the MVID.
/// </summary>
private ModuleMetadata _metadata;
private ISymUnmanagedReader _pdbReader;
private IntPtr _pdbReaderObjAsStream;
#endregion
private bool IsDebuggable
{
get { return _metadata != null; }
}
internal VsENCRebuildableProjectImpl(AbstractProject project)
{
_vsProject = project;
_encService = _vsProject.VisualStudioWorkspace.Services.GetService<IEditAndContinueWorkspaceService>();
_trackingService = _vsProject.VisualStudioWorkspace.Services.GetService<IActiveStatementTrackingService>();
_notifications = _vsProject.VisualStudioWorkspace.Services.GetService<INotificationService>();
_debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel));
_diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>();
_editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
Debug.Assert(_encService != null);
Debug.Assert(_trackingService != null);
Debug.Assert(_diagnosticProvider != null);
Debug.Assert(_editorAdaptersFactoryService != null);
}
// called from an edit filter if an edit of a read-only buffer is attempted:
internal bool OnEdit(DocumentId documentId)
{
SessionReadOnlyReason sessionReason;
ProjectReadOnlyReason projectReason;
if (_encService.IsProjectReadOnly(documentId.ProjectId, out sessionReason, out projectReason))
{
OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason);
return true;
}
return false;
}
private void OnReadOnlyDocumentEditAttempt(
DocumentId documentId,
SessionReadOnlyReason sessionReason,
ProjectReadOnlyReason projectReason)
{
if (sessionReason == SessionReadOnlyReason.StoppedAtException)
{
_debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState();
return;
}
var hostProject = _vsProject.VisualStudioWorkspace.GetHostProject(documentId.ProjectId) as AbstractEncProject;
if (hostProject?.EditAndContinueImplOpt?._metadata != null)
{
var projectHierarchy = _vsProject.VisualStudioWorkspace.GetHierarchy(documentId.ProjectId);
_debugEncNotify.NotifyEncEditDisallowedByProject(projectHierarchy);
return;
}
// NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586).
string message;
if (sessionReason == SessionReadOnlyReason.Running)
{
message = "Changes are not allowed while code is running.";
}
else
{
Debug.Assert(sessionReason == SessionReadOnlyReason.None);
switch (projectReason)
{
case ProjectReadOnlyReason.MetadataNotAvailable:
message = "Changes are not allowed if the project wasn't built when debugging started.";
break;
case ProjectReadOnlyReason.NotLoaded:
message = "Changes are not allowed if the assembly has not been loaded.";
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectReason);
}
}
_notifications.SendNotification(message, title: FeaturesResources.EditAndContinue, severity: NotificationSeverity.Error);
}
/// <summary>
/// Since we can't await asynchronous operations we need to wait for them to complete.
/// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to
/// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext
/// that doesn't pump messages. We need to make sure though that the async methods we wait for
/// don't dispatch to foreground thread, otherwise we would end up in a deadlock.
/// </summary>
private static VsThreading.SpecializedSyncContext NonReentrantContext
{
get
{
return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default);
}
}
public bool HasCustomMetadataEmitter()
{
return true;
}
/// <summary>
/// Invoked when the debugger transitions from Design mode to Run mode or Break mode.
/// </summary>
public int StartDebuggingPE()
{
try
{
log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid starting the debug session if it has already been started.
if (_encService.DebuggingSession == null)
{
Debug.Assert(s_debugStateProjectCount == 0);
Debug.Assert(s_breakStateProjectCount == 0);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run);
_encService.StartDebuggingSession(_vsProject.VisualStudioWorkspace.CurrentSolution);
s_encDebuggingSessionInfo = new EncDebuggingSessionInfo();
s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject);
}
string outputPath = _vsProject.TryGetObjOutputPath();
// The project doesn't produce a debuggable binary or we can't read it.
// Continue on since the debugger ignores HResults and we need to handle subsequent calls.
if (outputPath != null)
{
try
{
InjectFault_MvidRead();
_metadata = ModuleMetadata.CreateFromFile(outputPath);
_metadata.GetModuleVersionId();
}
catch (FileNotFoundException)
{
// If the project isn't referenced by the project being debugged it might not be built.
// In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state.
log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath);
_metadata = null;
}
catch (Exception e)
{
log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message);
_metadata = null;
var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.ErrorWhileReading, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue);
_diagnosticProvider.ReportDiagnostics(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId, _vsProject.Id, _encService.DebuggingSession.InitialSolution,
new[]
{
Diagnostic.Create(descriptor, Location.None, outputPath, e.Message)
});
}
}
else
{
log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName);
_metadata = null;
}
if (_metadata != null)
{
// The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID.
// However a project that's initially not loaded (but it might be in future) enters
// both the debug and break states.
s_debugStateProjectCount++;
}
_activeMethods = new HashSet<uint>();
_exceptionRegions = new List<VsExceptionRegion>();
_activeStatementIds = new Dictionary<uint, ActiveStatementId>();
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public int StopDebuggingPE()
{
try
{
log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
// Clear the solution stored while projects were entering break mode.
// It should be cleared as soon as all tracked projects enter the break mode
// but if the entering break mode fails for some projects we should avoid leaking the solution.
Debug.Assert(s_breakStateEntrySolution == null);
s_breakStateEntrySolution = null;
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid ending the debug session if it has already been ended.
if (_encService.DebuggingSession != null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design);
_encService.EndDebuggingSession();
LogEncSession();
s_encDebuggingSessionInfo = null;
s_readOnlyDocumentTracker.Dispose();
s_readOnlyDocumentTracker = null;
}
if (_metadata != null)
{
_metadata.Dispose();
_metadata = null;
s_debugStateProjectCount--;
}
else
{
// an error might have been reported:
_diagnosticProvider.ClearDiagnostics(_encService.DebuggingSession, _vsProject.VisualStudioWorkspace, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId, _vsProject.Id, documentId: null);
}
_activeMethods = null;
_exceptionRegions = null;
_committedBaseline = null;
_activeStatementIds = null;
Debug.Assert((_pdbReaderObjAsStream == IntPtr.Zero) || (_pdbReader == null));
if (_pdbReader != null)
{
Marshal.ReleaseComObject(_pdbReader);
_pdbReader = null;
}
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static void LogEncSession()
{
var sessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo));
foreach (var editSession in s_encDebuggingSessionInfo.EditSessions)
{
var editSessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession));
if (editSession.EmitDeltaErrorIds != null)
{
foreach (var error in editSession.EmitDeltaErrorIds)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error));
}
}
foreach (var rudeEdit in editSession.RudeEdits)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits));
}
}
}
/// <summary>
/// Get MVID and file name of the project's output file.
/// </summary>
/// <remarks>
/// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project.
/// The path seems to be unused.
///
/// The output file path might be different from the path of the module loaded into the process.
/// For example, the binary produced by the C# compiler is stores in obj directory,
/// and then copied to bin directory from which it is loaded to the debuggee.
///
/// The binary produced by the compiler can also be rewritten by post-processing tools.
/// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session
/// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though.
/// </remarks>
public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName)
{
Debug.Assert(_encService.DebuggingSession != null);
if (_metadata == null)
{
return VSConstants.E_FAIL;
}
if (pMVID != null && pMVID.Length != 0)
{
pMVID[0] = _metadata.GetModuleVersionId();
}
if (pbstrPEName != null && pbstrPEName.Length != 0)
{
var outputPath = _vsProject.TryGetObjOutputPath();
Debug.Assert(outputPath != null);
pbstrPEName[0] = Path.GetFileName(outputPath);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger when entering a Break state.
/// </summary>
/// <param name="encBreakReason">Reason for transition to Break state.</param>
/// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param>
/// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param>
public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements)
{
try
{
using (NonReentrantContext)
{
log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : "");
Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0));
Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount);
Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0);
Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count);
Debug.Assert(IsDebuggable);
if (s_breakStateEntrySolution == null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break);
s_breakStateEntrySolution = _vsProject.VisualStudioWorkspace.CurrentSolution;
// TODO: This is a workaround for a debugger bug in which not all projects exit the break state.
// Reset the project count.
s_breakStateProjectCount = 0;
}
ProjectReadOnlyReason state;
if (pActiveStatements != null)
{
AddActiveStatements(s_breakStateEntrySolution, pActiveStatements);
state = ProjectReadOnlyReason.None;
}
else
{
// unfortunately the debugger doesn't provide details:
state = ProjectReadOnlyReason.NotLoaded;
}
// If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding
// to the project in the debuggee. We won't include such projects in the edit session.
s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state));
s_breakStateProjectCount++;
// EnC service is global, but the debugger calls this for each project.
// Avoid starting the edit session until all projects enter break state.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
Debug.Assert(_encService.EditSession == null);
Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0));
var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>();
// note: fills in activeStatementIds of projects that own the active statements:
GroupActiveStatements(s_pendingActiveStatements, byDocument);
// When stopped at exception: All documents are read-only, but the files might be changed outside of VS.
// So we start an edit session as usual and report a rude edit for all changes we see.
bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION;
var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects);
_encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException);
_trackingService.StartTracking(_encService.EditSession);
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
// When tracking is started the tagger is notified and the active statements are highlighted.
// Add the handler that notifies the debugger *after* that initial tagger notification,
// so that it's not triggered unless an actual change in leaf AS occurs.
_trackingService.TrackingSpansChanged += TrackingSpansChanged;
}
}
// The debugger ignores the result.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
finally
{
// TODO: This is a workaround for a debugger bug.
// Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
// we don't need these anymore:
s_pendingActiveStatements.Clear();
s_breakStateEnteredProjects.Clear();
s_breakStateEntrySolution = null;
}
}
}
private void TrackingSpansChanged(bool leafChanged)
{
//log.Write("Tracking spans changed: {0}", leafChanged);
//if (leafChanged)
//{
// // fire and forget:
// Application.Current.Dispatcher.InvokeAsync(() =>
// {
// log.Write("Notifying debugger of active statement change.");
// var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
// debugNotify.NotifyEncUpdateCurrentStatement();
// });
//}
}
private struct VsActiveStatement
{
public readonly DocumentId DocumentId;
public readonly uint StatementId;
public readonly ActiveStatementSpan Span;
public readonly VsENCRebuildableProjectImpl Owner;
public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span)
{
this.Owner = owner;
this.StatementId = statementId;
this.DocumentId = documentId;
this.Span = span;
}
}
private struct VsExceptionRegion
{
public readonly uint ActiveStatementId;
public readonly int Ordinal;
public readonly uint MethodToken;
public readonly LinePositionSpan Span;
public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span)
{
this.ActiveStatementId = activeStatementId;
this.Span = span;
this.MethodToken = methodToken;
this.Ordinal = ordinal;
}
}
// See InternalApis\vsl\inc\encbuild.idl
private const int TEXT_POSITION_ACTIVE_STATEMENT = 1;
private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements)
{
Debug.Assert(_activeMethods.Count == 0);
Debug.Assert(_exceptionRegions.Count == 0);
foreach (var vsActiveStatement in vsActiveStatements)
{
log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'",
vsActiveStatement.id,
vsActiveStatement.tsPosition.iStartLine,
vsActiveStatement.tsPosition.iStartIndex,
vsActiveStatement.tsPosition.iEndLine,
vsActiveStatement.tsPosition.iEndIndex,
vsActiveStatement.filename);
// TODO (tomat):
// Active statement is in user hidden code. The only information that we have from the debugger
// is the method token. We don't need to track the statement (it's not in user code anyways),
// but we should probably track the list of such methods in order to preserve their local variables.
// Not sure what's exactly the scenario here, perhaps modifying async method/iterator?
// Dev12 just ignores these.
if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT)
{
continue;
}
var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO;
IVisualStudioHostDocument vsDocument = _vsProject.GetCurrentDocumentFromPath(vsActiveStatement.filename);
if (vsDocument != null)
{
var document = solution.GetDocument(vsDocument.Id);
Debug.Assert(document != null);
SourceText source = document.GetTextAsync(default(CancellationToken)).Result;
LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan();
// If the PDB is out of sync with the source we might get bad spans.
var sourceLines = source.Lines;
if (lineSpan.End.Line >= sourceLines.Count || lineSpan.End.Character > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak)
{
log.Write("AS out of bounds (line count is {0})", source.Lines.Count);
continue;
}
SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result;
var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>();
s_pendingActiveStatements.Add(new VsActiveStatement(
this,
vsActiveStatement.id,
document.Id,
new ActiveStatementSpan(flags, lineSpan)));
bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0;
var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf);
for (int i = 0; i < ehRegions.Length; i++)
{
_exceptionRegions.Add(new VsExceptionRegion(
vsActiveStatement.id,
i,
vsActiveStatement.methodToken,
ehRegions[i]));
}
}
_activeMethods.Add(vsActiveStatement.methodToken);
}
}
private static void GroupActiveStatements(
IEnumerable<VsActiveStatement> activeStatements,
Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument)
{
var spans = new List<ActiveStatementSpan>();
foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId))
{
var documentId = grouping.Key;
foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start))
{
int ordinal = spans.Count;
// register vsid with the project that owns the active statement:
activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal));
spans.Add(activeStatement.Span);
}
byDocument.Add(documentId, spans.AsImmutable());
spans.Clear();
}
}
/// <summary>
/// Returns the number of exception regions around current active statements.
/// This is called when the project is entering a break right after
/// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpanCount(out uint pcExceptionSpan)
{
pcExceptionSpan = (uint)_exceptionRegions.Count;
return VSConstants.S_OK;
}
/// <summary>
/// Returns information about exception handlers in the source.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched)
{
Debug.Assert(celt == rgelt.Length);
Debug.Assert(celt == _exceptionRegions.Count);
for (int i = 0; i < _exceptionRegions.Count; i++)
{
rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN()
{
id = (uint)i,
methodToken = _exceptionRegions[i].MethodToken,
tsPosition = _exceptionRegions[i].Span.ToVsTextSpan()
};
}
pceltFetched = celt;
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger whenever it needs to determine a position of an active statement.
/// E.g. the user clicks on a frame in a call stack.
/// </summary>
/// <remarks>
/// Called when applying change, when setting current IP, a notification is received from
/// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc.
/// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components.
/// </remarks>
public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
var session = _encService.EditSession;
var ids = _activeStatementIds;
// Can be called anytime, even outside of an edit/debug session.
// We might not have an active statement available if PDB got out of sync with the source.
ActiveStatementId id;
if (session == null || ids == null || !ids.TryGetValue(vsId, out id))
{
log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", vsId);
return VSConstants.E_FAIL;
}
Document document = _vsProject.VisualStudioWorkspace.CurrentSolution.GetDocument(id.DocumentId);
SourceText text = document.GetTextAsync(default(CancellationToken)).Result;
// Try to get spans from the tracking service first.
// We might get an imprecise result if the document analysis hasn't been finished yet and
// the active statement has structurally changed, but that's ok. The user won't see an updated tag
// for the statement until the analysis finishes anyways.
TextSpan span;
LinePositionSpan lineSpan;
if (_trackingService.TryGetSpan(id, text, out span) && span.Length > 0)
{
lineSpan = text.Lines.GetLinePositionSpan(span);
}
else
{
var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements;
if (activeSpans.IsDefault)
{
// The document has syntax errors and the tracking span is gone.
log.Write("Position not available for AS {0} due to syntax errors", vsId);
return VSConstants.E_FAIL;
}
lineSpan = activeSpans[id.Ordinal];
}
ptsNewPosition[0] = lineSpan.ToVsTextSpan();
log.DebugWrite("AS position: {0} {1} {2}", vsId, lineSpan,
session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags);
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Returns the state of the changes made to the source.
/// The EnC manager calls this to determine whether there are any changes to the source
/// and if so whether there are any rude edits.
/// </summary>
public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1);
// GetENCBuildState is called outside of edit session (at least) in following cases:
// 1) when the debugger is determining whether a source file checksum matches the one in PDB.
// 2) when the debugger is setting the next statement and a change is pending
// See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange):
//
// pENC2->ExitBreakState();
// >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true);
// pENC2->EnterBreakState(m_pSession, GetEncBreakReason());
//
// The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur.
if (_changesApplied || _encService.EditSession == null)
{
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
}
else
{
// Fetch the latest snapshot of the project and get an analysis summary for any changes
// made since the break mode was entered.
var currentProject = _vsProject.VisualStudioWorkspace.CurrentSolution.GetProject(_vsProject.Id);
if (currentProject == null)
{
// If the project has yet to be loaded into the solution (which may be the case,
// since they are loaded on-demand), then it stands to reason that it has not yet
// been modified.
// TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary.
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
log.Write($"Project '{_vsProject.DisplayName}' has not yet been loaded into the solution");
}
else
{
_projectBeingEmitted = currentProject;
_lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted);
}
_encService.EditSession.LogBuildState(_lastEditSessionSummary);
}
switch (_lastEditSessionSummary)
{
case ProjectAnalysisSummary.NoChanges:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED;
break;
case ProjectAnalysisSummary.CompilationErrors:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS;
break;
case ProjectAnalysisSummary.RudeEdits:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS;
break;
case ProjectAnalysisSummary.ValidChanges:
case ProjectAnalysisSummary.ValidInsignificantChanges:
// The debugger doesn't distinguish between these two.
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY;
break;
default:
throw ExceptionUtilities.Unreachable;
}
log.Write("EnC state of '{0}' queried: {1}{2}",
_vsProject.DisplayName,
pENCBuildState[0],
_encService.EditSession != null ? "" : " (no session)");
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project)
{
if (!IsDebuggable)
{
return ProjectAnalysisSummary.NoChanges;
}
var cancellationToken = default(CancellationToken);
return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result;
}
public int ExitBreakStateOnPE()
{
try
{
using (NonReentrantContext)
{
// The debugger calls Exit without previously calling Enter if the project's MVID isn't available.
if (!IsDebuggable)
{
return VSConstants.S_OK;
}
log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global, but the debugger calls this for each project.
// Avoid ending the edit session if it has already been ended.
if (_encService.EditSession != null)
{
Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run);
_encService.EditSession.LogEditSession(s_encDebuggingSessionInfo);
_encService.EndEditSession();
_trackingService.EndTracking();
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
_trackingService.TrackingSpansChanged -= TrackingSpansChanged;
}
_exceptionRegions.Clear();
_activeMethods.Clear();
_activeStatementIds.Clear();
s_breakStateProjectCount--;
Debug.Assert(s_breakStateProjectCount >= 0);
_changesApplied = false;
_diagnosticProvider.ClearDiagnostics(_encService.DebuggingSession, _vsProject.VisualStudioWorkspace, EditAndContinueDiagnosticUpdateSource.EmitErrorId, _vsProject.Id, _documentsWithEmitError);
_documentsWithEmitError = default(ImmutableArray<DocumentId>);
}
// HResult ignored by the debugger
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public unsafe int BuildForEnc(object pUpdatePE)
{
try
{
log.Write("Applying changes to {0}", _vsProject.DisplayName);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
// Non-debuggable project has no changes.
Debug.Assert(IsDebuggable);
if (_changesApplied)
{
log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName);
throw ExceptionUtilities.Unreachable;
}
// The debugger always calls GetENCBuildState right before BuildForEnc.
Debug.Assert(_projectBeingEmitted != null);
Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted));
// The debugger should have called GetENCBuildState before calling BuildForEnc.
// Unfortunately, there is no way how to tell the debugger that the changes were not significant,
// so we'll to emit an empty delta. See bug 839558.
Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges ||
_lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges);
var updater = (IDebugUpdateInMemoryPE2)pUpdatePE;
if (_committedBaseline == null)
{
var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream);
if (hr != VSConstants.S_OK)
{
return hr;
}
_committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo);
}
// ISymUnmanagedReader can only be accessed from an MTA thread,
// so dispatch it to one of thread pool threads, which are MTA.
var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default);
Deltas delta;
using (NonReentrantContext)
{
delta = emitTask.Result;
}
// Clear diagnostics, in case the project was built before and failed due to errors.
_diagnosticProvider.ClearDiagnostics(_encService.DebuggingSession, _vsProject.VisualStudioWorkspace, EditAndContinueDiagnosticUpdateSource.EmitErrorId, _vsProject.Id, _documentsWithEmitError);
if (!delta.EmitResult.Success)
{
var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error);
_documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(
_encService.DebuggingSession,
EditAndContinueDiagnosticUpdateSource.EmitErrorId,
_vsProject.Id,
_projectBeingEmitted.Solution,
errors);
_encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id));
return VSConstants.E_FAIL;
}
_documentsWithEmitError = default(ImmutableArray<DocumentId>);
SetFileUpdates(updater, delta.LineEdits);
updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length);
updater.SetDeltaPdb(new ComStreamWrapper(delta.Pdb.Stream));
updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length);
updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length);
_pendingBaseline = delta.EmitResult.Baseline;
#if DEBUG
fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0])
{
var reader = new MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length);
var moduleDef = reader.GetModuleDefinition();
log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}",
moduleDef.Generation,
reader.GetGuid(moduleDef.Mvid),
reader.GetGuid(moduleDef.BaseGenerationId),
reader.GetGuid(moduleDef.GenerationId));
}
#endif
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private unsafe void SetFileUpdates(
IDebugUpdateInMemoryPE2 updater,
List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits)
{
int totalEditCount = edits.Sum(e => e.Value.Length);
if (totalEditCount == 0)
{
return;
}
var lineUpdates = new LINEUPDATE[totalEditCount];
fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates)
{
int index = 0;
var fileUpdates = new FILEUPDATE[edits.Count];
for (int f = 0; f < fileUpdates.Length; f++)
{
var documentId = edits[f].Key;
var deltas = edits[f].Value;
fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath;
fileUpdates[f].LineUpdateCount = (uint)deltas.Length;
fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index);
for (int l = 0; l < deltas.Length; l++)
{
lineUpdates[index + l].Line = (uint)deltas[l].OldLine;
lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine;
}
index += deltas.Length;
}
// The updater makes a copy of all data, we can release the buffer after the call.
updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length);
}
}
private Deltas EmitProjectDelta()
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken));
return emitTask.Result;
}
private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle)
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
if (_pdbReader == null)
{
// Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA).
Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero);
object pdbReaderObjMta;
int hr = NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out pdbReaderObjMta);
_pdbReaderObjAsStream = IntPtr.Zero;
if (hr != VSConstants.S_OK)
{
log.Write("Error unmarshaling object from stream.");
return default(EditAndContinueMethodDebugInformation);
}
_pdbReader = (ISymUnmanagedReader)pdbReaderObjMta;
}
int methodToken = MetadataTokens.GetToken(methodHandle);
byte[] debugInfo = _pdbReader.GetCustomDebugInfoBytes(methodToken, methodVersion: 1);
if (debugInfo != null)
{
try
{
var localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap);
var lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap);
return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap);
}
catch (Exception e) when (e is InvalidOperationException || e is InvalidDataException)
{
log.Write($"Error reading CDI of method 0x{methodToken:X8}: {e.Message}");
}
}
return default(EditAndContinueMethodDebugInformation);
}
public int EncApplySucceeded(int hrApplyResult)
{
try
{
log.Write("Change applied to {0}", _vsProject.DisplayName);
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(_pendingBaseline != null);
// Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges.
_changesApplied = true;
_committedBaseline = _pendingBaseline;
_pendingBaseline = null;
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Called when changes are being applied.
/// </summary>
/// <param name="exceptionRegionId">
/// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>.
/// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>.
/// </param>
/// <param name="ptsNewPosition">Output value holder.</param>
public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(ptsNewPosition.Length == 1);
var exceptionRegion = _exceptionRegions[(int)exceptionRegionId];
var session = _encService.EditSession;
var asid = _activeStatementIds[exceptionRegion.ActiveStatementId];
var document = _projectBeingEmitted.GetDocument(asid.DocumentId);
var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken));
var regions = analysis.ExceptionRegions;
// the method shouldn't be called in presence of errors:
Debug.Assert(!analysis.HasChangesAndErrors);
Debug.Assert(!regions.IsDefault);
// Absence of rude edits guarantees that the exception regions around AS haven't semantically changed.
// Only their spans might have changed.
ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan();
}
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer)
{
// ISymUnmanagedReader can only be accessed from an MTA thread, however, we need
// fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here
// in the STA. To further complicate things, we need to return synchronously from
// this method. Waiting for the MTA thread to complete so we can return synchronously
// blocks the STA thread, so we need to make sure the CLR doesn't try to marshal
// ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this
// happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to
// achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer
// over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal
// the object. The reader object was originally created on an MTA thread, and the
// instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the
// MTA, it "unwraps" the proxy, allowing us to directly call the implementation.
// Another way to achieve this would be for the symbol reader to implement IAgileObject,
// but the symbol reader we use today does not. If that changes, we should consider
// removing this marshal/unmarshal code.
IENCDebugInfo debugInfo;
updater.GetENCDebugInfo(out debugInfo);
var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo;
object pdbReaderObjSta;
symbolReaderProvider.GetSymbolReader(out pdbReaderObjSta);
int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer);
Marshal.ReleaseComObject(pdbReaderObjSta);
return hr;
}
#region Testing
#if DEBUG
// Fault injection:
// If set we'll fail to read MVID of specified projects to test error reporting.
internal static ImmutableArray<string> InjectMvidReadingFailure;
private void InjectFault_MvidRead()
{
if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName))
{
throw new IOException("Fault injection");
}
}
#else
[Conditional("DEBUG")]
private void InjectFault_MvidRead()
{
}
#endif
#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.
////////////////////////////////////////////////////////////////
//
// Description
// ____________
// On IA64 if the only use of a parameter is assigning to it
// inside and EH clause and the parameter is a GC pointer, then
// the JIT reports a stack slot as live for the duration of the method,
// but never initializes it. Sort of the inverse of a GC hole.
// Thus the runtime sees random stack garbage as a GC pointer and
// bad things happen. Workarounds include using the parameter,
// assinging to a different local, removing the assignment (since
// it has no subsequent uses).
//
//
// Right Behavior
// ________________
// No Assertion
//
// Wrong Behavior
// ________________
// Assertion
//
// Commands to issue
// __________________
// > test1.exe
//
// External files
// _______________
// None
////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Runtime.InteropServices;
class ApplicationException : Exception { }
#pragma warning disable 1917,1918
public enum TestEnum
{
red = 1,
green = 2,
blue = 4,
}
public class AA<TA, TB, TC, TD, TE, TF>
where TA : IComparable where TB : IComparable where TC : IComparable where TD : IComparable where TE : IComparable
{
public TC m_aguiGeneric1;
public short[][][] Method1(uint[,,,] param1, ref TestEnum param2)
{
uint local1 = ((uint)(((ulong)(17.0f))));
double local2 = ((double)(((ulong)(113.0f))));
String[] local3 = new String[] { "113", "92", "26", "24" };
while (Convert.ToBoolean(((short)(local1))))
{
local3[23] = "69";
do
{
char[][] local4 = new char[][]{(new char[48u]), new char[]{'\x3f', '\x00',
'\x47' }, new char[]{'\x58', '\x39', '\x70', '\x31' }, (new char[48u]),
new char[]{'\x62', '\x6b', '\x19', '\x30', '\x17' } };
local3 = ((String[])(((Array)(null))));
while ((((short)(local2)) == ((short)(local2))))
{
for (App.m_byFwd1 = App.m_byFwd1; ((bool)(((object)(new BB())))); local1--)
{
do
{
while (Convert.ToBoolean((local1 >> 100)))
{
local2 = local2;
}
while ((new AA<TA, TB, TC, TD, TE, TF>() == new
AA<TA, TB, TC, TD, TE, TF>()))
{
if (((bool)(((object)(new AA<TA, TB, TC, TD, TE, TF>())))))
param1 = (new uint[local1, 107u, 22u, local1]);
if (((bool)(((object)(param2)))))
continue;
if (App.m_bFwd2)
continue;
if ((/*2 REFS*/((byte)(local1)) != /*2 REFS*/((byte)(local1))))
{
throw new ApplicationException();
}
}
local1 -= 88u;
while (((bool)(((object)(local2)))))
{
}
if (Convert.ToBoolean(((int)(local2))))
do
{
}
while (App.m_bFwd2);
else
{
}
}
while ((null != new AA<TA, TB, TC, TD, TE, TF>()));
local4 = (local4 = (local4 = new char[][]{(new char[local1]), (new char[
local1]), (new char[113u]) }));
do
{
}
while (Convert.ToBoolean(local2));
for (App.m_byFwd1 = ((byte)(local1)); ((bool)(((object)(local1)))); local2
-= (local2 + local2))
{
}
while (Convert.ToBoolean(((short)(local1))))
{
}
}
if (((bool)(((object)(new BB())))))
{
}
else
for (App.m_iFwd3 -= 33; ((bool)(((object)(local2)))); App.m_bFwd2 = App.
m_bFwd2)
{
}
}
for (App.m_iFwd3 /= (Convert.ToByte(33.0) ^ ((byte)(local1))); App.m_bFwd2;
App.m_shFwd4 = ((short)(((sbyte)(local2)))))
{
}
while (App.m_bFwd2)
{
}
break;
}
while ((/*2 REFS*/((object)(new BB())) != ((AA<TA, TB, TC, TD, TE, TF>)(
/*2 REFS*/((object)(new BB()))))));
for (App.m_iFwd3 = 60; ((bool)(((object)(new BB())))); local2 = local2)
{
}
local3 = ((String[])(((object)(local2))));
}
local3[((int)(((byte)(65))))] = "47";
try
{
}
catch (IndexOutOfRangeException)
{
}
return new short[][][]{/*2 REFS*/(new short[36u][]), new short[][]{ },
/*2 REFS*/
(new short[36u][]) };
}
public static ulong Static1(TF param1)
{
byte local5 = ((byte)(((long)(69.0))));
float[,][,] local6 = (new float[9u, 6u][,]);
TestEnum local7 = TestEnum.blue;
do
{
bool[,,,,][,] local8 = (new bool[81u, 98u, ((uint)(58.0f)), ((uint)(36.0f)),
74u*4u][,]);
while ((((uint)(local5)) != 4u))
{
if (Convert.ToBoolean((local5 + local5)))
local6 = (new float[((uint)(116.0)), 94u][,]);
else
for (App.m_iFwd3 -= 97; Convert.ToBoolean(((ushort)(local5))); App.m_ushFwd5
= Math.Max(((ushort)(26)), ((ushort)(43))))
{
local7 = local7;
}
}
local8[69, 1, 61, 62, 122][24, 40] = true;
local8[97, (((short)(115)) >> ((ushort)(local5))), 29, 29, ((int)(((ulong)(
local5))))][((int)(((long)(119u)))), 52] = false;
try
{
param1 = param1;
param1 = param1;
while ((/*2 REFS*/((sbyte)(local5)) == /*2 REFS*/((sbyte)(local5))))
{
try
{
throw new IndexOutOfRangeException();
}
catch (InvalidOperationException)
{
try
{
while (((bool)(((object)(local7)))))
{
return ((ulong)(((int)(7u))));
}
while ((new AA<TA, TB, TC, TD, TE, TF>() == new
AA<TA, TB, TC, TD, TE, TF>()))
{
local7 = local7;
local5 = (local5 += local5);
}
while (((bool)(((object)(local5)))))
{
}
goto label1;
}
catch (InvalidOperationException)
{
}
do
{
}
while ((new AA<TA, TB, TC, TD, TE, TF>() == new AA<TA, TB, TC, TD, TE, TF>(
)));
label1:
try
{
}
catch (Exception)
{
}
}
for (App.m_fFwd6 = App.m_fFwd6; ((bool)(((object)(new BB())))); App.m_dblFwd7
/= 94.0)
{
}
for (App.m_shFwd4--; App.m_bFwd2; App.m_ulFwd8 = ((ulong)(((ushort)(local5))
)))
{
}
local7 = local7;
local8[((int)(Convert.ToUInt64(26.0))), 60, ((int)(((long)(local5)))), ((
int)(local5)), 96] = (new bool[((uint)(48.0)), 97u]);
}
param1 = (param1 = param1);
}
finally
{
}
local8 = local8;
}
while (((bool)(((object)(local7)))));
if ((local5 == (local5 -= local5)))
while ((((Array)(null)) != ((object)(local7))))
{
}
else
{
}
for (App.m_dblFwd7++; App.m_bFwd2; App.m_chFwd9 += '\x69')
{
}
return ((ulong)(105));
}
public static char[] Static2(ulong param1, short param2, ref uint param3, ref
TA param4)
{
long[,,,,][,,][][,,,] local9 = (new long[((uint)(5.0)), 24u, 65u, 9u, 29u]
[,,][][,,,]);
char local10 = ((char)(97));
double local11 = 102.0;
sbyte[,][,,,][] local12 = (new sbyte[41u, 15u][,,,][]);
try
{
local12[26, 65] = ((sbyte[,,,][])(((object)(new AA<TA, TB, TC, TD, TE, TF>()
))));
try
{
do
{
do
{
do
{
try
{
do
{
try
{
local11 *= 27.0;
try
{
if (Convert.ToBoolean(((ushort)(param1))))
for (App.m_ushFwd5 /= ((ushort)(17.0f)); (new
AA<TA, TB, TC, TD, TE, TF>() != new AA<TA, TB, TC, TD, TE, TF>());
App.m_ushFwd5 *= ((ushort)(((sbyte)(param1)))))
{
}
}
catch (IndexOutOfRangeException)
{
}
do
{
}
while (((bool)(((object)(param1)))));
}
catch (InvalidOperationException)
{
}
}
while (("95" == Convert.ToString(local10)));
local11 -= ((double)(30));
while (((bool)(((object)(local10)))))
{
}
}
catch (NullReferenceException)
{
}
try
{
}
catch (InvalidOperationException)
{
}
param3 /= ((param3 /= param3) / param3);
}
while ((((long)(param2)) != (55 | param3)));
local10 = ((char)(((object)(local10))));
param1 *= ((ulong)(((ushort)(54u))));
try
{
}
catch (ApplicationException)
{
}
param4 = (param4 = param4);
}
while ((param2 == param2));
do
{
}
while (((bool)(((object)(new AA<TA, TB, TC, TD, TE, TF>())))));
throw new DivideByZeroException();
}
while ((param3 == (65u / param3)));
do
{
}
while ((((sbyte)(local11)) == ((sbyte)(local11))));
local12[116, ((int)((param2 *= param2)))] = (new sbyte[((uint)(param2)), (
param3 += param3), 67u, 116u][]);
try
{
}
finally
{
}
}
finally
{
}
for (App.m_lFwd10 = (60 * param3); ((bool)(((object)(local10)))); local11--)
{
}
local12 = (local12 = (local12 = local12));
}
catch (IndexOutOfRangeException)
{
}
local9 = local9;
param1 *= (param1 >> ((ushort)(30)));
return new char[] { (local10 = local10), local10, (local10 = local10), '\x7e' };
}
public static sbyte[][][,,,,][][,,] Static3(TestEnum param1, short param2)
{
param1 = param1;
do
{
sbyte local13 = ((sbyte)(89.0));
double local14 = 103.0;
uint[,][][,,][,] local15 = (new uint[92u, 102u][][,,][,]);
short[][,,,][,][] local16 = (new short[32u][,,,][,][]);
local15[((int)(((float)(69.0)))), 9][((int)(((ushort)(75.0f))))][((int)(66u))
, (((byte)(local13)) ^ ((byte)(param2))), ((local13 << local13) << ((ushort
)(local13)))][((int)(63u)), ((int)(((char)(8))))] *= 82u;
param1 = (param1 = param1);
}
while (((bool)(((object)(param1)))));
param1 = param1;
param2 = (param2 /= (param2 = param2));
return (new sbyte[36u][][,,,,][][,,]);
}
public static long[][,,] Static4(char param1)
{
sbyte[][] local17 = ((sbyte[][])(((Array)(null))));
ulong[,,] local18 = ((ulong[,,])(((Array)(null))));
sbyte[][] local19 = new sbyte[][] { (new sbyte[16u]), (new sbyte[126u]) };
byte local20 = ((byte)(((sbyte)(90u))));
return (new long[15u][,,]);
}
public static int Static5(ref TE param1, ref char[][,,,] param2, Array param3,
ref ulong[,,,,] param4, ref long[,,,][][][][,] param5)
{
BB[] local21 = ((BB[])(((Array)(null))));
sbyte local22 = ((sbyte)(121));
bool local23 = (new AA<TA, TB, TC, TD, TE, TF>() == new
AA<TA, TB, TC, TD, TE, TF>());
object[][,,][][,,][,] local24 = (new object[115u][,,][][,,][,]);
while (local23)
{
param1 = param1;
while (local23)
{
try
{
local23 = false;
}
catch (ApplicationException)
{
param2[1] = (new char[57u, ((uint)(68)), 104u, ((uint)(local22))]);
try
{
local22 = local22;
do
{
do
{
local21[((int)(((long)(102u))))].m_achField1[((int)(local22))] = ((
char[,])(((object)(new BB()))));
param3 = ((Array)(null));
throw new IndexOutOfRangeException();
}
while (local23);
param3 = ((Array)(null));
local22 = local22;
local22 = (local22 *= local22);
while ((local23 && (null != new AA<TA, TB, TC, TD, TE, TF>())))
{
for (local22 = local22; local23; App.m_abyFwd11 = App.m_abyFwd11)
{
while (local23)
{
}
}
local22 = local22;
}
}
while ((/*3 REFS*/((uint)(local22)) != (local23 ?/*3 REFS*/((uint)(local22))
:/*3 REFS*/((uint)(local22)))));
local21[38].m_achField1 = new char[][,]{((char[,])(param3)), (new char[
102u, 36u]) };
}
catch (DivideByZeroException)
{
}
local21 = local21;
}
try
{
}
catch (Exception)
{
}
throw new InvalidOperationException();
}
try
{
}
catch (ApplicationException)
{
}
for (App.m_uFwd12--; local23; App.m_lFwd10 /= ((long)(((short)(28u)))))
{
}
}
param5 = (new long[108u, 115u, 20u, 126u][][][][,]);
local21[(((ushort)(local22)) << ((int)(local22)))].m_achField1[101] = (new
char[21u, 43u]);
for (App.m_shFwd4 = ((short)(76.0f)); ((bool)(((object)(local23)))); App.
m_chFwd9 *= '\x67')
{
}
if (local23)
try
{
}
catch (InvalidOperationException)
{
}
else
while (local23)
{
}
return 83;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct BB
{
public char[][,] m_achField1;
public void Method1(ref uint[][][,] param1, ref String[][] param2, ref char[,]
param3, AA<sbyte, byte, uint, uint, long, bool> param4, ref
AA<sbyte, byte, uint, uint, long, bool> param5, int param6)
{
do
{
ushort[] local25 = (new ushort[62u]);
do
{
BB local26 = ((BB)(((object)(new AA<sbyte, byte, uint, uint, long, bool>()))
));
param4.m_aguiGeneric1 = new AA<sbyte, byte, uint, uint, long, bool>().
m_aguiGeneric1;
try
{
ulong[,,][] local27 = ((ulong[,,][])(((Array)(null))));
ushort[,] local28 = (new ushort[8u, 8u]);
if ((/*2 REFS*/((short)(param6)) == /*2 REFS*/((short)(param6))))
while (App.m_bFwd2)
{
for (App.m_ushFwd5--; App.m_bFwd2; App.m_ulFwd8--)
{
param1 = param1;
}
AA<sbyte, byte, uint, uint, long, bool>.Static3(
TestEnum.blue,
App.m_shFwd4);
param1[(5 ^ param6)][param6] = (new uint[2u, ((uint)(param6))]);
}
else
local28[param6, (((ushort)(param6)) << ((sbyte)(47)))] += ((ushort)(((
ulong)(25u))));
while (((bool)(((object)(param4)))))
{
AA<sbyte, byte, uint, uint, long, bool>.Static2(
((ulong)(114.0)),
((short)(((long)(49.0f)))),
ref App.m_uFwd12,
ref App.m_gsbFwd13);
try
{
if ((null == new AA<sbyte, byte, uint, uint, long, bool>()))
if ((((char)(25)) != ((char)(param6))))
if (App.m_bFwd2)
try
{
param6 /= param6;
while ((((long)(44u)) != ((long)(param6))))
{
try
{
}
catch (InvalidOperationException)
{
}
do
{
}
while (App.m_bFwd2);
local25 = local25;
for (App.m_shFwd4 -= App.m_shFwd4; Convert.ToBoolean(param6); App.
m_byFwd1 *= Math.Max(((byte)(9u)), ((byte)(40u))))
{
}
}
local25[12] = App.m_ushFwd5;
local28 = (new ushort[111u, 80u]);
for (App.m_dblFwd7 = App.m_dblFwd7; (param6 == ((int)(101.0))); param6
*= param6)
{
}
}
catch (IndexOutOfRangeException)
{
}
param1 = param1;
param2[param6] = ((String[])(((Array)(null))));
try
{
}
catch (ApplicationException)
{
}
}
finally
{
}
}
}
catch (Exception)
{
}
}
while (App.m_bFwd2);
for (App.m_xFwd14 = App.m_xFwd14; ((param6 - (0.0f)) == 86.0f); App.m_fFwd6 += (
108u - ((float)(param6))))
{
}
if ((((object)(new AA<sbyte, byte, uint, uint, long, bool>())) == "32"))
param5.m_aguiGeneric1 = new AA<sbyte, byte, uint, uint, long, bool>().
m_aguiGeneric1;
else
do
{
}
while (((bool)(((object)(new AA<sbyte, byte, uint, uint, long, bool>())))));
if (App.m_bFwd2)
{
}
}
while (Convert.ToBoolean(param6));
param5.m_aguiGeneric1 = (param4 = param4).m_aguiGeneric1;
do
{
}
while (Convert.ToBoolean(param6));
;
}
}
public class App
{
private static int Main()
{
try
{
Console.WriteLine("Testing AA::Method1");
((AA<sbyte, byte, uint, uint, long, bool>)(((object)(new BB())))).Method1(
(new uint[12u, 115u, 95u, 13u]),
ref App.m_xFwd15);
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
try
{
Console.WriteLine("Testing AA::Static1");
AA<sbyte, byte, uint, uint, long, bool>.Static1(App.m_agboFwd16);
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
try
{
Console.WriteLine("Testing AA::Static2");
AA<sbyte, byte, uint, uint, long, bool>.Static2(
((ulong)(((ushort)(10.0)))),
((short)(70.0)),
ref App.m_uFwd12,
ref App.m_gsbFwd13);
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
try
{
Console.WriteLine("Testing AA::Static3");
AA<sbyte, byte, uint, uint, long, bool>.Static3(
TestEnum.green,
((short)(((sbyte)(69.0)))));
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
try
{
Console.WriteLine("Testing AA::Static4");
AA<sbyte, byte, uint, uint, long, bool>.Static4('\x02');
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
try
{
Console.WriteLine("Testing AA::Static5");
AA<sbyte, byte, uint, uint, long, bool>.Static5(
ref App.m_aglFwd17,
ref App.m_achFwd18,
((Array)(null)),
ref App.m_aulFwd19,
ref App.m_alFwd20);
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
try
{
Console.WriteLine("Testing BB::Method1");
new BB().Method1(
ref App.m_auFwd21,
ref App.m_axFwd22,
ref App.m_achFwd23,
new AA<sbyte, byte, uint, uint, long, bool>(),
ref App.m_axFwd24,
87);
}
catch (Exception x)
{
Console.WriteLine("Exception handled: " + x.ToString());
}
Console.WriteLine("Passed.");
return 100;
}
public static byte m_byFwd1;
public static bool m_bFwd2;
public static int m_iFwd3;
public static short m_shFwd4;
public static ushort m_ushFwd5;
public static float m_fFwd6;
public static double m_dblFwd7;
public static ulong m_ulFwd8;
public static char m_chFwd9;
public static long m_lFwd10;
public static byte[] m_abyFwd11;
public static uint m_uFwd12;
public static sbyte m_gsbFwd13;
public static Array m_xFwd14;
public static TestEnum m_xFwd15;
public static bool m_agboFwd16;
public static long m_aglFwd17;
public static char[][,,,] m_achFwd18;
public static ulong[,,,,] m_aulFwd19;
public static long[,,,][][][][,] m_alFwd20;
public static uint[][][,] m_auFwd21;
public static String[][] m_axFwd22;
public static char[,] m_achFwd23;
public static AA<sbyte, byte, uint, uint, long, bool> m_axFwd24;
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Camera/Depth of Field (Lens Blur, Scatter, DX11)") ]
public class DepthOfField : PostEffectsBase {
public bool visualizeFocus = false;
public float focalLength = 10.0f;
public float focalSize = 0.05f;
public float aperture = 11.5f;
public Transform focalTransform = null;
public float maxBlurSize = 2.0f;
public bool highResolution = false;
public enum BlurType {
DiscBlur = 0,
DX11 = 1,
}
public enum BlurSampleCount {
Low = 0,
Medium = 1,
High = 2,
}
public BlurType blurType = BlurType.DiscBlur;
public BlurSampleCount blurSampleCount = BlurSampleCount.High;
public bool nearBlur = false;
public float foregroundOverlap = 1.0f;
public Shader dofHdrShader;
private Material dofHdrMaterial = null;
public Shader dx11BokehShader;
private Material dx11bokehMaterial;
public float dx11BokehThreshold = 0.5f;
public float dx11SpawnHeuristic = 0.0875f;
public Texture2D dx11BokehTexture = null;
public float dx11BokehScale = 1.2f;
public float dx11BokehIntensity = 2.5f;
private float focalDistance01 = 10.0f;
private ComputeBuffer cbDrawArgs;
private ComputeBuffer cbPoints;
private float internalBlurWidth = 1.0f;
public override bool CheckResources () {
CheckSupport (true); // only requires depth, not HDR
dofHdrMaterial = CheckShaderAndCreateMaterial (dofHdrShader, dofHdrMaterial);
if (supportDX11 && blurType == BlurType.DX11) {
dx11bokehMaterial = CheckShaderAndCreateMaterial(dx11BokehShader, dx11bokehMaterial);
CreateComputeResources ();
}
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnEnable () {
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
void OnDisable () {
ReleaseComputeResources ();
if (dofHdrMaterial) DestroyImmediate(dofHdrMaterial);
dofHdrMaterial = null;
if (dx11bokehMaterial) DestroyImmediate(dx11bokehMaterial);
dx11bokehMaterial = null;
}
void ReleaseComputeResources () {
if (cbDrawArgs != null) cbDrawArgs.Release();
cbDrawArgs = null;
if (cbPoints != null) cbPoints.Release();
cbPoints = null;
}
void CreateComputeResources () {
if (cbDrawArgs == null)
{
cbDrawArgs = new ComputeBuffer (1, 16, ComputeBufferType.IndirectArguments);
var args= new int[4];
args[0] = 0; args[1] = 1; args[2] = 0; args[3] = 0;
cbDrawArgs.SetData (args);
}
if (cbPoints == null)
{
cbPoints = new ComputeBuffer (90000, 12+16, ComputeBufferType.Append);
}
}
float FocalDistance01 ( float worldDist) {
return GetComponent<Camera>().WorldToViewportPoint((worldDist-GetComponent<Camera>().nearClipPlane) * GetComponent<Camera>().transform.forward + GetComponent<Camera>().transform.position).z / (GetComponent<Camera>().farClipPlane-GetComponent<Camera>().nearClipPlane);
}
private void WriteCoc ( RenderTexture fromTo, bool fgDilate) {
dofHdrMaterial.SetTexture("_FgOverlap", null);
if (nearBlur && fgDilate) {
int rtW = fromTo.width/2;
int rtH = fromTo.height/2;
// capture fg coc
RenderTexture temp2 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format);
Graphics.Blit (fromTo, temp2, dofHdrMaterial, 4);
// special blur
float fgAdjustment = internalBlurWidth * foregroundOverlap;
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgAdjustment , 0.0f, fgAdjustment));
RenderTexture temp1 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format);
Graphics.Blit (temp2, temp1, dofHdrMaterial, 2);
RenderTexture.ReleaseTemporary(temp2);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgAdjustment, 0.0f, 0.0f, fgAdjustment));
temp2 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format);
Graphics.Blit (temp1, temp2, dofHdrMaterial, 2);
RenderTexture.ReleaseTemporary(temp1);
// "merge up" with background COC
dofHdrMaterial.SetTexture("_FgOverlap", temp2);
fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected
Graphics.Blit (fromTo, fromTo, dofHdrMaterial, 13);
RenderTexture.ReleaseTemporary(temp2);
}
else {
// capture full coc in alpha channel (fromTo is not read, but bound to detect screen flip)
fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected
Graphics.Blit (fromTo, fromTo, dofHdrMaterial, 0);
}
}
void OnRenderImage (RenderTexture source, RenderTexture destination) {
if (!CheckResources ()) {
Graphics.Blit (source, destination);
return;
}
// clamp & prepare values so they make sense
if (aperture < 0.0f) aperture = 0.0f;
if (maxBlurSize < 0.1f) maxBlurSize = 0.1f;
focalSize = Mathf.Clamp(focalSize, 0.0f, 2.0f);
internalBlurWidth = Mathf.Max(maxBlurSize, 0.0f);
// focal & coc calculations
focalDistance01 = (focalTransform) ? (GetComponent<Camera>().WorldToViewportPoint (focalTransform.position)).z / (GetComponent<Camera>().farClipPlane) : FocalDistance01 (focalLength);
dofHdrMaterial.SetVector ("_CurveParams", new Vector4 (1.0f, focalSize, aperture/10.0f, focalDistance01));
// possible render texture helpers
RenderTexture rtLow = null;
RenderTexture rtLow2 = null;
RenderTexture rtSuperLow1 = null;
RenderTexture rtSuperLow2 = null;
float fgBlurDist = internalBlurWidth * foregroundOverlap;
if (visualizeFocus)
{
//
// 2.
// visualize coc
//
//
WriteCoc (source, true);
Graphics.Blit (source, destination, dofHdrMaterial, 16);
}
else if ((blurType == BlurType.DX11) && dx11bokehMaterial)
{
//
// 1.
// optimized dx11 bokeh scatter
//
//
if (highResolution) {
internalBlurWidth = internalBlurWidth < 0.1f ? 0.1f : internalBlurWidth;
fgBlurDist = internalBlurWidth * foregroundOverlap;
rtLow = RenderTexture.GetTemporary (source.width, source.height, 0, source.format);
var dest2= RenderTexture.GetTemporary (source.width, source.height, 0, source.format);
// capture COC
WriteCoc (source, false);
// blur a bit so we can do a frequency check
rtSuperLow1 = RenderTexture.GetTemporary(source.width>>1, source.height>>1, 0, source.format);
rtSuperLow2 = RenderTexture.GetTemporary(source.width>>1, source.height>>1, 0, source.format);
Graphics.Blit(source, rtSuperLow1, dofHdrMaterial, 15);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, 1.5f , 0.0f, 1.5f));
Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19);
// capture fg coc
if (nearBlur)
Graphics.Blit (source, rtSuperLow2, dofHdrMaterial, 4);
dx11bokehMaterial.SetTexture ("_BlurredColor", rtSuperLow1);
dx11bokehMaterial.SetFloat ("_SpawnHeuristic", dx11SpawnHeuristic);
dx11bokehMaterial.SetVector ("_BokehParams", new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth));
dx11bokehMaterial.SetTexture ("_FgCocMask", nearBlur ? rtSuperLow2 : null);
// collect bokeh candidates and replace with a darker pixel
Graphics.SetRandomWriteTarget (1, cbPoints);
Graphics.Blit (source, rtLow, dx11bokehMaterial, 0);
Graphics.ClearRandomWriteTargets ();
// fg coc blur happens here (after collect!)
if (nearBlur) {
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgBlurDist , 0.0f, fgBlurDist));
Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 2);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgBlurDist, 0.0f, 0.0f, fgBlurDist));
Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 2);
// merge fg coc with bg coc
Graphics.Blit (rtSuperLow2, rtLow, dofHdrMaterial, 3);
}
// NEW: LAY OUT ALPHA on destination target so we get nicer outlines for the high rez version
Graphics.Blit (rtLow, dest2, dofHdrMaterial, 20);
// box blur (easier to merge with bokeh buffer)
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (internalBlurWidth, 0.0f , 0.0f, internalBlurWidth));
Graphics.Blit (rtLow, source, dofHdrMaterial, 5);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.0f, internalBlurWidth));
Graphics.Blit (source, dest2, dofHdrMaterial, 21);
// apply bokeh candidates
Graphics.SetRenderTarget (dest2);
ComputeBuffer.CopyCount (cbPoints, cbDrawArgs, 0);
dx11bokehMaterial.SetBuffer ("pointBuffer", cbPoints);
dx11bokehMaterial.SetTexture ("_MainTex", dx11BokehTexture);
dx11bokehMaterial.SetVector ("_Screen", new Vector3(1.0f/(1.0f*source.width), 1.0f/(1.0f*source.height), internalBlurWidth));
dx11bokehMaterial.SetPass (2);
Graphics.DrawProceduralIndirectNow (MeshTopology.Points, cbDrawArgs, 0);
Graphics.Blit (dest2, destination); // hackaround for DX11 high resolution flipfun (OPTIMIZEME)
RenderTexture.ReleaseTemporary(dest2);
RenderTexture.ReleaseTemporary(rtSuperLow1);
RenderTexture.ReleaseTemporary(rtSuperLow2);
}
else {
rtLow = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format);
rtLow2 = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format);
fgBlurDist = internalBlurWidth * foregroundOverlap;
// capture COC & color in low resolution
WriteCoc (source, false);
source.filterMode = FilterMode.Bilinear;
Graphics.Blit (source, rtLow, dofHdrMaterial, 6);
// blur a bit so we can do a frequency check
rtSuperLow1 = RenderTexture.GetTemporary(rtLow.width>>1, rtLow.height>>1, 0, rtLow.format);
rtSuperLow2 = RenderTexture.GetTemporary(rtLow.width>>1, rtLow.height>>1, 0, rtLow.format);
Graphics.Blit(rtLow, rtSuperLow1, dofHdrMaterial, 15);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, 1.5f , 0.0f, 1.5f));
Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19);
RenderTexture rtLow3 = null;
if (nearBlur) {
// capture fg coc
rtLow3 = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format);
Graphics.Blit (source, rtLow3, dofHdrMaterial, 4);
}
dx11bokehMaterial.SetTexture ("_BlurredColor", rtSuperLow1);
dx11bokehMaterial.SetFloat ("_SpawnHeuristic", dx11SpawnHeuristic);
dx11bokehMaterial.SetVector ("_BokehParams", new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth));
dx11bokehMaterial.SetTexture ("_FgCocMask", rtLow3);
// collect bokeh candidates and replace with a darker pixel
Graphics.SetRandomWriteTarget (1, cbPoints);
Graphics.Blit (rtLow, rtLow2, dx11bokehMaterial, 0);
Graphics.ClearRandomWriteTargets ();
RenderTexture.ReleaseTemporary(rtSuperLow1);
RenderTexture.ReleaseTemporary(rtSuperLow2);
// fg coc blur happens here (after collect!)
if (nearBlur) {
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgBlurDist , 0.0f, fgBlurDist));
Graphics.Blit (rtLow3, rtLow, dofHdrMaterial, 2);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgBlurDist, 0.0f, 0.0f, fgBlurDist));
Graphics.Blit (rtLow, rtLow3, dofHdrMaterial, 2);
// merge fg coc with bg coc
Graphics.Blit (rtLow3, rtLow2, dofHdrMaterial, 3);
}
// box blur (easier to merge with bokeh buffer)
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (internalBlurWidth, 0.0f , 0.0f, internalBlurWidth));
Graphics.Blit (rtLow2, rtLow, dofHdrMaterial, 5);
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.0f, internalBlurWidth));
Graphics.Blit (rtLow, rtLow2, dofHdrMaterial, 5);
// apply bokeh candidates
Graphics.SetRenderTarget (rtLow2);
ComputeBuffer.CopyCount (cbPoints, cbDrawArgs, 0);
dx11bokehMaterial.SetBuffer ("pointBuffer", cbPoints);
dx11bokehMaterial.SetTexture ("_MainTex", dx11BokehTexture);
dx11bokehMaterial.SetVector ("_Screen", new Vector3(1.0f/(1.0f*rtLow2.width), 1.0f/(1.0f*rtLow2.height), internalBlurWidth));
dx11bokehMaterial.SetPass (1);
Graphics.DrawProceduralIndirectNow (MeshTopology.Points, cbDrawArgs, 0);
// upsample & combine
dofHdrMaterial.SetTexture ("_LowRez", rtLow2);
dofHdrMaterial.SetTexture ("_FgOverlap", rtLow3);
dofHdrMaterial.SetVector ("_Offsets", ((1.0f*source.width)/(1.0f*rtLow2.width)) * internalBlurWidth * Vector4.one);
Graphics.Blit (source, destination, dofHdrMaterial, 9);
if (rtLow3) RenderTexture.ReleaseTemporary(rtLow3);
}
}
else
{
//
// 2.
// poisson disc style blur in low resolution
//
//
source.filterMode = FilterMode.Bilinear;
if (highResolution) internalBlurWidth *= 2.0f;
WriteCoc (source, true);
rtLow = RenderTexture.GetTemporary (source.width >> 1, source.height >> 1, 0, source.format);
rtLow2 = RenderTexture.GetTemporary (source.width >> 1, source.height >> 1, 0, source.format);
int blurPass = (blurSampleCount == BlurSampleCount.High || blurSampleCount == BlurSampleCount.Medium) ? 17 : 11;
if (highResolution) {
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.025f, internalBlurWidth));
Graphics.Blit (source, destination, dofHdrMaterial, blurPass);
}
else {
dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.1f, internalBlurWidth));
// blur
Graphics.Blit (source, rtLow, dofHdrMaterial, 6);
Graphics.Blit (rtLow, rtLow2, dofHdrMaterial, blurPass);
// cheaper blur in high resolution, upsample and combine
dofHdrMaterial.SetTexture("_LowRez", rtLow2);
dofHdrMaterial.SetTexture("_FgOverlap", null);
dofHdrMaterial.SetVector ("_Offsets", Vector4.one * ((1.0f*source.width)/(1.0f*rtLow2.width)) * internalBlurWidth);
Graphics.Blit (source, destination, dofHdrMaterial, blurSampleCount == BlurSampleCount.High ? 18 : 12);
}
}
if (rtLow) RenderTexture.ReleaseTemporary(rtLow);
if (rtLow2) RenderTexture.ReleaseTemporary(rtLow2);
}
}
}
| |
// 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.Text;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace System.Xml.Serialization
{
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class CodeIdentifier
{
internal static CodeDomProvider csharp = new CSharpCodeProvider();
internal const int MaxIdentifierLength = 511;
[Obsolete("This class should never get constructed as it contains only static methods.")]
public CodeIdentifier()
{
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakePascal(string identifier)
{
identifier = MakeValid(identifier);
if (identifier.Length <= 2)
return CultureInfo.InvariantCulture.TextInfo.ToUpper(identifier);
else if (char.IsLower(identifier[0]))
return char.ToUpperInvariant(identifier[0]) + identifier.Substring(1);
else
return identifier;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakeCamel(string identifier)
{
identifier = MakeValid(identifier);
if (identifier.Length <= 2)
return CultureInfo.InvariantCulture.TextInfo.ToLower(identifier);
else if (char.IsUpper(identifier[0]))
return char.ToLower(identifier[0]) + identifier.Substring(1);
else
return identifier;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakeValid(string identifier)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < identifier.Length && builder.Length < MaxIdentifierLength; i++)
{
char c = identifier[i];
if (IsValid(c))
{
if (builder.Length == 0 && !IsValidStart(c))
{
builder.Append("Item");
}
builder.Append(c);
}
}
if (builder.Length == 0) return "Item";
return builder.ToString();
}
internal static string MakeValidInternal(string identifier)
{
if (identifier.Length > 30)
{
return "Item";
}
return MakeValid(identifier);
}
private static bool IsValidStart(char c)
{
// the given char is already a valid name character
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (!IsValid(c)) throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Invalid identifier character " + ((Int16)c).ToString(CultureInfo.InvariantCulture)), "c");
#endif
// First char cannot be a number
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber)
return false;
return true;
}
private static bool IsValid(char c)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
// each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc
//
switch (uc)
{
case UnicodeCategory.UppercaseLetter: // Lu
case UnicodeCategory.LowercaseLetter: // Ll
case UnicodeCategory.TitlecaseLetter: // Lt
case UnicodeCategory.ModifierLetter: // Lm
case UnicodeCategory.OtherLetter: // Lo
case UnicodeCategory.DecimalDigitNumber: // Nd
case UnicodeCategory.NonSpacingMark: // Mn
case UnicodeCategory.SpacingCombiningMark: // Mc
case UnicodeCategory.ConnectorPunctuation: // Pc
break;
case UnicodeCategory.LetterNumber:
case UnicodeCategory.OtherNumber:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Control:
case UnicodeCategory.Format:
case UnicodeCategory.Surrogate:
case UnicodeCategory.PrivateUse:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
case UnicodeCategory.MathSymbol:
case UnicodeCategory.CurrencySymbol:
case UnicodeCategory.ModifierSymbol:
case UnicodeCategory.OtherSymbol:
case UnicodeCategory.OtherNotAssigned:
return false;
default:
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Unhandled category " + uc), "c");
#else
return false;
#endif
}
return true;
}
internal static void CheckValidIdentifier(string ident)
{
if (!CodeGenerator.IsValidLanguageIndependentIdentifier(ident))
throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), "ident");
}
internal static string GetCSharpName(string name)
{
return EscapeKeywords(name.Replace('+', '.'), csharp);
}
private static int GetCSharpName(Type t, Type[] parameters, int index, StringBuilder sb)
{
if (t.DeclaringType != null && t.DeclaringType != t)
{
index = GetCSharpName(t.DeclaringType, parameters, index, sb);
sb.Append(".");
}
string name = t.Name;
int nameEnd = name.IndexOf('`');
if (nameEnd < 0)
{
nameEnd = name.IndexOf('!');
}
if (nameEnd > 0)
{
EscapeKeywords(name.Substring(0, nameEnd), csharp, sb);
sb.Append("<");
int arguments = Int32.Parse(name.Substring(nameEnd + 1), CultureInfo.InvariantCulture) + index;
for (; index < arguments; index++)
{
sb.Append(GetCSharpName(parameters[index]));
if (index < arguments - 1)
{
sb.Append(",");
}
}
sb.Append(">");
}
else
{
EscapeKeywords(name, csharp, sb);
}
return index;
}
internal static string GetCSharpName(Type t)
{
int rank = 0;
while (t.IsArray)
{
t = t.GetElementType();
rank++;
}
StringBuilder sb = new StringBuilder();
sb.Append("global::");
string ns = t.Namespace;
if (ns != null && ns.Length > 0)
{
string[] parts = ns.Split(new char[] { '.' });
for (int i = 0; i < parts.Length; i++)
{
EscapeKeywords(parts[i], csharp, sb);
sb.Append(".");
}
}
Type[] arguments = t.GetTypeInfo().IsGenericType || t.GetTypeInfo().ContainsGenericParameters ? t.GetGenericArguments() : Array.Empty<Type>();
GetCSharpName(t, arguments, 0, sb);
for (int i = 0; i < rank; i++)
{
sb.Append("[]");
}
return sb.ToString();
}
/*
internal static string GetTypeName(string name, CodeDomProvider codeProvider) {
return codeProvider.GetTypeOutput(new CodeTypeReference(name));
}
*/
private static void EscapeKeywords(string identifier, CodeDomProvider codeProvider, StringBuilder sb)
{
if (identifier == null || identifier.Length == 0)
return;
int arrayCount = 0;
while (identifier.EndsWith("[]", StringComparison.Ordinal))
{
arrayCount++;
identifier = identifier.Substring(0, identifier.Length - 2);
}
if (identifier.Length > 0)
{
CheckValidIdentifier(identifier);
identifier = codeProvider.CreateEscapedIdentifier(identifier);
sb.Append(identifier);
}
for (int i = 0; i < arrayCount; i++)
{
sb.Append("[]");
}
}
private static string EscapeKeywords(string identifier, CodeDomProvider codeProvider)
{
if (identifier == null || identifier.Length == 0) return identifier;
string originalIdentifier = identifier;
string[] names = identifier.Split(new char[] { '.', ',', '<', '>' });
StringBuilder sb = new StringBuilder();
int separator = -1;
for (int i = 0; i < names.Length; i++)
{
if (separator >= 0)
{
sb.Append(originalIdentifier.Substring(separator, 1));
}
separator++;
separator += names[i].Length;
string escapedName = names[i].Trim();
EscapeKeywords(escapedName, codeProvider, sb);
}
if (sb.Length != originalIdentifier.Length)
return sb.ToString();
return originalIdentifier;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SpendingReport.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal partial class ExpressionBinder
{
////////////////////////////////////////////////////////////////////////////////
// This table is used to implement the last set of 'better' conversion rules
// when there are no implicit conversions between T1(down) and T2 (across)
// Use all the simple types plus 1 more for Object
// See CLR section 7.4.1.3
static private readonly byte[][] s_betterConversionTable =
{
// BYTE SHORT INT LONG FLOAT DOUBLE DECIMAL CHAR BOOL SBYTE USHORT UINT ULONG IPTR UIPTR OBJECT
new byte[] /* BYTE*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0},
new byte[] /* SHORT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
new byte[] /* INT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0},
new byte[] /* LONG*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
new byte[] /* FLOAT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* DOUBLE*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* DECIMAL*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* CHAR*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* BOOL*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* SBYTE*/ {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
new byte[] /* USHORT*/ {0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0},
new byte[] /* UINT*/ {0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0},
new byte[] /* ULONG*/ {0, 2, 2, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0},
new byte[] /* IPTR*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* UIPTR*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new byte[] /* OBJECT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
protected BetterType WhichMethodIsBetterTieBreaker(
CandidateFunctionMember node1,
CandidateFunctionMember node2,
CType pTypeThrough,
ArgInfos args)
{
MethPropWithInst mpwi1 = node1.mpwi;
MethPropWithInst mpwi2 = node2.mpwi;
// Same signatures. If they have different lifting numbers, the smaller number wins.
// Otherwise, if one is generic and the other isn't then the non-generic wins.
// Otherwise, if one is expanded and the other isn't then the non-expanded wins.
// Otherwise, if one has fewer modopts than the other then it wins.
if (node1.ctypeLift != node2.ctypeLift)
{
return node1.ctypeLift < node2.ctypeLift ? BetterType.Left : BetterType.Right;
}
// Non-generic wins.
if (mpwi1.TypeArgs.size != 0)
{
if (mpwi2.TypeArgs.size == 0)
{
return BetterType.Right;
}
}
else if (mpwi2.TypeArgs.size != 0)
{
return BetterType.Left;
}
// Non-expanded wins
if (node1.fExpanded)
{
if (!node2.fExpanded)
{
return BetterType.Right;
}
}
else if (node2.fExpanded)
{
return BetterType.Left;
}
// See if one's parameter types (un-instantiated) are more specific.
BetterType nT = GetGlobalSymbols().CompareTypes(
RearrangeNamedArguments(mpwi1.MethProp().Params, mpwi1, pTypeThrough, args),
RearrangeNamedArguments(mpwi2.MethProp().Params, mpwi2, pTypeThrough, args));
if (nT == BetterType.Left || nT == BetterType.Right)
{
return nT;
}
// Fewer modopts wins.
if (mpwi1.MethProp().modOptCount != mpwi2.MethProp().modOptCount)
{
return mpwi1.MethProp().modOptCount < mpwi2.MethProp().modOptCount ? BetterType.Left : BetterType.Right;
}
// Bona-fide tie.
return BetterType.Neither;
}
////////////////////////////////////////////////////////////////////////////////
// Find the index of a name on a list.
// There is no failure case; we require that the name actually
// be on the list
private static int FindName(List<Name> names, Name name)
{
int index = names.IndexOf(name);
Debug.Assert(index != -1);
return index;
}
////////////////////////////////////////////////////////////////////////////////
// We need to rearange the method parameters so that the type of any specified named argument
// appears in the same place as the named argument. Consider the example below:
// Foo(int x = 4, string y = "", long l = 4)
// Foo(string y = "", string x="", long l = 5)
// and the call site:
// Foo(y:"a")
// After rearanging the parameter types we will have:
// (string, int, long) and (string, string, long)
// By rearanging the arguments as such we make sure that any specified named arguments appear in the same position for both
// methods and we also maintain the relative order of the other parameters (the type long appears after int in the above example)
private TypeArray RearrangeNamedArguments(TypeArray pta, MethPropWithInst mpwi,
CType pTypeThrough, ArgInfos args)
{
if (!args.fHasExprs)
{
return pta;
}
#if DEBUG
// We never have a named argument that is in a position in the argument
// list past the end of what would be the formal parameter list.
for (int i = pta.size; i < args.carg; i++)
{
Debug.Assert(!args.prgexpr[i].isNamedArgumentSpecification());
}
#endif
CType type = pTypeThrough != null ? pTypeThrough : mpwi.GetType();
CType[] typeList = new CType[pta.size];
MethodOrPropertySymbol methProp = GroupToArgsBinder.FindMostDerivedMethod(GetSymbolLoader(), mpwi.MethProp(), type);
// We initialize the new type array with the parameters for the method.
for (int iParam = 0; iParam < pta.size; iParam++)
{
typeList[iParam] = pta.Item(iParam);
}
// We then go over the specified arguments and put the type for any named argument in the right position in the array.
for (int iParam = 0; iParam < args.carg; iParam++)
{
EXPR arg = args.prgexpr[iParam];
if (arg.isNamedArgumentSpecification())
{
// We find the index of the type of the argument in the method parameter list and store that in a temp
int index = FindName(methProp.ParameterNames, arg.asNamedArgumentSpecification().Name);
CType tempType = pta.Item(index);
// Starting from the current position in the type list up until the location of the type of the optional argument
// We shift types by one:
// before: (int, string, long)
// after: (string, int, long)
// We only touch the types between the current position and the position of the type we need to move
for (int iShift = iParam; iShift < index; iShift++)
{
typeList[iShift + 1] = typeList[iShift];
}
typeList[iParam] = tempType;
}
}
return GetSymbolLoader().getBSymmgr().AllocParams(pta.size, typeList);
}
////////////////////////////////////////////////////////////////////////////////
// Determine which method is better for the purposes of overload resolution.
// Better means: as least as good in all params, and better in at least one param.
// Better w/r to a param means is an ordering, from best down:
// 1) same type as argument
// 2) implicit conversion from argument to formal type
// Because of user defined conversion opers this relation is not transitive.
//
// If there is a tie because of identical signatures, the tie may be broken by the
// following rules:
// 1) If one is generic and the other isn't, the non-generic wins.
// 2) Otherwise if one is expanded (params) and the other isn't, the non-expanded wins.
// 3) Otherwise if one has more specific parameter types (at the declaration) it wins:
// This occurs if at least on parameter type is more specific and no parameter type is
// less specific.
//* A type parameter is less specific than a non-type parameter.
//* A constructed type is more specific than another constructed type if at least
// one type argument is more specific and no type argument is less specific than
// the corresponding type args in the other.
// 4) Otherwise if one has more modopts than the other does, the smaller number of modopts wins.
//
// Returns Left if m1 is better, Right if m2 is better, or Neither/Same
protected BetterType WhichMethodIsBetter(
CandidateFunctionMember node1,
CandidateFunctionMember node2,
CType pTypeThrough,
ArgInfos args)
{
MethPropWithInst mpwi1 = node1.mpwi;
MethPropWithInst mpwi2 = node2.mpwi;
// Substitutions should have already been done on these!
TypeArray pta1 = RearrangeNamedArguments(node1.@params, mpwi1, pTypeThrough, args);
TypeArray pta2 = RearrangeNamedArguments(node2.@params, mpwi2, pTypeThrough, args);
// If the parameter types for both candidate methods are identical,
// use the tie breaking rules.
if (pta1 == pta2)
{
return WhichMethodIsBetterTieBreaker(node1, node2, pTypeThrough, args);
}
// Otherwise, do a parameter-by-parameter comparison:
//
// Given an argument list A with a set of argument expressions {E1, ... En} and
// two applicable function members Mp and Mq with parameter types {P1,... Pn} and
// {Q1, ... Qn}, Mp is defined to be a better function member than Mq if:
//* for each argument the implicit conversion from Ex to Qx is not better than
// the implicit conversion from Ex to Px.
//* for at least one argument, the conversion from Ex to Px is better than the
// conversion from Ex to Qx.
BetterType betterMethod = BetterType.Neither;
CType type1 = pTypeThrough != null ? pTypeThrough : mpwi1.GetType();
CType type2 = pTypeThrough != null ? pTypeThrough : mpwi2.GetType();
MethodOrPropertySymbol methProp1 = ExpressionBinder.GroupToArgsBinder.FindMostDerivedMethod(GetSymbolLoader(), mpwi1.MethProp(), type1);
MethodOrPropertySymbol methProp2 = ExpressionBinder.GroupToArgsBinder.FindMostDerivedMethod(GetSymbolLoader(), mpwi2.MethProp(), type2);
List<Name> names1 = methProp1.ParameterNames;
List<Name> names2 = methProp2.ParameterNames;
for (int i = 0; i < args.carg; i++)
{
EXPR arg = args.fHasExprs ? args.prgexpr[i] : null;
CType argType = args.types.Item(i);
CType p1 = pta1.Item(i);
CType p2 = pta2.Item(i);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// We need to consider conversions from the actual runtime type
// since we could have private interfaces that we are converting
if (arg.RuntimeObjectActualType != null)
{
argType = arg.RuntimeObjectActualType;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
BetterType betterConversion = WhichConversionIsBetter(arg, argType, p1, p2);
if (betterMethod == BetterType.Right && betterConversion == BetterType.Left)
{
betterMethod = BetterType.Neither;
break;
}
else if (betterMethod == BetterType.Left && betterConversion == BetterType.Right)
{
betterMethod = BetterType.Neither;
break;
}
else if (betterMethod == BetterType.Neither)
{
if (betterConversion == BetterType.Right || betterConversion == BetterType.Left)
{
betterMethod = betterConversion;
}
}
}
// We may have different sizes if we had optional parameters. If thats the case,
// the one with fewer parameters wins (ie less optional parameters) unless it is
// expanded. If so, the one with more parameters wins (ie option beats expanded).
if (pta1.size != pta2.size && betterMethod == BetterType.Neither)
{
if (node1.fExpanded && !node2.fExpanded)
{
return BetterType.Right;
}
else if (node2.fExpanded && !node1.fExpanded)
{
return BetterType.Left;
}
// Here, if both methods needed to use optionals to fill in the signatures,
// then we are ambiguous. Otherwise, take the one that didn't need any
// optionals.
if (pta1.size == args.carg)
{
return BetterType.Left;
}
else if (pta2.size == args.carg)
{
return BetterType.Right;
}
return BetterType.Neither;
}
return betterMethod;
}
protected BetterType WhichConversionIsBetter(EXPR arg, CType argType,
CType p1, CType p2)
{
Debug.Assert(argType != null);
Debug.Assert(p1 != null);
Debug.Assert(p2 != null);
// 7.4.2.3 Better Conversion From Expression
//
// Given an implicit conversion C1 that converts from an expression E to a type T1
// and an implicit conversion C2 that converts from an expression E to a type T2, the
// better conversion of the two conversions is determined as follows:
//* if T1 and T2 are the same type, neither conversion is better.
//* If E has a type S and the conversion from S to T1 is better than the conversion from
// S to T2 then C1 is the better conversion.
//* If E has a type S and the conversion from S to T2 is better than the conversion from
// S to T1 then C2 is the better conversion.
//* If E is a lambda expression or anonymous method for which an inferred return type X
// exists and T1 is a delegate type and T2 is a delegate type and T1 and T2 have identical
// parameter lists:
// * If T1 is a delegate of return type Y1 and T2 is a delegate of return type Y2 and the
// conversion from X to Y1 is better than the conversion from X to Y2, then C1 is the
// better return type.
// * If T1 is a delegate of return type Y1 and T2 is a delegate of return type Y2 and the
// conversion from X to Y2 is better than the conversion from X to Y1, then C2 is the
// better return type.
if (p1 == p2)
{
return BetterType.Same;
}
return WhichConversionIsBetter(argType, p1, p2);
}
public BetterType WhichConversionIsBetter(CType argType,
CType p1, CType p2)
{
// 7.4.2.4 Better conversion from type
//
// Given a conversion C1 that converts from a type S to a type T1 and a conversion C2
// that converts from a type S to a type T2, the better conversion of the two conversions
// is determined as follows:
//* If T1 and T2 are the same type, neither conversion is better
//* If S is T1, C1 is the better conversion.
//* If S is T2, C2 is the better conversion.
//* If an implicit conversion from T1 to T2 exists and no implicit conversion from T2 to
// T1 exists, C1 is the better conversion.
//* If an implicit conversion from T2 to T1 exists and no implicit conversion from T1 to
// T2 exists, C2 is the better conversion.
//
// [Otherwise, see table above for better integral type conversions.]
if (p1 == p2)
{
return BetterType.Same;
}
if (argType == p1)
{
return BetterType.Left;
}
if (argType == p2)
{
return BetterType.Right;
}
bool a2b = canConvert(p1, p2);
bool b2a = canConvert(p2, p1);
if (a2b && !b2a)
{
return BetterType.Left;
}
if (b2a && !a2b)
{
return BetterType.Right;
}
Debug.Assert(b2a == a2b);
if (p1.isPredefined() && p2.isPredefined() &&
p1.getPredefType() <= PredefinedType.PT_OBJECT && p2.getPredefType() <= PredefinedType.PT_OBJECT)
{
int c = s_betterConversionTable[(int)p1.getPredefType()][(int)p2.getPredefType()];
if (c == 1)
{
return BetterType.Left;
}
else if (c == 2)
{
return BetterType.Right;
}
}
return BetterType.Neither;
}
////////////////////////////////////////////////////////////////////////////////
// Determine best method for overload resolution. Returns null if no best
// method, in which case two tying methods are returned for error reporting.
protected CandidateFunctionMember FindBestMethod(
List<CandidateFunctionMember> list,
CType pTypeThrough,
ArgInfos args,
out CandidateFunctionMember methAmbig1,
out CandidateFunctionMember methAmbig2)
{
Debug.Assert(list.Any());
Debug.Assert(list.First().mpwi != null);
Debug.Assert(list.Count > 0);
// select the best method:
/*
Effectively, we pick the best item from a set using a non-transitive ranking function
So, pick the first item (candidate) and compare against next (contender), if there is
no next, goto phase 2
If first is better, move to next contender, if none proceed to phase 2
If second is better, make the contender the candidate and make the item following
contender into the new contender, if there is none, goto phase 2
If neither, make contender+1 into candidate and contender+2 into contender, if possible,
otherwise, if contender was last, return null, otherwise if new condidate is last,
goto phase 2
Phase 2: compare all items before candidate to candidate
If candidate always better, return it, otherwise return null
*/
// Record two method that are ambiguous for error reporting.
CandidateFunctionMember ambig1 = null;
CandidateFunctionMember ambig2 = null;
bool ambiguous = false;
CandidateFunctionMember candidate = list[0];
for (int i = 1; i < list.Count; i++)
{
CandidateFunctionMember contender = list[i];
Debug.Assert(candidate != contender);
BetterType result = WhichMethodIsBetter(candidate, contender, pTypeThrough, args);
if (result == BetterType.Left)
{
ambiguous = false;
continue; // (meaning m1 is better...)
}
else if (result == BetterType.Right)
{
ambiguous = false;
candidate = contender;
}
else
{
// in case of tie we don't want to bother with the contender who tied...
ambig1 = candidate;
ambig2 = contender;
i++;
if (i < list.Count)
{
contender = list[i];
candidate = contender;
}
else
{
ambiguous = true;
}
}
}
if (ambiguous)
goto AMBIG;
// Now, compare the candidate with items previous to it...
foreach (CandidateFunctionMember contender in list)
{
if (contender == candidate)
{
// We hit our winner, so its good enough...
methAmbig1 = null;
methAmbig2 = null;
return candidate;
}
BetterType result = WhichMethodIsBetter(contender, candidate, pTypeThrough, args);
if (result == BetterType.Right)
{ // meaning m2 is better
continue;
}
else if (result == BetterType.Same || result == BetterType.Neither)
{
ambig1 = candidate;
ambig2 = contender;
}
break;
}
AMBIG:
// an ambig call. Return two of the ambiguous set.
if (ambig1 != null && ambig2 != null)
{
methAmbig1 = ambig1;
methAmbig2 = ambig2;
}
else
{
// For some reason, we have an ambiguity but never had a tie.
// This can easily happen in a circular graph of candidate methods.
methAmbig1 = list.First();
methAmbig2 = list.Skip(1).First();
}
return null;
}
}
}
| |
// We can dramatically reduce garbage by using shared buffers
// on desktop platforms and dynamically adjusting the
// size which the arrays appear to be to C# code
// See: http://feedback.unity3d.com/suggestions/allow-mesh-data-to-have-a-length
#if !UNITY_STANDALONE
#undef USE_UNSAFE_CODE
#endif
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UMA
{
[Serializable]
/// <summary>
/// UMA version of Unity mesh triangle data.
/// </summary>
public struct SubMeshTriangles
{
public int[] triangles;
}
/// <summary>
/// UMA version of Unity transform data.
/// </summary>
[Serializable]
public class UMATransform
{
public Vector3 position;
public Quaternion rotation;
public Vector3 scale;
public string name;
public int hash;
public int parent;
public UMATransform()
{
}
public UMATransform(Transform transform, int nameHash, int parentHash)
{
this.hash = nameHash;
this.parent = parentHash;
position = transform.localPosition;
rotation = transform.localRotation;
scale = transform.localScale;
name = transform.name;
}
/// <summary>
/// Get a copy that is not part of an asset, to allow user manipulation.
/// </summary>
/// <returns>An identical copy</returns>
public UMATransform Duplicate()
{
return new UMATransform() { hash = hash, name = name, parent = parent, position = position, rotation = rotation, scale = scale };
}
public static UMATransformComparer TransformComparer = new UMATransformComparer();
public class UMATransformComparer : IComparer<UMATransform>
{
#region IComparer<UMATransform> Members
public int Compare(UMATransform x, UMATransform y)
{
return x.hash < y.hash ? -1 : x.hash > y.hash ? 1 : 0;
}
#endregion
}
public void Assign(UMATransform other)
{
hash = other.hash;
name = other.name;
parent = other.parent;
position = other.position;
rotation = other.rotation;
scale = other.scale;
}
}
/// <summary>
/// UMA version of Unity mesh bone weight.
/// </summary>
[Serializable]
public struct UMABoneWeight
{
public int boneIndex0;
public int boneIndex1;
public int boneIndex2;
public int boneIndex3;
public float weight0;
public float weight1;
public float weight2;
public float weight3;
public void Set(int index, int bone, float weight)
{
switch(index)
{
case 0:
boneIndex0 = bone;
weight0 = weight;
break;
case 1:
boneIndex1 = bone;
weight1 = weight;
break;
case 2:
boneIndex2 = bone;
weight2 = weight;
break;
case 3:
boneIndex3 = bone;
weight3 = weight;
break;
default:
throw new NotImplementedException();
}
}
public float GetWeight(int index)
{
switch(index)
{
case 0:
return weight0;
case 1:
return weight1;
case 2:
return weight2;
case 3:
return weight3;
default:
throw new NotImplementedException();
}
}
public int GetBoneIndex(int index)
{
switch(index)
{
case 0:
return boneIndex0;
case 1:
return boneIndex1;
case 2:
return boneIndex2;
case 3:
return boneIndex3;
default:
throw new NotImplementedException();
}
}
public static implicit operator UMABoneWeight(BoneWeight sourceWeight)
{
var res = new UMABoneWeight();
res.boneIndex0 = sourceWeight.boneIndex0;
res.boneIndex1 = sourceWeight.boneIndex1;
res.boneIndex2 = sourceWeight.boneIndex2;
res.boneIndex3 = sourceWeight.boneIndex3;
res.weight0 = sourceWeight.weight0;
res.weight1 = sourceWeight.weight1;
res.weight2 = sourceWeight.weight2;
res.weight3 = sourceWeight.weight3;
return res;
}
public static implicit operator BoneWeight(UMABoneWeight sourceWeight)
{
var res = new BoneWeight();
res.boneIndex0 = sourceWeight.boneIndex0;
res.boneIndex1 = sourceWeight.boneIndex1;
res.boneIndex2 = sourceWeight.boneIndex2;
res.boneIndex3 = sourceWeight.boneIndex3;
res.weight0 = sourceWeight.weight0;
res.weight1 = sourceWeight.weight1;
res.weight2 = sourceWeight.weight2;
res.weight3 = sourceWeight.weight3;
return res;
}
public static UMABoneWeight[] Convert(BoneWeight[] boneWeights)
{
if(boneWeights == null) return null;
var res = new UMABoneWeight[boneWeights.Length];
for (int i = 0; i < boneWeights.Length; i++)
{
res[i] = boneWeights[i];
}
return res;
}
public static UMABoneWeight[] Convert(List<BoneWeight> boneWeights)
{
if(boneWeights == null) return null;
var res = new UMABoneWeight[boneWeights.Count];
for (int i = 0; i < boneWeights.Count; i++)
{
res[i] = boneWeights[i];
}
return res;
}
public static BoneWeight[] Convert(UMABoneWeight[] boneWeights)
{
var res = new BoneWeight[boneWeights.Length];
for (int i = 0; i < boneWeights.Length; i++)
{
res[i] = boneWeights[i];
}
return res;
}
}
/// <summary>
/// UMA version of Unity mesh data.
/// </summary>
[Serializable]
public class UMAMeshData
{
public Matrix4x4[] bindPoses;
public UMABoneWeight[] boneWeights;
public BoneWeight[] unityBoneWeights;
public Vector3[] vertices;
public Vector3[] normals;
public Vector4[] tangents;
public Color32[] colors32;
public Vector2[] uv;
public Vector2[] uv2;
public Vector2[] uv3;
public Vector2[] uv4;
public SubMeshTriangles[] submeshes;
[NonSerialized]
public Transform[] bones;
[NonSerialized]
public Transform rootBone;
public UMATransform[] umaBones;
public int umaBoneCount;
public int rootBoneHash;
public int[] boneNameHashes;
public int subMeshCount;
public int vertexCount;
private bool OwnSharedBuffers()
{
#if USE_UNSAFE_CODE
return (this == bufferLockOwner);
#else
return false;
#endif
}
/// <summary>
/// Claims the static buffers.
/// </summary>
/// <returns><c>true</c>, if shared buffers was claimed, <c>false</c> otherwise.</returns>
public bool ClaimSharedBuffers()
{
#if USE_UNSAFE_CODE
if (bufferLockOwner == null)
{
bufferLockOwner = this;
vertices = gVertices;
boneWeights = null;
unityBoneWeights = gBoneWeights;
normals = gNormals;
tangents = gTangents;
uv = gUV;
uv2 = gUV2;
uv3 = gUV3;
uv4 = gUV4;
colors32 = gColors32;
boneHierarchy = gUMABones;
return true;
}
Debug.LogWarning("Unable to claim UMAMeshData global buffers!");
#endif
return false;
}
/// <summary>
/// Releases the static buffers.
/// </summary>
public void ReleaseSharedBuffers()
{
#if USE_UNSAFE_CODE
if (bufferLockOwner == this)
{
vertices = null;
boneWeights = null;
unityBoneWeights = null;
normals = null;
tangents = null;
uv = null;
uv2 = null;
uv3 = null;
uv4 = null;
colors32 = null;
bufferLockOwner = null;
}
#endif
}
public void PrepareVertexBuffers(int size)
{
vertexCount = size;
boneWeights = new UMABoneWeight[size];
vertices = new Vector3[size];
normals = new Vector3[size];
tangents = new Vector4[size];
colors32 = new Color32[size];
uv = new Vector2[size];
uv2 = new Vector2[size];
uv3 = new Vector2[size];
uv4 = new Vector2[size];
}
/// <summary>
/// Initialize UMA mesh data from Unity mesh.
/// </summary>
/// <param name="renderer">Source renderer.</param>
public void RetrieveDataFromUnityMesh(SkinnedMeshRenderer renderer)
{
RetrieveDataFromUnityMesh(renderer.sharedMesh);
UpdateBones(renderer.rootBone, renderer.bones);
}
/// <summary>
/// Initialize UMA mesh data from Unity mesh.
/// </summary>
/// <param name="renderer">Source renderer.</param>
public void RetrieveDataFromUnityMesh(Mesh sharedMesh)
{
bindPoses = sharedMesh.bindposes;
boneWeights = UMABoneWeight.Convert(sharedMesh.boneWeights);
vertices = sharedMesh.vertices;
vertexCount = vertices.Length;
normals = sharedMesh.normals;
tangents = sharedMesh.tangents;
colors32 = sharedMesh.colors32;
uv = sharedMesh.uv;
uv2 = sharedMesh.uv2;
uv3 = sharedMesh.uv3;
uv4 = sharedMesh.uv4;
subMeshCount = sharedMesh.subMeshCount;
submeshes = new SubMeshTriangles[subMeshCount];
for (int i = 0; i < subMeshCount; i++)
{
submeshes[i].triangles = sharedMesh.GetTriangles(i);
}
}
/// <summary>
/// Validates the skinned transform hierarchy.
/// </summary>
/// <param name="rootBone">Root transform.</param>
/// <param name="bones">Transforms.</param>
public void UpdateBones(Transform rootBone, Transform[] bones)
{
rootBone = FindRoot(rootBone, bones);
var requiredBones = new Dictionary<Transform, UMATransform>();
foreach (var bone in bones)
{
if (requiredBones.ContainsKey(bone)) continue;
var boneIterator = bone.parent;
var boneIteratorChild = bone;
var boneHash = UMAUtils.StringToHash(boneIterator.name);
var childHash = UMAUtils.StringToHash(boneIteratorChild.name);
while (boneIteratorChild != rootBone)
{
requiredBones.Add(boneIteratorChild, new UMATransform(boneIteratorChild, childHash, boneHash));
if (requiredBones.ContainsKey(boneIterator)) break;
boneIteratorChild = boneIterator;
boneIterator = boneIterator.parent;
childHash = boneHash;
boneHash = UMAUtils.StringToHash(boneIterator.name);
}
}
var sortedBones = new List<UMATransform>(requiredBones.Values);
sortedBones.Sort(UMATransform.TransformComparer);
umaBones = sortedBones.ToArray();
umaBoneCount = umaBones.Length;
rootBoneHash = UMAUtils.StringToHash(rootBone.name);
ComputeBoneNameHashes(bones);
this.rootBone = rootBone;
this.bones = bones;
}
private static Transform RecursiveFindBone(Transform bone, string raceRoot)
{
if (bone.name == raceRoot) return bone;
for (int i = 0; i < bone.childCount; i++)
{
var result = RecursiveFindBone(bone.GetChild(i), raceRoot);
if (result != null)
return result;
}
return null;
}
private Transform FindRoot(Transform rootBone, Transform[] bones)
{
if (rootBone == null)
{
for (int i = 0; i < bones.Length; i++)
{
if (bones[i] != null)
{
rootBone = bones[i];
break;
}
}
}
while (rootBone.parent != null)
rootBone = rootBone.parent;
return RecursiveFindBone(rootBone, "Global");
}
/// <summary>
/// Applies the data to a Unity mesh.
/// </summary>
/// <param name="renderer">Target renderer.</param>
/// <param name="skeleton">Skeleton.</param>
public void ApplyDataToUnityMesh(SkinnedMeshRenderer renderer, UMASkeleton skeleton)
{
CreateTransforms(skeleton);
Mesh mesh = renderer.sharedMesh;
#if UNITY_EDITOR
if (UnityEditor.PrefabUtility.IsComponentAddedToPrefabInstance(renderer))
{
Debug.LogError("Cannot apply changes to prefab!");
}
if (UnityEditor.AssetDatabase.IsSubAsset(mesh))
{
Debug.LogError("Cannot apply changes to asset mesh!");
}
#endif
mesh.subMeshCount = 1;
mesh.triangles = new int[0];
if (OwnSharedBuffers())
{
ApplySharedBuffers(mesh);
}
else
{
mesh.vertices = vertices;
mesh.boneWeights = unityBoneWeights != null ? unityBoneWeights : UMABoneWeight.Convert(boneWeights);
mesh.normals = normals;
mesh.tangents = tangents;
mesh.uv = uv;
mesh.uv2 = uv2;
mesh.uv3 = uv3;
mesh.uv4 = uv4;
mesh.colors32 = colors32;
}
mesh.bindposes = bindPoses;
var subMeshCount = submeshes.Length;
mesh.subMeshCount = subMeshCount;
for (int i = 0; i < subMeshCount; i++)
{
mesh.SetTriangles(submeshes[i].triangles, i);
}
mesh.RecalculateBounds();
renderer.bones = bones != null ? bones : skeleton.HashesToTransforms(boneNameHashes);
renderer.sharedMesh = mesh;
renderer.rootBone = rootBone;
}
/// <summary>
/// Applies the data to a Unity mesh.
/// </summary>
/// <param name="renderer">Target renderer.</param>
/// <param name="skeleton">Skeleton.</param>
public void CopyDataToUnityMesh(SkinnedMeshRenderer renderer)
{
Mesh mesh = renderer.sharedMesh;
mesh.subMeshCount = 1;
mesh.triangles = new int[0];
mesh.vertices = vertices;
mesh.boneWeights = UMABoneWeight.Convert(boneWeights);
mesh.normals = normals;
mesh.tangents = tangents;
mesh.uv = uv;
mesh.uv2 = uv2;
mesh.uv3 = uv3;
mesh.uv4 = uv4;
mesh.colors32 = colors32;
mesh.bindposes = bindPoses;
var subMeshCount = submeshes.Length;
mesh.subMeshCount = subMeshCount;
for (int i = 0; i < subMeshCount; i++)
{
mesh.SetTriangles(submeshes[i].triangles, i);
}
renderer.bones = bones;
renderer.rootBone = rootBone;
mesh.RecalculateBounds();
renderer.sharedMesh = mesh;
}
private void CreateTransforms(UMASkeleton skeleton)
{
for(int i = 0; i < umaBoneCount; i++ )
{
skeleton.EnsureBone(umaBones[i]);
}
skeleton.EnsureBoneHierarchy();
}
private void ApplySharedBuffers(Mesh mesh)
{
#if USE_UNSAFE_CODE
unsafe
{
UIntPtr* lengthPtr;
fixed (void* pVertices = gVertices)
{
lengthPtr = (UIntPtr*)pVertices - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.vertices = gVertices;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
fixed (void* pBoneWeights = gBoneWeights)
{
lengthPtr = (UIntPtr*)pBoneWeights - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.boneWeights = gBoneWeights;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
if (normals != null)
{
fixed (void* pNormals = gNormals)
{
lengthPtr = (UIntPtr*)pNormals - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.normals = gNormals;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
if (tangents != null)
{
fixed (void* pTangents = gTangents)
{
lengthPtr = (UIntPtr*)pTangents - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.tangents = gTangents;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
if (uv != null)
{
fixed (void* pUV = gUV)
{
lengthPtr = (UIntPtr*)pUV - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.uv = gUV;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
if (uv2 != null)
{
fixed (void* pUV2 = gUV2)
{
lengthPtr = (UIntPtr*)pUV2 - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.uv2 = gUV2;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
if (uv3 != null)
{
fixed (void* pUV3 = gUV3)
{
lengthPtr = (UIntPtr*)pUV3 - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.uv3 = gUV3;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
if (uv4 != null)
{
fixed (void* pUV4 = gUV4)
{
lengthPtr = (UIntPtr*)pUV4 - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.uv4 = gUV4;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
if (colors32 != null)
{
fixed (void* pColors32 = gColors32)
{
lengthPtr = (UIntPtr*)pColors32 - 1;
try
{
*lengthPtr = (UIntPtr)vertexCount;
mesh.colors32 = gColors32;
}
finally
{
*lengthPtr = (UIntPtr)MAX_VERTEX_COUNT;
}
}
}
}
#endif
}
private void ComputeBoneNameHashes(Transform[] bones)
{
boneNameHashes = new int[bones.Length];
for (int i = 0; i < bones.Length; i++)
{
boneNameHashes[i] = UMAUtils.StringToHash(bones[i].name);
}
}
#if USE_UNSAFE_CODE
private static UMAMeshData bufferLockOwner = null;
const int MAX_VERTEX_COUNT = 65534;
static Vector3[] gVertices = new Vector3[MAX_VERTEX_COUNT];
static BoneWeight[] gBoneWeights = new BoneWeight[MAX_VERTEX_COUNT];
static Vector3[] gNormals = new Vector3[MAX_VERTEX_COUNT];
static Vector4[] gTangents = new Vector4[MAX_VERTEX_COUNT];
static Vector2[] gUV = new Vector2[MAX_VERTEX_COUNT];
static Vector2[] gUV2 = new Vector2[MAX_VERTEX_COUNT];
static Vector2[] gUV3 = new Vector2[MAX_VERTEX_COUNT];
static Vector2[] gUV4 = new Vector2[MAX_VERTEX_COUNT];
static Color32[] gColors32 = new Color32[MAX_VERTEX_COUNT];
static UMATransform gUMABones = new UMATransform[MAX_VERTEX_COUNT];
#endif
#region operator ==, != and similar HACKS, seriously.....
public static implicit operator bool(UMAMeshData obj)
{
return ((System.Object)obj) != null && obj.vertexCount != 0;
}
public bool Equals(UMAMeshData other)
{
return (this == other);
}
public override bool Equals(object other)
{
return Equals(other as UMAMeshData);
}
public static bool operator ==(UMAMeshData overlay, UMAMeshData obj)
{
if (overlay)
{
if (obj)
{
return System.Object.ReferenceEquals(overlay, obj);
}
return false;
}
return !((bool)obj);
}
public static bool operator !=(UMAMeshData overlay, UMAMeshData obj)
{
if (overlay)
{
if (obj)
{
return !System.Object.ReferenceEquals(overlay, obj);
}
return true;
}
return ((bool)obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
internal void ReSortUMABones()
{
var newList = new List<UMATransform>(umaBones);
newList.Sort(UMATransform.TransformComparer);
umaBones = newList.ToArray();
}
}
}
| |
using System;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using MS.Internal.WindowsBase;
using MS.Internal;
namespace System.Windows.Threading
{
/// <summary>
/// DispatcherOperation represents a delegate that has been
/// posted to the Dispatcher queue.
/// </summary>
public class DispatcherOperation
{
/// <SecurityNote>
/// Critical: Accesses a critical field.
/// TreatAsSafe: Initializing critical field to a known safe value.
/// </SecurityNote>
[SecuritySafeCritical]
static DispatcherOperation()
{
_invokeInSecurityContext = new ContextCallback(InvokeInSecurityContext);
}
/// <SecurityNote>
/// Critical: accesses _executionContext
/// </SecurityNote>
[SecurityCritical]
internal DispatcherOperation(
Dispatcher dispatcher,
Delegate method,
DispatcherPriority priority,
object args,
int numArgs,
DispatcherOperationTaskSource taskSource,
bool useAsyncSemantics)
{
_dispatcher = dispatcher;
_method = method;
_priority = priority;
_numArgs = numArgs;
_args = args;
_executionContext = ExecutionContext.Capture();
_taskSource = taskSource;
_taskSource.Initialize(this);
_useAsyncSemantics = useAsyncSemantics;
}
/// <SecurityNote>
/// Critical: calls critical constructor
/// </SecurityNote>
[SecurityCritical]
internal DispatcherOperation(
Dispatcher dispatcher,
Delegate method,
DispatcherPriority priority,
object args,
int numArgs) : this(
dispatcher,
method,
priority,
args,
numArgs,
new DispatcherOperationTaskSource<object>(),
false)
{
}
/// <SecurityNote>
/// Critical: calls critical constructor
/// </SecurityNote>
[SecurityCritical]
internal DispatcherOperation(
Dispatcher dispatcher,
DispatcherPriority priority,
Action action) : this(
dispatcher,
action,
priority,
null,
0,
new DispatcherOperationTaskSource<object>(),
true)
{
}
/// <SecurityNote>
/// Critical: calls critical constructor
/// </SecurityNote>
[SecurityCritical]
internal DispatcherOperation(
Dispatcher dispatcher,
DispatcherPriority priority,
Delegate method,
object[] args) : this(
dispatcher,
method,
priority,
args,
-1,
new DispatcherOperationTaskSource<object>(),
true)
{
}
/// <summary>
/// Returns the Dispatcher that this operation was posted to.
/// </summary>
public Dispatcher Dispatcher
{
get
{
return _dispatcher;
}
}
/// <summary>
/// Gets or sets the priority of this operation within the
/// Dispatcher queue.
/// </summary>
public DispatcherPriority Priority // NOTE: should be Priority
{
get
{
return _priority;
}
set
{
Dispatcher.ValidatePriority(value, "value");
if(value != _priority && _dispatcher.SetPriority(this, value))
{
_priority = value;
}
}
}
/// <summary>
/// The status of this operation.
/// </summary>
public DispatcherOperationStatus Status
{
get
{
return _status;
}
}
/// <summary>
/// Returns a Task representing the operation.
/// </summary>
public Task Task
{
get
{
return _taskSource.GetTask();
}
}
/// <summary>
/// Returns an awaiter for awaiting the completion of the operation.
/// </summary>
/// <remarks>
/// This method is intended to be used by compilers.
/// </remarks>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public TaskAwaiter GetAwaiter()
{
return Task.GetAwaiter();
}
/// <summary>
/// Waits for this operation to complete.
/// </summary>
/// <returns>
/// The status of the operation. To obtain the return value
/// of the invoked delegate, use the the Result property.
/// </returns>
public DispatcherOperationStatus Wait()
{
return Wait(TimeSpan.FromMilliseconds(-1));
}
/// <summary>
/// Waits for this operation to complete.
/// </summary>
/// <param name="timeout">
/// The maximum amount of time to wait.
/// </param>
/// <returns>
/// The status of the operation. To obtain the return value
/// of the invoked delegate, use the the Result property.
/// </returns>
/// <SecurityNote>
/// Critical: This code calls into PushFrame which has a link demand
/// PublicOk: The act of waiting for operation to complete is safe.
/// </SecurityNote>
[SecurityCritical]
public DispatcherOperationStatus Wait(TimeSpan timeout)
{
if((_status == DispatcherOperationStatus.Pending || _status == DispatcherOperationStatus.Executing) &&
timeout.TotalMilliseconds != 0)
{
if(_dispatcher.Thread == Thread.CurrentThread)
{
if(_status == DispatcherOperationStatus.Executing)
{
// We are the dispatching thread, and the current operation state is
// executing, which means that the operation is in the middle of
// executing (on this thread) and is trying to wait for the execution
// to complete. Unfortunately, the thread will now deadlock, so
// we throw an exception instead.
throw new InvalidOperationException(SR.Get(SRID.ThreadMayNotWaitOnOperationsAlreadyExecutingOnTheSameThread));
}
// We are the dispatching thread for this operation, so
// we can't block. We will push a frame instead.
DispatcherOperationFrame frame = new DispatcherOperationFrame(this, timeout);
Dispatcher.PushFrame(frame);
}
else
{
// We are some external thread, so we can just block. Of
// course this means that the Dispatcher (queue)for this
// thread (if any) is now blocked. The COM STA model
// suggests that we should pump certain messages so that
// back-communication can happen. Underneath us, the CLR
// will pump the STA apartment for us, and we will allow
// the UI thread for a context to call
// Invoke(Priority.Max, ...) without going through the
// blocked queue.
DispatcherOperationEvent wait = new DispatcherOperationEvent(this, timeout);
wait.WaitOne();
}
}
if(_useAsyncSemantics)
{
if(_status == DispatcherOperationStatus.Completed ||
_status == DispatcherOperationStatus.Aborted)
{
// We know the operation has completed, so it safe to ask
// the task for the Awaiter, and the awaiter for the result.
// We don't actually care about the result, but this gives the
// Task the chance to throw any captured exceptions.
Task.GetAwaiter().GetResult();
}
}
return _status;
}
/// <summary>
/// Aborts this operation.
/// </summary>
/// <returns>
/// False if the operation could not be aborted (because the
/// operation was already in progress)
/// </returns>
/// <remarks>
/// Aborting an operation will try to remove an operation from the
/// Dispatcher queue so that it is never invoked. If successful,
/// the associated task is also marked as canceled.
/// </remarks>
public bool Abort()
{
bool removed = false;
if (_dispatcher != null)
{
removed = _dispatcher.Abort(this);
if (removed)
{
// Mark the task as canceled so that continuations will be invoked.
_taskSource.SetCanceled();
// Raise the aborted event.
EventHandler aborted = _aborted;
if (aborted != null)
{
aborted(this, EventArgs.Empty);
}
}
}
return removed;
}
/// <summary>
/// Name of this operation.
/// </summary>
/// <returns>
/// Returns a string representation of the operation to be invoked.
/// </returns>
internal String Name
{
get
{
return _method.Method.DeclaringType + "." + _method.Method.Name;
}
}
/// <summary>
/// ID of this operation.
/// </summary>
/// <returns>
/// Returns a "roaming" ID. This ID changes as the object is relocated by the GC.
/// However ETW tools listening for events containing these "roaming" IDs will be
/// able to account for the movements by listening for CLR's GC ETW events, and
/// will therefore be able to track this identity across the lifetime of the object.
/// </returns>
internal long Id
{
[SecurityCritical]
get
{
long addr;
unsafe
{
// we need a non-readonly field of a pointer-compatible type (using _priority)
fixed (DispatcherPriority* pb = &this._priority)
{
addr = (long) pb;
}
}
return addr;
}
}
/// <summary>
/// Returns the result of the operation if it has completed.
/// </summary>
public object Result
{
get
{
if(_useAsyncSemantics)
{
// New semantics require waiting for the operation to
// complete.
//
// Use DispatcherOperation.Wait instead of Task.Wait to handle
// waiting on the same thread.
Wait();
if(_status == DispatcherOperationStatus.Completed ||
_status == DispatcherOperationStatus.Aborted)
{
// We know the operation has completed, and the
// _taskSource has been completed, so it safe to ask
// the task for the Awaiter, and the awaiter for the result.
// We don't actually care about the result, but this gives the
// Task the chance to throw any captured exceptions.
Task.GetAwaiter().GetResult();
}
}
return _result;
}
}
/// <summary>
/// An event that is raised when the operation is aborted or canceled.
/// </summary>
public event EventHandler Aborted
{
add
{
lock (DispatcherLock)
{
_aborted = (EventHandler) Delegate.Combine(_aborted, value);
}
}
remove
{
lock(DispatcherLock)
{
_aborted = (EventHandler) Delegate.Remove(_aborted, value);
}
}
}
/// <summary>
/// An event that is raised when the operation completes.
/// </summary>
/// <remarks>
/// Completed indicates that the operation was invoked and has
/// either completed successfully or faulted. Note that a canceled
/// or aborted operation is never is never considered completed.
/// </remarks>
public event EventHandler Completed
{
add
{
lock (DispatcherLock)
{
_completed = (EventHandler) Delegate.Combine(_completed, value);
}
}
remove
{
lock(DispatcherLock)
{
_completed = (EventHandler) Delegate.Remove(_completed, value);
}
}
}
// Note: this is called by the Dispatcher to actually invoke the operation.
// Invoke --> InvokeInSecurityContext --> InvokeImpl
/// <SecurityNote>
/// Critical: This code calls into ExecutionContext.Run which is link demand protected
/// accesses _executionContext
/// </SecurityNote>
[SecurityCritical]
internal void Invoke()
{
// Mark this operation as executing.
_status = DispatcherOperationStatus.Executing;
// Invoke the operation under the execution context that was
// current when the operation was created.
if(_executionContext != null)
{
ExecutionContext.Run(_executionContext, _invokeInSecurityContext, this);
// Release any resources held by the execution context.
_executionContext.Dispose();
_executionContext = null;
}
else
{
// _executionContext can be null if someone called
// ExecutionContext.SupressFlow before calling BeginInvoke/Invoke.
// In this case we'll just call the invokation directly.
// SupressFlow is a privileged operation, so this is not a
// security hole.
_invokeInSecurityContext(this);
}
EventHandler handler; // either completed or aborted
lock(DispatcherLock)
{
if(_exception != null && _exception is OperationCanceledException)
{
// A new way to abort/cancel an operation is to raise an
// OperationCanceledException exception. This only works
// from the new APIs; the old APIs would flow the exception
// up through the Dispatcher.UnhandledException handling.
//
// Note that programmatically calling
// DispatcherOperation.Abort sets the status and raises the
// Aborted event itself.
handler = _aborted;
_status = DispatcherOperationStatus.Aborted;
}
else
{
// The operation either completed, or a new version threw an
// exception and we caught it. There is no seperate event
// for this, so we raise the same Completed event for both.
handler = _completed;
_status = DispatcherOperationStatus.Completed;
}
}
if(handler != null)
{
handler(this, EventArgs.Empty);
}
}
// Note: this is called by the Dispatcher to actually invoke the completions for the operation.
/// <SecurityNote>
/// Critical: This code invokes the completions for the task associated with an operation.
/// This may cause reentrancy, and effects program correctness, so must be
/// done carefully.
/// </SecurityNote>
[SecurityCritical]
internal void InvokeCompletions()
{
switch(_status)
{
case DispatcherOperationStatus.Aborted:
_taskSource.SetCanceled();
break;
case DispatcherOperationStatus.Completed:
if(_exception != null)
{
_taskSource.SetException(_exception);
}
else
{
_taskSource.SetResult(_result);
}
break;
default:
Invariant.Assert(false, "Operation should be either Aborted or Completed!");
break;
}
}
// Invoke --> InvokeInSecurityContext --> InvokeImpl
/// <SecurityNote>
/// Critical: This code can execute arbitrary code
/// </SecurityNote>
[SecurityCritical]
private static void InvokeInSecurityContext(Object state)
{
DispatcherOperation operation = (DispatcherOperation) state;
operation.InvokeImpl();
}
// Invoke --> InvokeInSecurityContext --> InvokeImpl
/// <SecurityNote>
/// Critical: This code calls into SynchronizationContext.SetSynchronizationContext which link demands
/// </SecurityNote>
[SecurityCritical]
private void InvokeImpl()
{
SynchronizationContext oldSynchronizationContext = SynchronizationContext.Current;
try
{
// We are executing under the "foreign" execution context, but the
// SynchronizationContext must be for the correct dispatcher and
// priority.
DispatcherSynchronizationContext newSynchronizationContext;
if(BaseCompatibilityPreferences.GetReuseDispatcherSynchronizationContextInstance())
{
newSynchronizationContext = Dispatcher._defaultDispatcherSynchronizationContext;
}
else
{
if(BaseCompatibilityPreferences.GetFlowDispatcherSynchronizationContextPriority())
{
newSynchronizationContext = new DispatcherSynchronizationContext(_dispatcher, _priority);
}
else
{
newSynchronizationContext = new DispatcherSynchronizationContext(_dispatcher, DispatcherPriority.Normal);
}
}
SynchronizationContext.SetSynchronizationContext(newSynchronizationContext);
// Win32 considers timers to be low priority. Avalon does not, since different timers
// are associated with different priorities. So we promote the timers before we
// invoke any work items.
_dispatcher.PromoteTimers(Environment.TickCount);
if(_useAsyncSemantics)
{
try
{
_result = InvokeDelegateCore();
}
catch(Exception e)
{
// Remember this for the later call to InvokeCompletions.
_exception = e;
}
}
else
{
// Invoke the delegate and route exceptions through the dispatcher events.
_result = _dispatcher.WrappedInvoke(_method, _args, _numArgs, null);
// Note: we do not catch exceptions, they flow out the the Dispatcher.UnhandledException handling.
}
}
finally
{
SynchronizationContext.SetSynchronizationContext(oldSynchronizationContext);
}
}
protected virtual object InvokeDelegateCore()
{
Action action = (Action) _method;
action();
return null;
}
private class DispatcherOperationFrame : DispatcherFrame
{
// Note: we pass "exitWhenRequested=false" to the base
// DispatcherFrame construsctor because we do not want to exit
// this frame if the dispatcher is shutting down. This is
// because we may need to invoke operations during the shutdown process.
public DispatcherOperationFrame(DispatcherOperation op, TimeSpan timeout) : base(false)
{
_operation = op;
// We will exit this frame once the operation is completed or aborted.
_operation.Aborted += new EventHandler(OnCompletedOrAborted);
_operation.Completed += new EventHandler(OnCompletedOrAborted);
// We will exit the frame if the operation is not completed within
// the requested timeout.
if(timeout.TotalMilliseconds > 0)
{
_waitTimer = new Timer(new TimerCallback(OnTimeout),
null,
timeout,
TimeSpan.FromMilliseconds(-1));
}
// Some other thread could have aborted the operation while we were
// setting up the handlers. We check the state again and mark the
// frame as "should not continue" if this happened.
if(_operation._status != DispatcherOperationStatus.Pending)
{
Exit();
}
}
private void OnCompletedOrAborted(object sender, EventArgs e)
{
Exit();
}
private void OnTimeout(object arg)
{
Exit();
}
private void Exit()
{
Continue = false;
if(_waitTimer != null)
{
_waitTimer.Dispose();
}
_operation.Aborted -= new EventHandler(OnCompletedOrAborted);
_operation.Completed -= new EventHandler(OnCompletedOrAborted);
}
private DispatcherOperation _operation;
private Timer _waitTimer;
}
private class DispatcherOperationEvent
{
public DispatcherOperationEvent(DispatcherOperation op, TimeSpan timeout)
{
_operation = op;
_timeout = timeout;
_event = new ManualResetEvent(false);
_eventClosed = false;
lock(DispatcherLock)
{
// We will set our event once the operation is completed or aborted.
_operation.Aborted += new EventHandler(OnCompletedOrAborted);
_operation.Completed += new EventHandler(OnCompletedOrAborted);
// Since some other thread is dispatching this operation, it could
// have been dispatched while we were setting up the handlers.
// We check the state again and set the event ourselves if this
// happened.
if(_operation._status != DispatcherOperationStatus.Pending && _operation._status != DispatcherOperationStatus.Executing)
{
_event.Set();
}
}
}
private void OnCompletedOrAborted(object sender, EventArgs e)
{
lock(DispatcherLock)
{
if(!_eventClosed)
{
_event.Set();
}
}
}
public void WaitOne()
{
_event.WaitOne(_timeout, false);
lock(DispatcherLock)
{
if(!_eventClosed)
{
// Cleanup the events.
_operation.Aborted -= new EventHandler(OnCompletedOrAborted);
_operation.Completed -= new EventHandler(OnCompletedOrAborted);
// Close the event immediately instead of waiting for a GC
// because the Dispatcher is a a high-activity component and
// we could run out of events.
_event.Close();
_eventClosed = true;
}
}
}
private object DispatcherLock
{
get { return _operation.DispatcherLock; }
}
private DispatcherOperation _operation;
private TimeSpan _timeout;
private ManualResetEvent _event;
private bool _eventClosed;
}
private object DispatcherLock
{
get { return _dispatcher._instanceLock; }
}
/// <SecurityNote>
/// Obtained under an elevation.
/// </SecurityNote>
[SecurityCritical]
private ExecutionContext _executionContext;
private static readonly ContextCallback _invokeInSecurityContext;
private readonly Dispatcher _dispatcher;
private DispatcherPriority _priority;
internal readonly Delegate _method;
private readonly object _args;
private readonly int _numArgs;
internal DispatcherOperationStatus _status; // set from Dispatcher
private object _result;
private Exception _exception;
internal PriorityItem<DispatcherOperation> _item; // The Dispatcher sets this when it enques/deques the item.
EventHandler _aborted;
EventHandler _completed;
internal readonly DispatcherOperationTaskSource _taskSource; // also used from Dispatcher
private readonly bool _useAsyncSemantics;
}
/// <summary>
/// DispatcherOperation represents a delegate that has been
/// posted to the Dispatcher queue.
/// </summary>
public class DispatcherOperation<TResult> : DispatcherOperation
{
/// <SecurityNote>
/// Critical: calls critical constructor
/// </SecurityNote>
[SecurityCritical]
internal DispatcherOperation(
Dispatcher dispatcher,
DispatcherPriority priority,
Func<TResult> func) : base(
dispatcher,
func,
priority,
null,
0,
new DispatcherOperationTaskSource<TResult>(),
true)
{
}
/// <summary>
/// Returns a Task representing the operation.
/// </summary>
public new Task<TResult> Task
{
get
{
// Just upcast the base Task to what it really is.
return (Task<TResult>)((DispatcherOperation)this).Task;
}
}
/// <summary>
/// Returns an awaiter for awaiting the completion of the operation.
/// </summary>
/// <remarks>
/// This method is intended to be used by compilers.
/// </remarks>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new TaskAwaiter<TResult> GetAwaiter()
{
return Task.GetAwaiter();
}
/// <summary>
/// Returns the result of the operation if it has completed.
/// </summary>
public new TResult Result
{
get
{
return (TResult) ((DispatcherOperation)this).Result;
}
}
protected override object InvokeDelegateCore()
{
Func<TResult> func = (Func<TResult>) _method;
return func();
}
}
/// <summary>
/// A convenient delegate to use for dispatcher operations.
/// </summary>
public delegate object DispatcherOperationCallback(object arg);
}
| |
namespace Orleans.CodeGenerator
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.CodeGenerator.Utilities;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Serialization;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
/// <summary>
/// Code generator which generates serializers.
/// </summary>
public static class SerializerGenerator
{
private static readonly TypeFormattingOptions GeneratedTypeNameOptions = new TypeFormattingOptions(
ClassSuffix,
includeGenericParameters: false,
includeTypeParameters: false,
nestedClassSeparator: '_',
includeGlobal: false);
/// <summary>
/// The suffix appended to the name of generated classes.
/// </summary>
private const string ClassSuffix = "Serializer";
/// <summary>
/// The suffix appended to the name of the generic serializer registration class.
/// </summary>
private const string RegistererClassSuffix = "Registerer";
/// <summary>
/// Generates the class for the provided grain types.
/// </summary>
/// <param name="type">The grain interface type.</param>
/// <param name="onEncounteredType">
/// The callback invoked when a type is encountered.
/// </param>
/// <returns>
/// The generated class.
/// </returns>
internal static IEnumerable<TypeDeclarationSyntax> GenerateClass(Type type, Action<Type> onEncounteredType)
{
var typeInfo = type.GetTypeInfo();
var genericTypes = typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray()
: new TypeParameterSyntax[0];
var attributes = new List<AttributeSyntax>
{
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
#if !NETSTANDARD
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
#endif
SF.Attribute(typeof(SerializerAttribute).GetNameSyntax())
.AddArgumentListArguments(
SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))))
};
var className = CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions);
var fields = GetFields(type);
// Mark each field type for generation
foreach (var field in fields)
{
var fieldType = field.FieldInfo.FieldType;
onEncounteredType(fieldType);
}
var members = new List<MemberDeclarationSyntax>(GenerateStaticFields(fields))
{
GenerateDeepCopierMethod(type, fields),
GenerateSerializerMethod(type, fields),
GenerateDeserializerMethod(type, fields),
};
if (typeInfo.IsConstructedGenericType() || !typeInfo.IsGenericTypeDefinition)
{
members.Add(GenerateRegisterMethod(type));
members.Add(GenerateConstructor(className));
attributes.Add(SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax()));
}
var classDeclaration =
SF.ClassDeclaration(className)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray()))
.AddMembers(members.ToArray())
.AddConstraintClauses(type.GetTypeConstraintSyntax());
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
var classes = new List<TypeDeclarationSyntax> { classDeclaration };
if (typeInfo.IsGenericTypeDefinition)
{
// Create a generic representation of the serializer type.
var serializerType =
SF.GenericName(classDeclaration.Identifier)
.WithTypeArgumentList(
SF.TypeArgumentList()
.AddArguments(
type.GetTypeInfo().GetGenericArguments()
.Select(_ => SF.OmittedTypeArgument())
.Cast<TypeSyntax>()
.ToArray()));
var registererClassName = className + "_" +
string.Join("_",
type.GetTypeInfo().GenericTypeParameters.Select(_ => _.Name)) + "_" +
RegistererClassSuffix;
classes.Add(
SF.ClassDeclaration(registererClassName)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddAttributeLists(
SF.AttributeList()
.AddAttributes(
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
#if !NETSTANDARD
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
#endif
SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax())))
.AddMembers(
GenerateMasterRegisterMethod(type, serializerType),
GenerateConstructor(registererClassName)));
}
return classes;
}
/// <summary>
/// Returns syntax for the deserializer method.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fields">The fields.</param>
/// <returns>Syntax for the deserializer method.</returns>
private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List<FieldInfoMember> fields)
{
Expression<Action> deserializeInner =
() => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader));
var streamParameter = SF.IdentifierName("stream");
var resultDeclaration =
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("result")
.WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))));
var resultVariable = SF.IdentifierName("result");
var body = new List<StatementSyntax> { resultDeclaration };
// Value types cannot be referenced, only copied, so there is no need to box & record instances of value types.
if (!type.GetTypeInfo().IsValueType)
{
// Record the result for cyclic deserialization.
Expression<Action> recordObject = () => DeserializationContext.Current.RecordObject(default(object));
var currentSerializationContext =
SyntaxFactory.AliasQualifiedName(
SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)),
SF.IdentifierName("Orleans"))
.Qualify("Serialization")
.Qualify("DeserializationContext")
.Qualify("Current");
body.Add(
SF.ExpressionStatement(
recordObject.Invoke(currentSerializationContext)
.AddArgumentListArguments(SF.Argument(resultVariable))));
}
// Deserialize all fields.
foreach (var field in fields)
{
var deserialized =
deserializeInner.Invoke()
.AddArgumentListArguments(
SF.Argument(SF.TypeOfExpression(field.Type)),
SF.Argument(streamParameter));
body.Add(
SF.ExpressionStatement(
field.GetSetter(
resultVariable,
SF.CastExpression(field.Type, deserialized))));
}
body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable)));
return
SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()),
SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamReader).GetTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
SF.AttributeList()
.AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax())));
}
private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List<FieldInfoMember> fields)
{
Expression<Action> serializeInner =
() =>
SerializationManager.SerializeInner(default(object), default(BinaryTokenStreamWriter), default(Type));
var body = new List<StatementSyntax>
{
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("input")
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput"))))))
};
var inputExpression = SF.IdentifierName("input");
// Serialize all members.
foreach (var field in fields)
{
body.Add(
SF.ExpressionStatement(
serializeInner.Invoke()
.AddArgumentListArguments(
SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)),
SF.Argument(SF.IdentifierName("stream")),
SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax())))));
}
return
SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()),
SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamWriter).GetTypeSyntax()),
SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
SF.AttributeList()
.AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax())));
}
/// <summary>
/// Returns syntax for the deep copier method.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fields">The fields.</param>
/// <returns>Syntax for the deep copier method.</returns>
private static MemberDeclarationSyntax GenerateDeepCopierMethod(Type type, List<FieldInfoMember> fields)
{
var originalVariable = SF.IdentifierName("original");
var inputVariable = SF.IdentifierName("input");
var resultVariable = SF.IdentifierName("result");
var body = new List<StatementSyntax>();
if (type.GetTypeInfo().GetCustomAttribute<ImmutableAttribute>() != null)
{
// Immutable types do not require copying.
body.Add(SF.ReturnStatement(originalVariable));
}
else
{
body.Add(
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("input")
.WithInitializer(
SF.EqualsValueClause(
SF.ParenthesizedExpression(
SF.CastExpression(type.GetTypeSyntax(), originalVariable)))))));
body.Add(
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("result")
.WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type))))));
// Record this serialization.
Expression<Action> recordObject =
() => SerializationContext.Current.RecordObject(default(object), default(object));
var currentSerializationContext =
SyntaxFactory.AliasQualifiedName(
SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)),
SF.IdentifierName("Orleans"))
.Qualify("Serialization")
.Qualify("SerializationContext")
.Qualify("Current");
body.Add(
SF.ExpressionStatement(
recordObject.Invoke(currentSerializationContext)
.AddArgumentListArguments(SF.Argument(originalVariable), SF.Argument(resultVariable))));
// Copy all members from the input to the result.
foreach (var field in fields)
{
body.Add(SF.ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable))));
}
body.Add(SF.ReturnStatement(resultVariable));
}
return
SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "DeepCopier")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("original")).WithType(typeof(object).GetTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
SF.AttributeList().AddAttributes(SF.Attribute(typeof(CopierMethodAttribute).GetNameSyntax())));
}
/// <summary>
/// Returns syntax for the static fields of the serializer class.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns>Syntax for the static fields of the serializer class.</returns>
private static MemberDeclarationSyntax[] GenerateStaticFields(List<FieldInfoMember> fields)
{
var result = new List<MemberDeclarationSyntax>();
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Expression<Action<TypeInfo>> getField = _ => _.GetField(string.Empty, BindingFlags.Default);
Expression<Action<Type>> getTypeInfo = _ => _.GetTypeInfo();
Expression<Action> getGetter = () => SerializationManager.GetGetter(default(FieldInfo));
Expression<Action> getReferenceSetter = () => SerializationManager.GetReferenceSetter(default(FieldInfo));
Expression<Action> getValueSetter = () => SerializationManager.GetValueSetter(default(FieldInfo));
// Expressions for specifying binding flags.
var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax(
SyntaxKind.BitwiseOrExpression,
BindingFlags.Instance,
BindingFlags.NonPublic,
BindingFlags.Public);
// Add each field and initialize it.
foreach (var field in fields)
{
var fieldInfo =
getField.Invoke(getTypeInfo.Invoke(SF.TypeOfExpression(field.FieldInfo.DeclaringType.GetTypeSyntax())))
.AddArgumentListArguments(
SF.Argument(field.FieldInfo.Name.GetLiteralExpression()),
SF.Argument(bindingFlags));
var fieldInfoVariable =
SF.VariableDeclarator(field.InfoFieldName).WithInitializer(SF.EqualsValueClause(fieldInfo));
var fieldInfoField = SF.IdentifierName(field.InfoFieldName);
if (!field.IsGettableProperty || !field.IsSettableProperty)
{
result.Add(
SF.FieldDeclaration(
SF.VariableDeclaration(typeof(FieldInfo).GetTypeSyntax()).AddVariables(fieldInfoVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
// Declare the getter for this field.
if (!field.IsGettableProperty)
{
var getterType =
typeof(Func<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType)
.GetTypeSyntax();
var fieldGetterVariable =
SF.VariableDeclarator(field.GetterFieldName)
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(
getterType,
getGetter.Invoke().AddArgumentListArguments(SF.Argument(fieldInfoField)))));
result.Add(
SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
if (!field.IsSettableProperty)
{
if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.GetTypeInfo().IsValueType)
{
var setterType =
typeof(SerializationManager.ValueTypeSetter<,>).MakeGenericType(
field.FieldInfo.DeclaringType,
field.FieldInfo.FieldType).GetTypeSyntax();
var fieldSetterVariable =
SF.VariableDeclarator(field.SetterFieldName)
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(
setterType,
getValueSetter.Invoke()
.AddArgumentListArguments(SF.Argument(fieldInfoField)))));
result.Add(
SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
else
{
var setterType =
typeof(Action<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType)
.GetTypeSyntax();
var fieldSetterVariable =
SF.VariableDeclarator(field.SetterFieldName)
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(
setterType,
getReferenceSetter.Invoke()
.AddArgumentListArguments(SF.Argument(fieldInfoField)))));
result.Add(
SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
}
}
return result.ToArray();
}
/// <summary>
/// Returns syntax for initializing a new instance of the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Syntax for initializing a new instance of the provided type.</returns>
private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type)
{
ExpressionSyntax result;
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsValueType)
{
// Use the default value.
result = SF.DefaultExpression(typeInfo.AsType().GetTypeSyntax());
}
else if (typeInfo.GetConstructor(Type.EmptyTypes) != null)
{
// Use the default constructor.
result = SF.ObjectCreationExpression(typeInfo.AsType().GetTypeSyntax()).AddArgumentListArguments();
}
else
{
// Create an unformatted object.
Expression<Func<object>> getUninitializedObject =
#if NETSTANDARD
() => SerializationManager.GetUninitializedObjectWithFormatterServices(default(Type));
#else
() => FormatterServices.GetUninitializedObject(default(Type));
#endif
result = SF.CastExpression(
type.GetTypeSyntax(),
getUninitializedObject.Invoke()
.AddArgumentListArguments(
SF.Argument(SF.TypeOfExpression(typeInfo.AsType().GetTypeSyntax()))));
}
return result;
}
/// <summary>
/// Returns syntax for the serializer registration method.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Syntax for the serializer registration method.</returns>
private static MemberDeclarationSyntax GenerateRegisterMethod(Type type)
{
Expression<Action> register =
() =>
SerializationManager.Register(
default(Type),
default(SerializationManager.DeepCopier),
default(SerializationManager.Serializer),
default(SerializationManager.Deserializer));
return
SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters()
.AddBodyStatements(
SF.ExpressionStatement(
register.Invoke()
.AddArgumentListArguments(
SF.Argument(SF.TypeOfExpression(type.GetTypeSyntax())),
SF.Argument(SF.IdentifierName("DeepCopier")),
SF.Argument(SF.IdentifierName("Serializer")),
SF.Argument(SF.IdentifierName("Deserializer")))));
}
/// <summary>
/// Returns syntax for the constructor.
/// </summary>
/// <param name="className">The name of the class.</param>
/// <returns>Syntax for the constructor.</returns>
private static ConstructorDeclarationSyntax GenerateConstructor(string className)
{
return
SF.ConstructorDeclaration(className)
.AddModifiers(SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters()
.AddBodyStatements(
SF.ExpressionStatement(
SF.InvocationExpression(SF.IdentifierName("Register")).AddArgumentListArguments()));
}
/// <summary>
/// Returns syntax for the generic serializer registration method for the provided type..
/// </summary>
/// <param name="type">The type which is supported by this serializer.</param>
/// <param name="serializerType">The type of the serializer.</param>
/// <returns>Syntax for the generic serializer registration method for the provided type..</returns>
private static MemberDeclarationSyntax GenerateMasterRegisterMethod(Type type, TypeSyntax serializerType)
{
Expression<Action> register = () => SerializationManager.Register(default(Type), default(Type));
return
SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters()
.AddBodyStatements(
SF.ExpressionStatement(
register.Invoke()
.AddArgumentListArguments(
SF.Argument(
SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))),
SF.Argument(SF.TypeOfExpression(serializerType)))));
}
/// <summary>
/// Returns a sorted list of the fields of the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>A sorted list of the fields of the provided type.</returns>
private static List<FieldInfoMember> GetFields(Type type)
{
var result =
type.GetAllFields()
.Where(field => field.GetCustomAttribute<NonSerializedAttribute>() == null)
.Select((info, i) => new FieldInfoMember { FieldInfo = info, FieldNumber = i })
.ToList();
result.Sort(FieldInfoMember.Comparer.Instance);
return result;
}
/// <summary>
/// Represents a field.
/// </summary>
private class FieldInfoMember
{
private PropertyInfo property;
/// <summary>
/// Gets or sets the underlying <see cref="FieldInfo"/> instance.
/// </summary>
public FieldInfo FieldInfo { get; set; }
/// <summary>
/// Sets the ordinal assigned to this field.
/// </summary>
public int FieldNumber { private get; set; }
/// <summary>
/// Gets the name of the field info field.
/// </summary>
public string InfoFieldName
{
get
{
return "field" + this.FieldNumber;
}
}
/// <summary>
/// Gets the name of the getter field.
/// </summary>
public string GetterFieldName
{
get
{
return "getField" + this.FieldNumber;
}
}
/// <summary>
/// Gets the name of the setter field.
/// </summary>
public string SetterFieldName
{
get
{
return "setField" + this.FieldNumber;
}
}
/// <summary>
/// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter.
/// </summary>
public bool IsGettableProperty
{
get
{
return this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete;
}
}
/// <summary>
/// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter.
/// </summary>
public bool IsSettableProperty
{
get
{
return this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete;
}
}
/// <summary>
/// Gets syntax representing the type of this field.
/// </summary>
public TypeSyntax Type
{
get
{
return this.FieldInfo.FieldType.GetTypeSyntax();
}
}
/// <summary>
/// Gets the <see cref="PropertyInfo"/> which this field is the backing property for, or
/// <see langword="null" /> if this is not the backing field of an auto-property.
/// </summary>
private PropertyInfo PropertyInfo
{
get
{
if (this.property != null)
{
return this.property;
}
var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$");
if (propertyName.Success && this.FieldInfo.DeclaringType != null)
{
var name = propertyName.Groups[1].Value;
this.property = this.FieldInfo.DeclaringType.GetTypeInfo()
.GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
}
return this.property;
}
}
/// <summary>
/// Gets a value indicating whether or not this field is obsolete.
/// </summary>
private bool IsObsolete
{
get
{
var obsoleteAttr = this.FieldInfo.GetCustomAttribute<ObsoleteAttribute>();
// Get the attribute from the property, if present.
if (this.property != null && obsoleteAttr == null)
{
obsoleteAttr = this.property.GetCustomAttribute<ObsoleteAttribute>();
}
return obsoleteAttr != null;
}
}
/// <summary>
/// Returns syntax for retrieving the value of this field, deep copying it if neccessary.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false)
{
// Retrieve the value of the field.
var getValueExpression = this.GetValueExpression(instance);
// Avoid deep-copying the field if possible.
if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
{
// Return the value without deep-copying it.
return getValueExpression;
}
// Addressable arguments must be converted to references before passing.
// IGrainObserver instances cannot be directly converted to references, therefore they are not included.
ExpressionSyntax deepCopyValueExpression;
if (typeof(IAddressable).IsAssignableFrom(this.FieldInfo.FieldType)
&& this.FieldInfo.FieldType.GetTypeInfo().IsInterface
&& !typeof(IGrainObserver).IsAssignableFrom(this.FieldInfo.FieldType))
{
var getAsReference = getValueExpression.Member(
(IAddressable grain) => grain.AsReference<IGrain>(),
this.FieldInfo.FieldType);
// If the value is not a GrainReference, convert it to a strongly-typed GrainReference.
// C#: !(value is GrainReference) ? value.AsReference<TInterface>() : value;
deepCopyValueExpression =
SF.ConditionalExpression(
SF.PrefixUnaryExpression(
SyntaxKind.LogicalNotExpression,
SF.ParenthesizedExpression(
SF.BinaryExpression(
SyntaxKind.IsExpression,
getValueExpression,
typeof(GrainReference).GetTypeSyntax()))),
SF.InvocationExpression(getAsReference),
getValueExpression);
}
else
{
deepCopyValueExpression = getValueExpression;
}
// Deep-copy the value.
Expression<Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object));
var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax();
return SF.CastExpression(
typeSyntax,
deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(deepCopyValueExpression)));
}
/// <summary>
/// Returns syntax for setting the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="value">Syntax for the new value.</param>
/// <returns>Syntax for setting the value of this field.</returns>
public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value)
{
// If the field is the backing field for an accessible auto-property use the property directly.
if (this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete)
{
return SF.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
instance.Member(this.PropertyInfo.Name),
value);
}
var instanceArg = SF.Argument(instance);
if (this.FieldInfo.DeclaringType != null && this.FieldInfo.DeclaringType.GetTypeInfo().IsValueType)
{
instanceArg = instanceArg.WithRefOrOutKeyword(SF.Token(SyntaxKind.RefKeyword));
}
return
SF.InvocationExpression(SF.IdentifierName(this.SetterFieldName))
.AddArgumentListArguments(instanceArg, SF.Argument(value));
}
/// <summary>
/// Returns syntax for retrieving the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
private ExpressionSyntax GetValueExpression(ExpressionSyntax instance)
{
// If the field is the backing field for an accessible auto-property use the property directly.
ExpressionSyntax result;
if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete)
{
result = instance.Member(this.PropertyInfo.Name);
}
else
{
// Retrieve the field using the generated getter.
result =
SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName))
.AddArgumentListArguments(SF.Argument(instance));
}
return result;
}
/// <summary>
/// A comparer for <see cref="FieldInfoMember"/> which compares by name.
/// </summary>
public class Comparer : IComparer<FieldInfoMember>
{
/// <summary>
/// The singleton instance.
/// </summary>
private static readonly Comparer Singleton = new Comparer();
/// <summary>
/// Gets the singleton instance of this class.
/// </summary>
public static Comparer Instance
{
get
{
return Singleton;
}
}
public int Compare(FieldInfoMember x, FieldInfoMember y)
{
return string.Compare(x.FieldInfo.Name, y.FieldInfo.Name, StringComparison.Ordinal);
}
}
}
}
}
| |
//
// redis-sharp.cs: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010 Novell, Inc.
//
// Licensed under the same terms of Redis: new BSD license.
//
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using ServiceStack.Text;
namespace ServiceStack.Redis
{
public partial class RedisNativeClient
{
private void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
SendTimeout = SendTimeout
};
try
{
socket.Connect(Host, Port);
if (!socket.Connected)
{
socket.Close();
socket = null;
return;
}
Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
db = 0;
var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
lastCommand = null;
lastSocketException = null;
LastConnectedAtTimestamp = Stopwatch.GetTimestamp();
if (isPreVersion1_26 == null)
{
isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;
//force version reload
log.DebugFormat("redis-server Version: {0}", isPreVersion1_26);
}
}
catch (SocketException ex)
{
HadExceptions = true;
var throwEx = new InvalidOperationException("could not connect to redis Instance at " + Host + ":" + Port, ex);
log.Error(throwEx.Message, ex);
throw throwEx;
}
}
protected string ReadLine()
{
var sb = new StringBuilder();
int c;
while ((c = Bstream.ReadByte()) != -1)
{
if (c == '\r')
continue;
if (c == '\n')
break;
sb.Append((char)c);
}
return sb.ToString();
}
private bool AssertConnectedSocket()
{
if (LastConnectedAtTimestamp > 0)
{
var now = Stopwatch.GetTimestamp();
var elapsedSecs = (now - LastConnectedAtTimestamp) / Stopwatch.Frequency;
if (elapsedSecs > IdleTimeOutSecs && !socket.IsConnected())
{
return Reconnect();
}
LastConnectedAtTimestamp = now;
}
if (socket == null)
{
var previousDb = db;
Connect();
if (previousDb != DefaultDb) this.Db = previousDb;
}
var isConnected = socket != null;
return isConnected;
}
private bool Reconnect()
{
var previousDb = db;
SafeConnectionClose();
Connect(); //sets db to 0
if (previousDb != DefaultDb) this.Db = previousDb;
return socket != null;
}
private bool HandleSocketException(SocketException ex)
{
HadExceptions = true;
log.Error("SocketException: ", ex);
lastSocketException = ex;
// timeout?
socket.Close();
socket = null;
return false;
}
private RedisResponseException CreateResponseError(string error)
{
HadExceptions = true;
var throwEx = new RedisResponseException(
string.Format("{0}, sPort: {1}, LastCommand: {2}",
error, clientPort, lastCommand));
log.Error(throwEx.Message);
throw throwEx;
}
private Exception CreateConnectionError()
{
HadExceptions = true;
var throwEx = new Exception(
string.Format("Unable to Connect: sPort: {0}",
clientPort), lastSocketException);
log.Error(throwEx.Message);
throw throwEx;
}
private static byte[] GetCmdBytes(char cmdPrefix, int noOfLines)
{
var strLines = noOfLines.ToString();
var strLinesLength = strLines.Length;
var cmdBytes = new byte[1 + strLinesLength + 2];
cmdBytes[0] = (byte)cmdPrefix;
for (var i = 0; i < strLinesLength; i++)
cmdBytes[i + 1] = (byte)strLines[i];
cmdBytes[1 + strLinesLength] = 0x0D; // \r
cmdBytes[2 + strLinesLength] = 0x0A; // \n
return cmdBytes;
}
/// <summary>
/// Command to set multuple binary safe arguments
/// </summary>
/// <param name="cmdWithBinaryArgs"></param>
/// <returns></returns>
protected bool SendCommand(params byte[][] cmdWithBinaryArgs)
{
if (!AssertConnectedSocket()) return false;
try
{
CmdLog(cmdWithBinaryArgs);
//Total command lines count
WriteAllToSendBuffer(cmdWithBinaryArgs);
FlushSendBuffer();
}
catch (SocketException ex)
{
cmdBufferIndex = 0;
return HandleSocketException(ex);
}
return true;
}
public void WriteAllToSendBuffer(params byte[][] cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('*', cmdWithBinaryArgs.Length));
foreach (var safeBinaryValue in cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('$', safeBinaryValue.Length));
WriteToSendBuffer(safeBinaryValue);
WriteToSendBuffer(endData);
}
}
byte[] cmdBuffer = new byte[32 * 1024];
int cmdBufferIndex = 0;
public void WriteToSendBuffer(byte[] cmdBytes)
{
if ((cmdBufferIndex + cmdBytes.Length) > cmdBuffer.Length)
{
const int breathingSpaceToReduceReallocations = (32 * 1024);
var newLargerBuffer = new byte[cmdBufferIndex + cmdBytes.Length + breathingSpaceToReduceReallocations];
Buffer.BlockCopy(cmdBuffer, 0, newLargerBuffer, 0, cmdBuffer.Length);
cmdBuffer = newLargerBuffer;
}
Buffer.BlockCopy(cmdBytes, 0, cmdBuffer, cmdBufferIndex, cmdBytes.Length);
cmdBufferIndex += cmdBytes.Length;
}
public void FlushSendBuffer()
{
socket.Send(cmdBuffer, cmdBufferIndex, SocketFlags.None);
cmdBufferIndex = 0;
}
private int SafeReadByte()
{
return Bstream.ReadByte();
}
private void SendExpectSuccess(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteVoidQueuedCommand(ExpectSuccess);
ExpectQueued();
return;
}
ExpectSuccess();
}
private int SendExpectInt(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteIntQueuedCommand(ReadInt);
ExpectQueued();
return default(int);
}
return ReadInt();
}
private byte[] SendExpectData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteBytesQueuedCommand(ReadData);
ExpectQueued();
return null;
}
return ReadData();
}
private string SendExpectString(params byte[][] cmdWithBinaryArgs)
{
var bytes = SendExpectData(cmdWithBinaryArgs);
return bytes.FromUtf8Bytes();
}
private double SendExpectDouble(params byte[][] cmdWithBinaryArgs)
{
return parseDouble( SendExpectData(cmdWithBinaryArgs) );
}
private double parseDouble(byte[] doubleBytes)
{
var doubleString = Encoding.UTF8.GetString(doubleBytes);
double d;
double.TryParse(doubleString, out d);
return d;
}
private string SendExpectCode(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteBytesQueuedCommand(ReadData);
ExpectQueued();
return null;
}
return ExpectCode();
}
private byte[][] SendExpectMultiData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteMultiBytesQueuedCommand(ReadMultiData);
ExpectQueued();
return new byte[0][];
}
return ReadMultiData();
}
[Conditional("DEBUG")]
protected void Log(string fmt, params object[] args)
{
log.DebugFormat("{0}", string.Format(fmt, args).Trim());
}
[Conditional("DEBUG")]
protected void CmdLog(byte[][] args)
{
var sb = new StringBuilder();
foreach (var arg in args)
{
if (sb.Length > 0)
sb.Append(" ");
sb.Append(arg.FromUtf8Bytes());
}
this.lastCommand = sb.ToString();
if (this.lastCommand.Length > 100)
{
this.lastCommand = this.lastCommand.Substring(0, 100) + "...";
}
log.Debug("S: " + this.lastCommand);
}
protected void ExpectSuccess()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") && s.Length >= 4 ? s.Substring(4) : s);
}
private void ExpectWord(string word)
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (s != word)
throw CreateResponseError(string.Format("Expected '{0}' got '{1}'", word, s));
}
private string ExpectCode()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
return s;
}
protected void ExpectOk()
{
ExpectWord("OK");
}
protected void ExpectQueued()
{
ExpectWord("QUEUED");
}
public int ReadInt()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':' || c == '$')//really strange why ZRANK needs the '$' here
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw CreateResponseError("Unknown reply on integer response: " + c + s);
}
private byte[] ReadData()
{
string r = ReadLine();
Log("R: {0}", r);
if (r.Length == 0)
throw CreateResponseError("Zero length respose");
char c = r[0];
if (c == '-')
throw CreateResponseError(r.StartsWith("-ERR") ? r.Substring(5) : r.Substring(1));
if (c == '$')
{
if (r == "$-1")
return null;
int count;
if (Int32.TryParse(r.Substring(1), out count))
{
var retbuf = new byte[count];
var offset = 0;
while (count > 0)
{
var readCount = Bstream.Read(retbuf, offset, count);
if (readCount <= 0)
throw CreateResponseError("Unexpected end of Stream");
offset += readCount;
count -= readCount;
}
if (Bstream.ReadByte() != '\r' || Bstream.ReadByte() != '\n')
throw CreateResponseError("Invalid termination");
return retbuf;
}
throw CreateResponseError("Invalid length");
}
if (c == ':')
{
//match the return value
return r.Substring(1).ToUtf8Bytes();
}
throw CreateResponseError("Unexpected reply: " + r);
}
private byte[][] ReadMultiData()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
if (count == -1)
{
//redis is in an invalid state
return new byte[0][];
}
var result = new byte[count][];
for (int i = 0; i < count; i++)
result[i] = ReadData();
return result;
}
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private int ReadMultiDataResultCount()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
return count;
}
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private static void AssertListIdAndValue(string listId, byte[] value)
{
if (listId == null)
throw new ArgumentNullException("listId");
if (value == null)
throw new ArgumentNullException("value");
}
private static byte[][] MergeCommandWithKeysAndValues(byte[] cmd, byte[][] keys, byte[][] values)
{
var firstParams = new[] { cmd };
return MergeCommandWithKeysAndValues(firstParams, keys, values);
}
private static byte[][] MergeCommandWithKeysAndValues(byte[] cmd, byte[] firstArg, byte[][] keys, byte[][] values)
{
var firstParams = new[] { cmd, firstArg };
return MergeCommandWithKeysAndValues(firstParams, keys, values);
}
private static byte[][] MergeCommandWithKeysAndValues(byte[][] firstParams,
byte[][] keys, byte[][] values)
{
if (keys == null || keys.Length == 0)
throw new ArgumentNullException("keys");
if (values == null || values.Length == 0)
throw new ArgumentNullException("values");
if (keys.Length != values.Length)
throw new ArgumentException("The number of values must be equal to the number of keys");
var keyValueStartIndex = (firstParams != null) ? firstParams.Length : 0;
var keysAndValuesLength = keys.Length * 2 + keyValueStartIndex;
var keysAndValues = new byte[keysAndValuesLength][];
for (var i = 0; i < keyValueStartIndex; i++)
{
keysAndValues[i] = firstParams[i];
}
var j = 0;
for (var i = keyValueStartIndex; i < keysAndValuesLength; i += 2)
{
keysAndValues[i] = keys[j];
keysAndValues[i + 1] = values[j];
j++;
}
return keysAndValues;
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, params string[] args)
{
var mergedBytes = new byte[1 + args.Length][];
mergedBytes[0] = cmd;
for (var i = 0; i < args.Length; i++)
{
mergedBytes[i + 1] = args[i].ToUtf8Bytes();
}
return mergedBytes;
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, byte[] firstArg, params byte[][] args)
{
var mergedBytes = new byte[2 + args.Length][];
mergedBytes[0] = cmd;
mergedBytes[1] = firstArg;
for (var i = 0; i < args.Length; i++)
{
mergedBytes[i + 2] = args[i];
}
return mergedBytes;
}
protected byte[][] ConvertToBytes(string[] keys)
{
var keyBytes = new byte[keys.Length][];
for (var i = 0; i < keys.Length; i++)
{
var key = keys[i];
keyBytes[i] = key != null ? key.ToUtf8Bytes() : new byte[0];
}
return keyBytes;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition
{
using Microsoft.Azure.Management.Sql.Fluent.SqlVirtualNetworkRule.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Sql.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlFirewallRule.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlElasticPool.Definition;
/// <summary>
/// The stage of the SQL Server definition allowing to specify the SQL Virtual Network Rules.
/// </summary>
public interface IWithVirtualNetworkRule :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Begins the definition of a new SQL Virtual Network Rule to be added to this server.
/// </summary>
/// <param name="virtualNetworkRuleName">The name of the new SQL Virtual Network Rule.</param>
/// <return>The first stage of the new SQL Virtual Network Rule definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlVirtualNetworkRule.Definition.IBlank<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate> DefineVirtualNetworkRule(string virtualNetworkRuleName);
}
/// <summary>
/// A SQL Server definition with sufficient inputs to create a new
/// SQL Server in the cloud, but exposing additional optional inputs to
/// specify.
/// </summary>
public interface IWithCreate :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.Sql.Fluent.ISqlServer>,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithActiveDirectoryAdministrator,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithSystemAssignedManagedServiceIdentity,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithElasticPool,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithDatabase,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithFirewallRule,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithVirtualNetworkRule,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate>
{
}
/// <summary>
/// A SQL Server definition allowing resource group to be set.
/// </summary>
public interface IWithGroup :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition.IWithGroup<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithAdministratorLogin>
{
}
/// <summary>
/// The stage of the SQL Server definition allowing to specify the SQL Firewall rules.
/// </summary>
public interface IWithFirewallRule :
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithFirewallRuleBeta
{
/// <summary>
/// Creates new firewall rule in the SQL Server.
/// </summary>
/// <param name="ipAddress">IpAddress for the firewall rule.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithNewFirewallRule(string ipAddress);
/// <summary>
/// Creates new firewall rule in the SQL Server.
/// </summary>
/// <param name="startIPAddress">Start IP address for the firewall rule.</param>
/// <param name="endIPAddress">End IP address for the firewall rule.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithNewFirewallRule(string startIPAddress, string endIPAddress);
/// <summary>
/// Creates new firewall rule in the SQL Server.
/// </summary>
/// <param name="startIPAddress">Start IP address for the firewall rule.</param>
/// <param name="endIPAddress">End IP address for the firewall rule.</param>
/// <param name="firewallRuleName">Name for the firewall rule.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithNewFirewallRule(string startIPAddress, string endIPAddress, string firewallRuleName);
}
/// <summary>
/// Container interface for all the definitions that need to be implemented.
/// </summary>
public interface IDefinition :
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IBlank,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithGroup,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithAdministratorLogin,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithAdministratorPassword,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithElasticPool,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithDatabase,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithFirewallRule,
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate
{
}
/// <summary>
/// A SQL Server definition setting the managed service identity.
/// </summary>
public interface IWithSystemAssignedManagedServiceIdentity :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Sets a system assigned (local) Managed Service Identity (MSI) for the SQL server resource.
/// </summary>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithSystemAssignedManagedServiceIdentity();
}
/// <summary>
/// A SQL Server definition setting administrator user name.
/// </summary>
public interface IWithAdministratorLogin
{
/// <summary>
/// Sets the administrator login user name.
/// </summary>
/// <param name="administratorLogin">Administrator login user name.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithAdministratorPassword WithAdministratorLogin(string administratorLogin);
}
/// <summary>
/// A SQL Server definition setting admin user password.
/// </summary>
public interface IWithAdministratorPassword
{
/// <summary>
/// Sets the administrator login password.
/// </summary>
/// <param name="administratorLoginPassword">Password for administrator login.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithAdministratorPassword(string administratorLoginPassword);
}
/// <summary>
/// A SQL Server definition for specifying the databases.
/// </summary>
public interface IWithDatabase :
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithDatabaseBeta
{
/// <summary>
/// Creates new database in the SQL Server.
/// </summary>
/// <param name="databaseName">Name of the database to be created.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithNewDatabase(string databaseName);
}
/// <summary>
/// The first stage of the SQL Server definition.
/// </summary>
public interface IBlank :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithRegion<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithGroup>
{
}
/// <summary>
/// A SQL Server definition setting the Active Directory administrator.
/// </summary>
public interface IWithActiveDirectoryAdministrator :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Sets the SQL Active Directory administrator.
/// Azure Active Directory authentication allows you to centrally manage identity and access
/// to your Azure SQL Database V12.
/// </summary>
/// <param name="userLogin">The user or group login; it can be the name or the email address.</param>
/// <param name="id">The user or group unique ID.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithActiveDirectoryAdministrator(string userLogin, string id);
}
/// <summary>
/// A SQL Server definition for specifying elastic pool.
/// </summary>
public interface IWithElasticPool :
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithElasticPoolBeta
{
/// <summary>
/// Creates new elastic pool in the SQL Server.
/// </summary>
/// <param name="elasticPoolName">Name of the elastic pool to be created.</param>
/// <param name="elasticPoolEdition">Edition of the elastic pool.</param>
/// <param name="databaseNames">Names of the database to be included in the elastic pool.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithNewElasticPool(string elasticPoolName, string elasticPoolEdition, params string[] databaseNames);
/// <summary>
/// Creates new elastic pool in the SQL Server.
/// </summary>
/// <param name="elasticPoolName">Name of the elastic pool to be created.</param>
/// <param name="elasticPoolEdition">Edition of the elastic pool.</param>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithNewElasticPool(string elasticPoolName, string elasticPoolEdition);
}
/// <summary>
/// The stage of the SQL Server definition allowing to specify the SQL Firewall rules.
/// </summary>
public interface IWithFirewallRuleBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Sets the Azure services default access to this server to false.
/// The default is to allow Azure services default access to this server via a special
/// firewall rule named "AllowAllWindowsAzureIps" with the start IP "0.0.0.0".
/// </summary>
/// <return>Next stage of the SQL Server definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate WithoutAccessFromAzureServices();
/// <summary>
/// Begins the definition of a new SQL Firewall rule to be added to this server.
/// </summary>
/// <param name="firewallRuleName">The name of the new SQL Firewall rule.</param>
/// <return>The first stage of the new SQL Firewall rule definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlFirewallRule.Definition.IBlank<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate> DefineFirewallRule(string firewallRuleName);
}
/// <summary>
/// A SQL Server definition for specifying the databases.
/// </summary>
public interface IWithDatabaseBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Begins the definition of a new SQL Database to be added to this server.
/// </summary>
/// <param name="databaseName">The name of the new SQL Database.</param>
/// <return>The first stage of the new SQL Database definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.Definition.IBlank<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate> DefineDatabase(string databaseName);
}
/// <summary>
/// A SQL Server definition for specifying elastic pool.
/// </summary>
public interface IWithElasticPoolBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Begins the definition of a new SQL Elastic Pool to be added to this server.
/// </summary>
/// <param name="elasticPoolName">The name of the new SQL Elastic Pool.</param>
/// <return>The first stage of the new SQL Elastic Pool definition.</return>
Microsoft.Azure.Management.Sql.Fluent.SqlElasticPool.Definition.IBlank<Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition.IWithCreate> DefineElasticPool(string elasticPoolName);
}
}
| |
// 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.Globalization;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
/// <summary>
/// Represents a process that hosts an interactive session.
/// </summary>
/// <remarks>
/// Handles spawning of the host process and communication between the local callers and the remote session.
/// </remarks>
internal sealed partial class InteractiveHost : MarshalByRefObject
{
private readonly Type _replServiceProviderType;
private readonly string _hostPath;
private readonly string _initialWorkingDirectory;
// adjustable for testing purposes
private readonly int _millisecondsTimeout;
private const int MaxAttemptsToCreateProcess = 2;
private LazyRemoteService _lazyRemoteService;
private int _remoteServiceInstanceId;
// Remoting channel to communicate with the remote service.
private IpcServerChannel _serverChannel;
private TextWriter _output;
private TextWriter _errorOutput;
internal event Action<bool> ProcessStarting;
public InteractiveHost(
Type replServiceProviderType,
string hostPath,
string workingDirectory,
int millisecondsTimeout = 5000)
{
_millisecondsTimeout = millisecondsTimeout;
_output = TextWriter.Null;
_errorOutput = TextWriter.Null;
_replServiceProviderType = replServiceProviderType;
_hostPath = hostPath;
_initialWorkingDirectory = workingDirectory;
var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full };
_serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), "ReplChannel-" + Guid.NewGuid(), serverProvider);
ChannelServices.RegisterChannel(_serverChannel, ensureSecurity: false);
}
#region Test hooks
internal event Action<char[], int> OutputReceived;
internal event Action<char[], int> ErrorOutputReceived;
internal Process TryGetProcess()
{
InitializedRemoteService initializedService;
return (_lazyRemoteService?.InitializedService != null &&
_lazyRemoteService.InitializedService.TryGetValue(out initializedService)) ? initializedService.ServiceOpt.Process : null;
}
internal Service TryGetService()
{
var initializedService = TryGetOrCreateRemoteServiceAsync().Result;
return initializedService.ServiceOpt?.Service;
}
// Triggered whenever we create a fresh process.
// The ProcessExited event is not hooked yet.
internal event Action<Process> InteractiveHostProcessCreated;
internal IpcServerChannel _ServerChannel
{
get { return _serverChannel; }
}
internal void Dispose(bool joinThreads)
{
Dispose(joinThreads, disposing: true);
}
#endregion
private static string GenerateUniqueChannelLocalName()
{
return typeof(InteractiveHost).FullName + Guid.NewGuid();
}
public override object InitializeLifetimeService()
{
return null;
}
private RemoteService TryStartProcess(CultureInfo culture, CancellationToken cancellationToken)
{
Process newProcess = null;
int newProcessId = -1;
Semaphore semaphore = null;
try
{
int currentProcessId = Process.GetCurrentProcess().Id;
bool semaphoreCreated;
string semaphoreName;
while (true)
{
semaphoreName = "InteractiveHostSemaphore-" + Guid.NewGuid();
semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated);
if (semaphoreCreated)
{
break;
}
semaphore.Close();
cancellationToken.ThrowIfCancellationRequested();
}
var remoteServerPort = "InteractiveHostChannel-" + Guid.NewGuid();
var processInfo = new ProcessStartInfo(_hostPath);
processInfo.Arguments = remoteServerPort + " " + semaphoreName + " " + currentProcessId;
processInfo.WorkingDirectory = _initialWorkingDirectory;
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
processInfo.StandardErrorEncoding = Encoding.UTF8;
processInfo.StandardOutputEncoding = Encoding.UTF8;
newProcess = new Process();
newProcess.StartInfo = processInfo;
// enables Process.Exited event to be raised:
newProcess.EnableRaisingEvents = true;
newProcess.Start();
// test hook:
var processCreated = InteractiveHostProcessCreated;
if (processCreated != null)
{
processCreated(newProcess);
}
cancellationToken.ThrowIfCancellationRequested();
try
{
newProcessId = newProcess.Id;
}
catch
{
newProcessId = 0;
}
// sync:
while (!semaphore.WaitOne(_millisecondsTimeout))
{
if (!CheckAlive(newProcess))
{
return null;
}
_output.WriteLine(FeaturesResources.AttemptToConnectToProcess, newProcessId);
cancellationToken.ThrowIfCancellationRequested();
}
// instantiate remote service:
Service newService;
try
{
newService = (Service)Activator.GetObject(
typeof(Service),
"ipc://" + remoteServerPort + "/" + Service.ServiceName);
cancellationToken.ThrowIfCancellationRequested();
newService.Initialize(_replServiceProviderType, culture.Name);
}
catch (RemotingException) when (!CheckAlive(newProcess))
{
return null;
}
return new RemoteService(this, newProcess, newProcessId, newService);
}
catch (OperationCanceledException)
{
if (newProcess != null)
{
RemoteService.InitiateTermination(newProcess, newProcessId);
}
return null;
}
finally
{
if (semaphore != null)
{
semaphore.Close();
}
}
}
private bool CheckAlive(Process process)
{
bool alive = process.IsAlive();
if (!alive)
{
_errorOutput.WriteLine(FeaturesResources.FailedToLaunchProcess, _hostPath, process.ExitCode);
_errorOutput.WriteLine(process.StandardError.ReadToEnd());
}
return alive;
}
~InteractiveHost()
{
Dispose(joinThreads: false, disposing: false);
}
public void Dispose()
{
Dispose(joinThreads: false, disposing: true);
}
private void Dispose(bool joinThreads, bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
DisposeChannel();
}
if (_lazyRemoteService != null)
{
_lazyRemoteService.Dispose(joinThreads);
_lazyRemoteService = null;
}
}
private void DisposeChannel()
{
if (_serverChannel != null)
{
ChannelServices.UnregisterChannel(_serverChannel);
_serverChannel = null;
}
}
public TextWriter Output
{
get
{
return _output;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var oldOutput = Interlocked.Exchange(ref _output, value);
oldOutput.Flush();
}
}
public TextWriter ErrorOutput
{
get
{
return _errorOutput;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var oldOutput = Interlocked.Exchange(ref _errorOutput, value);
oldOutput.Flush();
}
}
internal void OnOutputReceived(bool error, char[] buffer, int count)
{
var notification = error ? ErrorOutputReceived : OutputReceived;
if (notification != null)
{
notification(buffer, count);
}
var writer = error ? ErrorOutput : Output;
writer.Write(buffer, 0, count);
}
private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization)
{
return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization);
}
private Task OnProcessExited(Process process)
{
ReportProcessExited(process);
return TryGetOrCreateRemoteServiceAsync();
}
private void ReportProcessExited(Process process)
{
int? exitCode;
try
{
exitCode = process.HasExited ? process.ExitCode : (int?)null;
}
catch
{
exitCode = null;
}
if (exitCode.HasValue)
{
_errorOutput.WriteLine(FeaturesResources.HostingProcessExitedWithExitCode, exitCode.Value);
}
}
private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync()
{
try
{
LazyRemoteService currentRemoteService = _lazyRemoteService;
// disposed or not reset:
Debug.Assert(currentRemoteService != null);
for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++)
{
var initializedService = await currentRemoteService.InitializedService.GetValueAsync(currentRemoteService.CancellationSource.Token).ConfigureAwait(false);
if (initializedService.ServiceOpt != null && initializedService.ServiceOpt.Process.IsAlive())
{
return initializedService;
}
// Service failed to start or initialize or the process died.
var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success);
var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService);
if (previousService == currentRemoteService)
{
// we replaced the service whose process we know is dead:
currentRemoteService.Dispose(joinThreads: false);
currentRemoteService = newService;
}
else
{
// the process was reset in between our checks, try to use the new service:
newService.Dispose(joinThreads: false);
currentRemoteService = previousService;
}
}
_errorOutput.WriteLine(FeaturesResources.UnableToCreateHostingProcess);
}
catch (OperationCanceledException)
{
// The user reset the process during initialization.
// The reset operation will recreate the process.
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
return default(InitializedRemoteService);
}
private async Task<TResult> Async<TResult>(Action<Service, RemoteAsyncOperation<TResult>> action)
{
try
{
var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false);
if (initializedService.ServiceOpt == null)
{
return default(TResult);
}
return await new RemoteAsyncOperation<TResult>(initializedService.ServiceOpt).AsyncExecute(action).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<TResult> Async<TResult>(RemoteService remoteService, Action<Service, RemoteAsyncOperation<TResult>> action)
{
try
{
return await new RemoteAsyncOperation<TResult>(remoteService).AsyncExecute(action).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
#region Operations
/// <summary>
/// Restarts and reinitializes the host process (or starts a new one if it is not running yet).
/// </summary>
/// <param name="optionsOpt">The options to initialize the new process with, or null to use the current options (or default options if the process isn't running yet).</param>
public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions optionsOpt)
{
try
{
var options = optionsOpt ?? _lazyRemoteService?.Options ?? new InteractiveHostOptions(null, CultureInfo.CurrentUICulture);
// replace the existing service with a new one:
var newService = CreateRemoteService(options, skipInitialization: false);
LazyRemoteService oldService = Interlocked.Exchange(ref _lazyRemoteService, newService);
if (oldService != null)
{
oldService.Dispose(joinThreads: false);
}
var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false);
if (initializedService.ServiceOpt == null)
{
return default(RemoteExecutionResult);
}
return initializedService.InitializationResult;
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Asynchronously executes given code in the remote interactive session.
/// </summary>
/// <param name="code">The code to execute.</param>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<RemoteExecutionResult> ExecuteAsync(string code)
{
Debug.Assert(code != null);
return Async<RemoteExecutionResult>((service, operation) => service.ExecuteAsync(operation, code));
}
/// <summary>
/// Asynchronously executes given code in the remote interactive session.
/// </summary>
/// <param name="path">The file to execute.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<RemoteExecutionResult> ExecuteFileAsync(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return Async<RemoteExecutionResult>((service, operation) => service.ExecuteFileAsync(operation, path));
}
/// <summary>
/// Asynchronously adds a reference to the set of available references for next submission.
/// </summary>
/// <param name="reference">The reference to add.</param>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<bool> AddReferenceAsync(string reference)
{
Debug.Assert(reference != null);
return Async<bool>((service, operation) => service.AddReferenceAsync(operation, reference));
}
/// <summary>
/// Sets the current session's search paths and base directory.
/// </summary>
public Task<RemoteExecutionResult> SetPathsAsync(string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory)
{
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
return Async<RemoteExecutionResult>((service, operation) => service.SetPathsAsync(operation, referenceSearchPaths, sourceSearchPaths, baseDirectory));
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Task.cs
//
// 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Android.App;
using Java.Util.Concurrent.Atomic;
using Dot42.Internal;
using Dot42.Threading.Tasks;
namespace System.Threading.Tasks
{
//[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
public class Task : IAsyncResult, IDisposable
{
private static readonly AtomicInteger lastId = new AtomicInteger(1);
private static readonly TaskFactory defaultFactory = new TaskFactory();
// With this attribute each thread has its own value so that it's correct for our Schedule code and for Parent property.
//[ThreadStatic]
private static readonly Java.Lang.ThreadLocal<Task> current = new Java.Lang.ThreadLocal<Task>();
private static readonly Task CompletedTask = FromResult(0);
private readonly int id;
private readonly TaskCreationOptions creationOptions;
private TaskStatus status;
private object state;
private TaskActionInvoker invoker;
internal int executing = 0;
private readonly TaskCompletionQueue<IContinuation> continuations = new TaskCompletionQueue<IContinuation>();
private readonly CancellationToken cancellationToken;
private CancellationTokenRegistration? cancellationTokenRegistration;
internal TaskScheduler scheduler;
private TaskExceptionSlot exSlot;
private const TaskCreationOptions MaxTaskCreationOptions = TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent | TaskCreationOptions.DenyChildAttach;
internal const TaskCreationOptions WorkerTaskNotSupportedOptions = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
#region Constuctors
public Task(Action action)
: this(action, TaskCreationOptions.None)
{
}
public Task(Action action, TaskCreationOptions creationOptions)
: this(action, CancellationToken.None, creationOptions)
{
}
public Task(Action action, CancellationToken cancellationToken)
: this(action, cancellationToken, TaskCreationOptions.None)
{
}
public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(TaskActionInvoker.Create(action), null, cancellationToken, creationOptions, current.Get())
{
if (action == null)
throw new ArgumentNullException("action");
if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
throw new ArgumentOutOfRangeException("creationOptions");
}
public Task(Action<object> action, object state)
: this(action, state, TaskCreationOptions.None)
{
}
public Task(Action<object> action, object state, TaskCreationOptions creationOptions)
: this(action, state, CancellationToken.None, creationOptions)
{
}
public Task(Action<object> action, object state, CancellationToken cancellationToken)
: this(action, state, cancellationToken, TaskCreationOptions.None)
{
}
public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(TaskActionInvoker.Create(action), state, cancellationToken, creationOptions, current.Get())
{
if (action == null)
throw new ArgumentNullException("action");
if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
throw new ArgumentOutOfRangeException("creationOptions");
}
internal Task(TaskActionInvoker invoker, object state, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, Task parent = null, Task contAncestor = null, bool ignoreCancellation = false)
{
if (SynchronizationContext.Current == null)
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
this.invoker = invoker;
this.creationOptions = creationOptions;
this.state = state;
this.id = lastId.GetAndIncrement();
this.cancellationToken = cancellationToken;
//this.parent = parent = parent == null ? current : parent;
// this.contAncestor = contAncestor;
this.status = cancellationToken.IsCancellationRequested && !ignoreCancellation ? TaskStatus.Canceled : TaskStatus.Created;
// Process creationOptions
//if (parent != null && HasFlag(creationOptions, TaskCreationOptions.AttachedToParent)
// && !HasFlags(parent.creationOptions, TaskCreationOptions.DenyChildAttach))
// parent.AddChild();
if (cancellationToken.CanBeCanceled && !ignoreCancellation)
cancellationTokenRegistration = cancellationToken.Register(l => ((Task)l).CancelReal(), this);
}
//static bool HasFlag(TaskCreationOptions opt, TaskCreationOptions member)
//{
// return (opt & member) == member;
//}
#endregion
#region Properties
internal CancellationToken CancellationToken
{
get
{
return cancellationToken;
}
}
/// <summary>
/// Gets the state object supplied when the Task was created, or null if none was supplied.
/// </summary>
public object AsyncState
{
get { throw new NotImplementedException("System.Threading.Tasks.Task.AsyncState"); }
}
/// <summary>
/// Gets a WaitHandle that can be used to wait for the task to complete.
/// </summary>
WaitHandle IAsyncResult.AsyncWaitHandle
{
get { throw new NotImplementedException("System.Threading.Tasks.Task.IAsyncResult.AsyncWaitHandle"); }
}
/// <summary>
/// Gets an indication of whether the operation completed synchronously.
/// </summary>
bool IAsyncResult.CompletedSynchronously
{
get { throw new NotImplementedException("System.Threading.Tasks.Task.IAsyncResult.CompletedSynchronously"); }
}
/// <summary>
/// Gets the TaskCreationOptions used to create this task.
/// </summary>
public TaskCreationOptions CreationOptions
{
get { return creationOptions; }
}
// <summary>
// Returns the unique ID of the currently executing Task.
// </summary>
public static int? CurrentId
{
get
{
Task t = current.Get();
return t == null ? (int?)null : t.Id;
}
}
/// <summary>
/// Gets the AggregateException that caused the Task to end prematurely.
/// If the Task completed successfully or has not yet thrown any exceptions, this will return null.
/// </summary>
public AggregateException Exception
{
get { return exSlot != null ? exSlot.Exception : null; }
}
/// <summary>
/// Provides access to factory methods for creating Task and Task<TResult> instances.
/// </summary>
public static TaskFactory Factory
{
get { return defaultFactory; }
}
/// <summary>
/// Gets a unique ID for this Task instance.
/// </summary>
public int Id
{
get { return id; }
}
/// <summary>
/// Gets whether this Task instance has completed execution due to being canceled.
/// </summary>
public bool IsCanceled
{
get { return status == TaskStatus.Canceled; }
}
/// <summary>
/// Gets whether this Task has completed.
/// </summary>
public bool IsCompleted
{
get { return status == TaskStatus.RanToCompletion || status == TaskStatus.Faulted || status == TaskStatus.Canceled; }
}
/// <summary>
/// Gets whether the Task completed due to an unhandled exception.
/// </summary>
public bool IsFaulted
{
get { return status == TaskStatus.Faulted; }
}
/// <summary>
/// Gets the TaskStatus of this task.
/// </summary>
public TaskStatus Status
{
get { return status; }
internal set { status = value; }
}
TaskExceptionSlot ExceptionSlot
{
get
{
if (exSlot != null)
return exSlot;
lock (this)
{
if (exSlot == null)
exSlot = new TaskExceptionSlot(this);
return exSlot;
}
}
}
#endregion
#region Methods
#region Start
public void Start()
{
Start(TaskScheduler.Current);
}
public void Start(TaskScheduler scheduler)
{
if (scheduler == null)
throw new ArgumentNullException("scheduler");
if (status >= TaskStatus.WaitingToRun)
throw new InvalidOperationException("The Task is not in a valid state to be started.");
//if (IsContinuation)
// throw new InvalidOperationException("Start may not be called on a continuation task");
SetupScheduler(scheduler);
Schedule();
}
internal void SetupScheduler(TaskScheduler scheduler)
{
if(scheduler == null)
throw new ArgumentNullException();
this.scheduler = scheduler;
status = TaskStatus.WaitingForActivation;
}
public void RunSynchronously()
{
RunSynchronously(TaskScheduler.Current);
}
public void RunSynchronously(TaskScheduler scheduler)
{
if (scheduler == null)
throw new ArgumentNullException("scheduler");
if (Status > TaskStatus.WaitingForActivation)
throw new InvalidOperationException("The task is not in a valid state to be started");
//if (IsContinuation)
// throw new InvalidOperationException("RunSynchronously may not be called on a continuation task");
RunSynchronouslyCore(scheduler);
}
internal void RunSynchronouslyCore(TaskScheduler scheduler)
{
SetupScheduler(scheduler);
var saveStatus = status;
Status = TaskStatus.WaitingToRun;
try
{
if (scheduler.RunInline(this, false))
return;
}
catch (Exception inner)
{
throw new TaskSchedulerException(inner);
}
Status = saveStatus;
Start(scheduler);
Wait();
}
internal void Schedule()
{
status = TaskStatus.WaitingToRun;
scheduler.QueueTask(this);
}
void ThreadStart()
{
/* Allow scheduler to break fairness of deque ordering without
* breaking its semantic (the task can be executed twice but the
* second time it will return immediately
*/
if (Interlocked.Exchange(ref executing, 1) != 0)
return;
// Disable CancellationToken direct cancellation
if (cancellationTokenRegistration != null)
{
cancellationTokenRegistration.Value.Dispose();
cancellationTokenRegistration = null;
}
// If Task are ran inline on the same thread we might trash these values
var saveCurrent = current.Get();
var saveScheduler = TaskScheduler.Current;
current.Set(this);
#if NET_4_5
TaskScheduler.Current = HasFlag (creationOptions, TaskCreationOptions.HideScheduler) ? TaskScheduler.Default : scheduler;
#else
TaskScheduler.Current = scheduler;
#endif
if (!cancellationToken.IsCancellationRequested)
{
status = TaskStatus.Running;
try
{
InnerInvoke();
}
catch (OperationCanceledException oce)
{
if (cancellationToken != CancellationToken.None && oce.CancellationToken == cancellationToken)
CancelReal();
else
HandleGenericException(oce);
}
catch (Exception e)
{
HandleGenericException(e);
}
}
else
{
CancelReal();
}
if (saveCurrent != null)
current.Set(saveCurrent);
if (saveScheduler != null)
TaskScheduler.Current = saveScheduler;
Finish();
}
internal bool TrySetCanceled()
{
if (IsCompleted)
return false;
//if (!executing.TryRelaxedSet())
//{
// var sw = new SpinWait();
// while (!IsCompleted)
// sw.SpinOnce();
// return false;
//}
CancelReal();
return true;
}
internal bool TrySetException(AggregateException aggregate)
{
if (IsCompleted)
return false;
//if (!executing.TryRelaxedSet())
//{
// var sw = new SpinWait();
// while (!IsCompleted)
// sw.SpinOnce();
// return false;
//}
HandleGenericException(aggregate);
return true;
}
internal bool TrySetExceptionObserved()
{
if (exSlot != null)
{
exSlot.Observed = true;
return true;
}
return false;
}
internal void Execute()
{
ThreadStart();
}
internal void CancelReal()
{
Status = TaskStatus.Canceled;
ProcessCompleteDelegates();
}
void HandleGenericException(Exception e)
{
HandleGenericException(new AggregateException(e));
}
void HandleGenericException(AggregateException e)
{
ExceptionSlot.Exception = e;
//Thread.MemoryBarrier();
Status = TaskStatus.Faulted;
ProcessCompleteDelegates();
}
void InnerInvoke()
{
//if (IsContinuation)
//{
// invoker.Invoke(contAncestor, state, this);
//}
//else
//{
invoker.Invoke(this, state, this);
//}
}
internal void Finish()
{
/*
// If there was children created and they all finished, we set the countdown
if (childTasks != null)
{
if (childTasks.Signal())
ProcessChildExceptions(true);
}
*/
// Don't override Canceled or Faulted
if (status == TaskStatus.Running)
{
//if (childTasks == null || childTasks.IsSet)
Status = TaskStatus.RanToCompletion;
//else
// Status = TaskStatus.WaitingForChildrenToComplete;
}
/*
// Tell parent that we are finished
if (parent != null && HasFlag(creationOptions, TaskCreationOptions.AttachedToParent) &&
#if NET_4_5
!HasFlag (parent.CreationOptions, TaskCreationOptions.DenyChildAttach) &&
#endif
status != TaskStatus.WaitingForChildrenToComplete)
{
parent.ChildCompleted(this.Exception);
}
*/
// Completions are already processed when task is canceled or faulted
if (status == TaskStatus.RanToCompletion)
ProcessCompleteDelegates();
// Reset the current thingies
if (current.Get() == this)
current.Set(null);
if (TaskScheduler.Current == scheduler)
TaskScheduler.Current = null;
if (cancellationTokenRegistration.HasValue)
cancellationTokenRegistration.Value.Dispose();
}
void ProcessCompleteDelegates()
{
if (continuations.HasElements)
{
IContinuation continuation;
while ((continuation = continuations.PollCompletion()) != null)
{
continuation.Execute(this);
}
}
}
#endregion
public void Wait()
{
Wait(Timeout.Infinite, CancellationToken.None);
}
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
public bool Wait(TimeSpan timeout)
{
return Wait(CheckTimeout(timeout), CancellationToken.None);
}
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, CancellationToken.None);
}
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException("millisecondsTimeout");
bool result = WaitCore(millisecondsTimeout, cancellationToken);
if (IsCanceled)
throw new AggregateException(new TaskCanceledException(this));
var exception = Exception;
if (exception != null)
throw exception;
return result;
}
internal bool WaitCore(int millisecondsTimeout, CancellationToken cancellationToken)
{
if (IsCompleted)
return true;
// If the task is ready to be run and we were supposed to wait on it indefinitely without cancellation, just run it
if (Status == TaskStatus.WaitingToRun && millisecondsTimeout == Timeout.Infinite && scheduler != null && !cancellationToken.CanBeCanceled)
scheduler.RunInline(this, true);
bool result = true;
if (!IsCompleted)
{
var continuation = new ManualResetContinuation();
try
{
ContinueWith(continuation);
result = continuation.Wait(millisecondsTimeout, cancellationToken);
}
finally
{
if (!result)
RemoveContinuation(continuation);
continuation.Dispose();
}
}
return result;
}
public static void WaitAll(params Task[] tasks)
{
WaitAll(tasks, Timeout.Infinite, CancellationToken.None);
}
public static void WaitAll(Task[] tasks, CancellationToken cancellationToken)
{
WaitAll(tasks, Timeout.Infinite, cancellationToken);
}
public static bool WaitAll(Task[] tasks, TimeSpan timeout)
{
return WaitAll(tasks, CheckTimeout(timeout), CancellationToken.None);
}
public static bool WaitAll(Task[] tasks, int millisecondsTimeout)
{
return WaitAll(tasks, millisecondsTimeout, CancellationToken.None);
}
public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (tasks == null)
throw new ArgumentNullException("tasks");
bool result = true;
foreach (var t in tasks)
{
if (t == null)
throw new ArgumentException("tasks", "the tasks argument contains a null element");
result &= t.Status == TaskStatus.RanToCompletion;
}
if (!result)
{
var continuation = new CountdownContinuation(tasks.Length);
try
{
foreach (var t in tasks)
t.ContinueWith(continuation);
result = continuation.Wait(millisecondsTimeout, cancellationToken);
}
finally
{
List<Exception> exceptions = null;
foreach (var t in tasks)
{
if (result)
{
if (t.Status == TaskStatus.RanToCompletion)
continue;
if (exceptions == null)
exceptions = new List<Exception>();
if (t.Exception != null)
exceptions.AddRange(t.Exception.InnerExceptions);
else
exceptions.Add(new TaskCanceledException(t));
}
else
{
t.RemoveContinuation(continuation);
}
}
continuation.Dispose();
if (exceptions != null)
throw new AggregateException(exceptions);
}
}
return result;
}
public static int WaitAny(params Task[] tasks)
{
return WaitAny(tasks, Timeout.Infinite, CancellationToken.None);
}
public static int WaitAny(Task[] tasks, TimeSpan timeout)
{
return WaitAny(tasks, CheckTimeout(timeout));
}
public static int WaitAny(Task[] tasks, int millisecondsTimeout)
{
return WaitAny(tasks, millisecondsTimeout, CancellationToken.None);
}
public static int WaitAny(Task[] tasks, CancellationToken cancellationToken)
{
return WaitAny(tasks, Timeout.Infinite, cancellationToken);
}
public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (tasks == null)
throw new ArgumentNullException("tasks");
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException("millisecondsTimeout");
CheckForNullTasks(tasks);
if (tasks.Length > 0)
{
var continuation = new ManualResetContinuation();
bool result = false;
try
{
for (int i = 0; i < tasks.Length; i++)
{
var t = tasks[i];
if (t.IsCompleted)
return i;
t.ContinueWith(continuation);
}
result = continuation.Wait(millisecondsTimeout, cancellationToken);
if (!result) return -1;
}
finally
{
if (!result)
foreach (var t in tasks)
t.RemoveContinuation(continuation);
continuation.Dispose();
}
}
int firstFinished = -1;
for (int i = 0; i < tasks.Length; i++)
{
var t = tasks[i];
if (t.IsCompleted)
{
firstFinished = i;
break;
}
}
return firstFinished;
}
public static Task WhenAll(params Task[] tasks)
{
if (tasks.Length == 0)
return CompletedTask;
return WhenAll(tasks.ToList());
}
public static Task WhenAll(IEnumerable<Task> tasks)
{
return WhenAll(tasks.ToList());
}
private static Task WhenAll(Collections.Generic.IList<Task> tasks)
{
CheckForNullTasks(tasks);
if (tasks.Count == 0)
return CompletedTask;
var task = new TaskCompletionSource<object>();
new WhenAllContinuation(task, tasks);
return task.Task;
}
public static Task WhenAny(params Task[] tasks)
{
if (tasks.Length == 0)
return CompletedTask;
return WhenAny(tasks.ToList());
}
public static Task WhenAny(IEnumerable<Task> tasks)
{
return WhenAny(tasks.ToList());
}
private static Task<Task> WhenAny(Collections.Generic.IList<Task> tasks)
{
CheckForNullTasks(tasks);
if (tasks.Count == 0)
throw new ArgumentException("tasks");
var task = new TaskCompletionSource<Task>();
new WhenAnyContinuation(task, tasks);
return task.Task;
}
public static Task Run(Action action)
{
return Run(action, CancellationToken.None);
}
public static Task Run(Action action, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return TaskConstants.Canceled;
return Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public static Task<TResult> Run<TResult>(Func<TResult> function)
{
return Run(function, CancellationToken.None);
}
public static Task<TResult> Run<TResult>(Func<TResult> function, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return TaskConstants<TResult>.Canceled;
return Task.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public static Task<T> FromResult<T>(T value)
{
var task = new TaskCompletionSource<T>();
task.SetResult(value);
return task.Task;
}
internal void ContinueWith(IContinuation continuation)
{
if (IsCompleted)
{
continuation.Execute(this);
return;
}
continuations.Add(continuation);
// Retry in case completion was achieved but event adding was too late
if (IsCompleted && continuations.Remove(continuation))
continuation.Execute(this);
}
public Task ContinueWith(Action<Task> continuation)
{
var task = new Task(() => continuation(this));
task.SetupScheduler(TaskScheduler.Default);
ContinueWith(new TaskContinuation(task, TaskContinuationOptions.None));
return task;
}
public Task ContinueWith(Action<Task> continuation, TaskContinuationOptions options)
{
var task = new Task(() => continuation(this));
task.SetupScheduler(TaskScheduler.Default);
ContinueWith(new TaskContinuation(task, options));
return task;
}
internal void RemoveContinuation(IContinuation continuation)
{
continuations.Remove(continuation);
}
private static int CheckTimeout(TimeSpan timeout)
{
try
{
return checked((int)timeout.TotalMilliseconds);
}
catch (System.OverflowException)
{
throw new ArgumentOutOfRangeException("timeout");
}
}
private static void CheckForNullTasks(Task[] tasks)
{
foreach (var t in tasks)
if (t == null)
throw new ArgumentException("tasks", "the tasks argument contains a null element");
}
private static void CheckForNullTasks(System.Collections.Generic.IList<Task> tasks)
{
foreach (var t in tasks)
if (t == null)
throw new ArgumentException("tasks", "the tasks argument contains a null element");
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!IsCompleted)
throw new InvalidOperationException("A task may only be disposed if it is in a completion state");
// Set action to null so that the GC can collect the delegate and thus
// any big object references that the user might have captured in a anonymous method
if (disposing)
{
invoker = null;
state = null;
if (cancellationTokenRegistration != null)
cancellationTokenRegistration.Value.Dispose();
}
}
public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
{
return new ConfiguredTaskAwaitable(this, continueOnCapturedContext, null);
}
public ConfiguredTaskAwaitable ConfigureAwait(Activity activity)
{
return ConfigureAwait(new InstanceReference(activity));
}
#if ANDROID_11P
public ConfiguredTaskAwaitable ConfigureAwait(Fragment fragment)
{
return ConfigureAwait(new InstanceReference(fragment));
}
#endif
public ConfiguredTaskAwaitable ConfigureAwait(InstanceReference instanceReference)
{
return new ConfiguredTaskAwaitable(this, true, instanceReference);
}
/// <summary>
/// Gets an awaiter used to await this Task.
/// </summary>
/// <remarks>
/// This method is intended for compiler user rather than use directly in code.
/// </remarks>
public TaskAwaiter GetAwaiter()
{
return new TaskAwaiter(this);
}
public static Task Delay (int millisecondsDelay)
{
return Delay (millisecondsDelay, CancellationToken.None);
}
public static Task Delay (TimeSpan delay)
{
return Delay (CheckTimeout (delay), CancellationToken.None);
}
public static Task Delay (TimeSpan delay, CancellationToken cancellationToken)
{
return Delay (CheckTimeout (delay), cancellationToken);
}
public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
{
var source = new TaskCompletionSource<object>();
var delayed = TaskMonitorService.GetService().Delay((long)millisecondsDelay, source);
if (cancellationToken != CancellationToken.None)
{
cancellationToken.Register(() =>
{
if(delayed.Cancel(false))
source.TrySetCanceled();
});
}
return source.Task;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using Xunit;
[Trait("Owner", "lianwei")]
[Trait("EntityType", "Parser")]
public class TripleSlashParserUnitTest
{
[Trait("Related", "TripleSlashComments")]
[Fact]
public void TestTripleSlashParser()
{
string inputFolder = Path.GetRandomFileName();
Directory.CreateDirectory(inputFolder);
File.WriteAllText(Path.Combine(inputFolder, "Example.cs"), @"
using System;
namespace Example
{
#region Example
static class Program
{
public int Main(string[] args)
{
Console.HelloWorld();
}
}
#endregion
}
");
string input = @"
<member name='T:TestClass1.Partial1'>
<summary>
Partial classes <see cref='T:System.AccessViolationException'/><see cref='T:System.AccessViolationException'/>can not cross assemblies, Test <see langword='null'/>
```
Classes in assemblies are by definition complete.
```
</summary>
<remarks>
<see href=""https://example.org""/>
<see href=""https://example.org"">example</see>
<para>This is <paramref name='ref'/> <paramref />a sample of exception node</para>
<list type='bullet'>
<item>
<description>
<code language = 'c#'>
public class XmlElement
: XmlLinkedNode
</code>
<list type='number'>
<item>
<description>
word inside list->listItem->list->listItem->para.>
the second line.
</description>
</item>
<item>
<description>item2 in numbered list</description>
</item>
</list>
</description>
</item>
<item>
<description>item2 in bullet list</description>
</item>
</list>
</remarks>
<returns>Task<see cref='T:System.AccessViolationException'/> returns</returns>
<param name='input'>This is <see cref='T:System.AccessViolationException'/>the input</param>
<param name = 'output' > This is the output </param >
<exception cref='T:System.Xml.XmlException'>This is a sample of exception node. Ref <see href=""http://exception.com"">Exception</see></exception>
<exception cref='System.Xml.XmlException'>This is a sample of exception node with invalid cref</exception>
<exception cref=''>This is a sample of invalid exception node</exception>
<exception >This is a sample of another invalid exception node</exception>
<example>
This sample shows how to call the <see cref=""M: Microsoft.DocAsCode.EntityModel.TripleSlashCommentParser.GetExceptions(System.String, Microsoft.DocAsCode.EntityModel.ITripleSlashCommentParserContext)""/> method.
<code>
class TestClass
{
static int Main()
{
return GetExceptions(null, null).Count();
}
}
</code>
</example>
<example>
This is another example
</example>
<example>
Check empty code.
<code></code>
</example>
<example>
This is an example using source reference.
<code source='Example.cs' region='Example'/>
</example>
<see cref=""T:Microsoft.DocAsCode.EntityModel.SpecIdHelper""/>
<see cref=""T:System.Diagnostics.SourceSwitch""/>
<see cref=""Overload:System.String.Compare""/>
<see href=""http://exception.com"">Global See section</see>
<see href=""http://exception.com""/>
<seealso cref=""T:System.IO.WaitForChangedResult""/>
<seealso cref=""!:http://google.com"">ABCS</seealso>
<seealso href=""http://www.bing.com"">Hello Bing</seealso>
<seealso href=""http://www.bing.com""/>
</member>";
var context = new TripleSlashCommentParserContext
{
AddReferenceDelegate = null,
PreserveRawInlineComments = false,
Source = new SourceDetail
{
Path = Path.Combine(inputFolder, "Source.cs"),
}
};
var commentModel = TripleSlashCommentModel.CreateModel(input, SyntaxLanguage.CSharp, context);
Assert.True(commentModel.InheritDoc == null, nameof(commentModel.InheritDoc));
var summary = commentModel.Summary;
Assert.Equal(@"
Partial classes <xref href=""System.AccessViolationException"" data-throw-if-not-resolved=""false""></xref><xref href=""System.AccessViolationException"" data-throw-if-not-resolved=""false""></xref>can not cross assemblies, Test <xref uid=""langword_csharp_null"" name=""null"" href=""""></xref>
```
Classes in assemblies are by definition complete.
```
".Replace("\r\n", "\n"), summary);
var returns = commentModel.Returns;
Assert.Equal("Task<xref href=\"System.AccessViolationException\" data-throw-if-not-resolved=\"false\"></xref> returns", returns);
var paramInput = commentModel.Parameters["input"];
Assert.Equal("This is <xref href=\"System.AccessViolationException\" data-throw-if-not-resolved=\"false\"></xref>the input", paramInput);
var remarks = commentModel.Remarks;
Assert.Equal(@"
<a href=""https://example.org"">https://example.org</a>
<a href=""https://example.org"">example</a>
<p>This is <code data-dev-comment-type=""paramref"" class=""paramref"">ref</code> a sample of exception node</p>
<ul><li>
<pre><code class=""lang-c#"">public class XmlElement
: XmlLinkedNode</code></pre>
<ol><li>
word inside list->listItem->list->listItem->para.>
the second line.
</li><li>item2 in numbered list</li></ol>
</li><li>item2 in bullet list</li></ul>
".Replace("\r\n", "\n"),
remarks);
var exceptions = commentModel.Exceptions;
Assert.Single(exceptions);
Assert.Equal("System.Xml.XmlException", exceptions[0].Type);
Assert.Equal(@"This is a sample of exception node. Ref <a href=""http://exception.com"">Exception</a>", exceptions[0].Description);
var example = commentModel.Examples;
var expected = new List<string> {
@"
This sample shows how to call the <see cref=""M: Microsoft.DocAsCode.EntityModel.TripleSlashCommentParser.GetExceptions(System.String, Microsoft.DocAsCode.EntityModel.ITripleSlashCommentParserContext)""></see> method.
<pre><code>class TestClass
{
static int Main()
{
return GetExceptions(null, null).Count();
}
} </code></pre>
".Replace("\r\n", "\n"),
@"
This is another example
".Replace("\r\n", "\n"),
@"
Check empty code.
<pre><code></code></pre>
".Replace("\r\n", "\n"),
@"
This is an example using source reference.
<pre><code source=""Example.cs"" region=""Example""> static class Program
{
public int Main(string[] args)
{
Console.HelloWorld();
}
}</code></pre>
".Replace("\r\n", "\n")};
Assert.Equal(expected, example);
context.PreserveRawInlineComments = true;
commentModel = TripleSlashCommentModel.CreateModel(input, SyntaxLanguage.CSharp, context);
var sees = commentModel.Sees;
Assert.Equal(5, sees.Count);
Assert.Equal("Microsoft.DocAsCode.EntityModel.SpecIdHelper", sees[0].LinkId);
Assert.Null(sees[0].AltText);
Assert.Equal("System.String.Compare*", sees[2].LinkId);
Assert.Null(sees[1].AltText);
Assert.Equal("http://exception.com", sees[3].LinkId);
Assert.Equal("Global See section", sees[3].AltText);
Assert.Equal("http://exception.com", sees[4].AltText);
Assert.Equal("http://exception.com", sees[4].LinkId);
var seeAlsos = commentModel.SeeAlsos;
Assert.Equal(3, seeAlsos.Count);
Assert.Equal("System.IO.WaitForChangedResult", seeAlsos[0].LinkId);
Assert.Null(seeAlsos[0].AltText);
Assert.Equal("http://www.bing.com", seeAlsos[1].LinkId);
Assert.Equal("Hello Bing", seeAlsos[1].AltText);
Assert.Equal("http://www.bing.com", seeAlsos[2].AltText);
Assert.Equal("http://www.bing.com", seeAlsos[2].LinkId);
}
[Trait("Related", "TripleSlashComments")]
[Fact]
public void InheritDoc()
{
const string input = @"
<member name=""M:ClassLibrary1.MyClass.DoThing"">
<inheritdoc />
</member>";
var context = new TripleSlashCommentParserContext
{
AddReferenceDelegate = null,
PreserveRawInlineComments = false,
};
var commentModel = TripleSlashCommentModel.CreateModel(input, SyntaxLanguage.CSharp, context);
Assert.True(commentModel.InheritDoc != null, nameof(commentModel.InheritDoc));
}
[Trait("Related", "TripleSlashComments")]
[Fact]
public void InheritDocWithCref()
{
const string input = @"
<member name=""M:ClassLibrary1.MyClass.DoThing"">
<inheritdoc cref=""M:ClassLibrary1.MyClass.DoThing""/>
</member>";
var context = new TripleSlashCommentParserContext
{
AddReferenceDelegate = null,
PreserveRawInlineComments = false,
};
var commentModel = TripleSlashCommentModel.CreateModel(input, SyntaxLanguage.CSharp, context);
Assert.Equal("ClassLibrary1.MyClass.DoThing", commentModel.InheritDoc);
}
[Trait("Related", "TripleSlashComments")]
[Fact]
public void TestTripleSlashParserForXamlSource()
{
string inputFolder = Path.GetRandomFileName();
Directory.CreateDirectory(inputFolder);
var expectedExampleContent = @" <Grid>
<TextBlock Text=""Hello World"" />
</Grid>";
File.WriteAllText(Path.Combine(inputFolder, "Example.xaml"), $@"
<UserControl x:Class=""Examples""
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""
xmlns:d=""http://schemas.microsoft.com/expression/blend/2008""
mc: Ignorable = ""d""
d:DesignHeight=""300"" d:DesignWidth=""300"" >
<UserControl.Resources>
<!-- <Example> -->
{expectedExampleContent}
<!-- </Example> -->
");
string input = @"
<member name='T:TestClass1.Partial1'>
<summary>
</summary>
<returns>Something</returns>
<example>
This is an example using source reference in a xaml file.
<code source='Example.xaml' region='Example'/>
</example>
</member>";
var context = new TripleSlashCommentParserContext
{
AddReferenceDelegate = null,
PreserveRawInlineComments = false,
Source = new SourceDetail
{
Path = Path.Combine(inputFolder, "Source.cs"),
}
};
var commentModel = TripleSlashCommentModel.CreateModel(input, SyntaxLanguage.CSharp, context);
// using xml to get rid of escaped tags
var example = commentModel.Examples.Single();
var doc = XDocument.Parse($"<root>{example}</root>");
var codeNode = doc.Descendants("code").Single();
var actual = NormalizeWhitespace(codeNode.Value);
var expected = NormalizeWhitespace(expectedExampleContent.Replace("\r\n", "\n"));
Assert.Equal(expected, actual);
}
/// <summary>
/// Normalizes multiple whitespaces into 1 single whitespace to allow ignoring of insignificant whitespaces.
/// </summary>
private string NormalizeWhitespace(String s)
{
var regex = new Regex(@"(?<= ) +");
return regex.Replace(s, String.Empty);
}
}
}
| |
namespace ColorPicker
{
partial class ColorPickerDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.m_tabControl = new System.Windows.Forms.TabControl();
this.m_colorTabPage = new System.Windows.Forms.TabPage();
this.m_knownColorsTabPage = new System.Windows.Forms.TabPage();
this.m_colorList = new ColorPicker.ColorListBox();
this.m_cancel = new System.Windows.Forms.Button();
this.m_ok = new System.Windows.Forms.Button();
this.m_tabControl.SuspendLayout();
this.m_knownColorsTabPage.SuspendLayout();
this.SuspendLayout();
//
// m_tabControl
//
this.m_tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_tabControl.Controls.Add(this.m_colorTabPage);
this.m_tabControl.Controls.Add(this.m_knownColorsTabPage);
this.m_tabControl.Location = new System.Drawing.Point(4, 5);
this.m_tabControl.Name = "m_tabControl";
this.m_tabControl.SelectedIndex = 0;
this.m_tabControl.Size = new System.Drawing.Size(527, 282);
this.m_tabControl.TabIndex = 1;
this.m_tabControl.Selected += new System.Windows.Forms.TabControlEventHandler(this.OnSelected);
//
// m_colorTabPage
//
this.m_colorTabPage.Location = new System.Drawing.Point(4, 22);
this.m_colorTabPage.Name = "m_colorTabPage";
this.m_colorTabPage.Padding = new System.Windows.Forms.Padding(3);
this.m_colorTabPage.Size = new System.Drawing.Size(519, 256);
this.m_colorTabPage.TabIndex = 0;
this.m_colorTabPage.Text = "Colors";
this.m_colorTabPage.UseVisualStyleBackColor = true;
//
// m_knownColorsTabPage
//
this.m_knownColorsTabPage.Controls.Add(this.m_colorList);
this.m_knownColorsTabPage.Location = new System.Drawing.Point(4, 22);
this.m_knownColorsTabPage.Name = "m_knownColorsTabPage";
this.m_knownColorsTabPage.Padding = new System.Windows.Forms.Padding(3);
this.m_knownColorsTabPage.Size = new System.Drawing.Size(519, 256);
this.m_knownColorsTabPage.TabIndex = 1;
this.m_knownColorsTabPage.Text = "Known Colors";
this.m_knownColorsTabPage.UseVisualStyleBackColor = true;
//
// m_colorList
//
this.m_colorList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_colorList.ColumnWidth = 170;
this.m_colorList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.m_colorList.FormattingEnabled = true;
this.m_colorList.ItemHeight = 26;
this.m_colorList.Items.AddRange(new object[] {
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen,
System.Drawing.Color.AliceBlue,
System.Drawing.Color.AntiqueWhite,
System.Drawing.Color.Aqua,
System.Drawing.Color.Aquamarine,
System.Drawing.Color.Azure,
System.Drawing.Color.Beige,
System.Drawing.Color.Bisque,
System.Drawing.Color.Black,
System.Drawing.Color.BlanchedAlmond,
System.Drawing.Color.Blue,
System.Drawing.Color.BlueViolet,
System.Drawing.Color.Brown,
System.Drawing.Color.BurlyWood,
System.Drawing.Color.CadetBlue,
System.Drawing.Color.Chartreuse,
System.Drawing.Color.Chocolate,
System.Drawing.Color.Coral,
System.Drawing.Color.CornflowerBlue,
System.Drawing.Color.Cornsilk,
System.Drawing.Color.Crimson,
System.Drawing.Color.Cyan,
System.Drawing.Color.DarkBlue,
System.Drawing.Color.DarkCyan,
System.Drawing.Color.DarkGoldenrod,
System.Drawing.Color.DarkGray,
System.Drawing.Color.DarkGreen,
System.Drawing.Color.DarkKhaki,
System.Drawing.Color.DarkMagenta,
System.Drawing.Color.DarkOliveGreen,
System.Drawing.Color.DarkOrange,
System.Drawing.Color.DarkOrchid,
System.Drawing.Color.DarkRed,
System.Drawing.Color.DarkSalmon,
System.Drawing.Color.DarkSeaGreen,
System.Drawing.Color.DarkSlateBlue,
System.Drawing.Color.DarkSlateGray,
System.Drawing.Color.DarkTurquoise,
System.Drawing.Color.DarkViolet,
System.Drawing.Color.DeepPink,
System.Drawing.Color.DeepSkyBlue,
System.Drawing.Color.DimGray,
System.Drawing.Color.DodgerBlue,
System.Drawing.Color.Firebrick,
System.Drawing.Color.FloralWhite,
System.Drawing.Color.ForestGreen,
System.Drawing.Color.Fuchsia,
System.Drawing.Color.Gainsboro,
System.Drawing.Color.GhostWhite,
System.Drawing.Color.Gold,
System.Drawing.Color.Goldenrod,
System.Drawing.Color.Gray,
System.Drawing.Color.Green,
System.Drawing.Color.GreenYellow,
System.Drawing.Color.Honeydew,
System.Drawing.Color.HotPink,
System.Drawing.Color.IndianRed,
System.Drawing.Color.Indigo,
System.Drawing.Color.Ivory,
System.Drawing.Color.Khaki,
System.Drawing.Color.Lavender,
System.Drawing.Color.LavenderBlush,
System.Drawing.Color.LawnGreen,
System.Drawing.Color.LemonChiffon,
System.Drawing.Color.LightBlue,
System.Drawing.Color.LightCoral,
System.Drawing.Color.LightCyan,
System.Drawing.Color.LightGoldenrodYellow,
System.Drawing.Color.LightGreen,
System.Drawing.Color.LightGray,
System.Drawing.Color.LightPink,
System.Drawing.Color.LightSalmon,
System.Drawing.Color.LightSeaGreen,
System.Drawing.Color.LightSkyBlue,
System.Drawing.Color.LightSlateGray,
System.Drawing.Color.LightSteelBlue,
System.Drawing.Color.LightYellow,
System.Drawing.Color.Lime,
System.Drawing.Color.LimeGreen,
System.Drawing.Color.Linen,
System.Drawing.Color.Magenta,
System.Drawing.Color.Maroon,
System.Drawing.Color.MediumAquamarine,
System.Drawing.Color.MediumBlue,
System.Drawing.Color.MediumOrchid,
System.Drawing.Color.MediumPurple,
System.Drawing.Color.MediumSeaGreen,
System.Drawing.Color.MediumSlateBlue,
System.Drawing.Color.MediumSpringGreen,
System.Drawing.Color.MediumTurquoise,
System.Drawing.Color.MediumVioletRed,
System.Drawing.Color.MidnightBlue,
System.Drawing.Color.MintCream,
System.Drawing.Color.MistyRose,
System.Drawing.Color.Moccasin,
System.Drawing.Color.NavajoWhite,
System.Drawing.Color.Navy,
System.Drawing.Color.OldLace,
System.Drawing.Color.Olive,
System.Drawing.Color.OliveDrab,
System.Drawing.Color.Orange,
System.Drawing.Color.OrangeRed,
System.Drawing.Color.Orchid,
System.Drawing.Color.PaleGoldenrod,
System.Drawing.Color.PaleGreen,
System.Drawing.Color.PaleTurquoise,
System.Drawing.Color.PaleVioletRed,
System.Drawing.Color.PapayaWhip,
System.Drawing.Color.PeachPuff,
System.Drawing.Color.Peru,
System.Drawing.Color.Pink,
System.Drawing.Color.Plum,
System.Drawing.Color.PowderBlue,
System.Drawing.Color.Purple,
System.Drawing.Color.Red,
System.Drawing.Color.RosyBrown,
System.Drawing.Color.RoyalBlue,
System.Drawing.Color.SaddleBrown,
System.Drawing.Color.Salmon,
System.Drawing.Color.SandyBrown,
System.Drawing.Color.SeaGreen,
System.Drawing.Color.SeaShell,
System.Drawing.Color.Sienna,
System.Drawing.Color.Silver,
System.Drawing.Color.SkyBlue,
System.Drawing.Color.SlateBlue,
System.Drawing.Color.SlateGray,
System.Drawing.Color.Snow,
System.Drawing.Color.SpringGreen,
System.Drawing.Color.SteelBlue,
System.Drawing.Color.Tan,
System.Drawing.Color.Teal,
System.Drawing.Color.Thistle,
System.Drawing.Color.Tomato,
System.Drawing.Color.Turquoise,
System.Drawing.Color.Violet,
System.Drawing.Color.Wheat,
System.Drawing.Color.White,
System.Drawing.Color.WhiteSmoke,
System.Drawing.Color.Yellow,
System.Drawing.Color.YellowGreen});
this.m_colorList.Location = new System.Drawing.Point(6, 10);
this.m_colorList.MultiColumn = true;
this.m_colorList.Name = "m_colorList";
this.m_colorList.Size = new System.Drawing.Size(506, 238);
this.m_colorList.TabIndex = 0;
//
// m_cancel
//
this.m_cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_cancel.Location = new System.Drawing.Point(452, 293);
this.m_cancel.Name = "m_cancel";
this.m_cancel.Size = new System.Drawing.Size(75, 23);
this.m_cancel.TabIndex = 2;
this.m_cancel.Text = "&Cancel";
this.m_cancel.UseVisualStyleBackColor = true;
//
// m_ok
//
this.m_ok.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_ok.DialogResult = System.Windows.Forms.DialogResult.OK;
this.m_ok.Location = new System.Drawing.Point(371, 293);
this.m_ok.Name = "m_ok";
this.m_ok.Size = new System.Drawing.Size(75, 23);
this.m_ok.TabIndex = 2;
this.m_ok.Text = "&OK";
this.m_ok.UseVisualStyleBackColor = true;
//
// ColorPickerDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(534, 326);
this.Controls.Add(this.m_ok);
this.Controls.Add(this.m_cancel);
this.Controls.Add(this.m_tabControl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ColorPickerDialog";
this.Text = "Color Picker";
this.m_tabControl.ResumeLayout(false);
this.m_knownColorsTabPage.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl m_tabControl;
private System.Windows.Forms.TabPage m_knownColorsTabPage;
private System.Windows.Forms.TabPage m_colorTabPage;
private System.Windows.Forms.Button m_ok;
private System.Windows.Forms.Button m_cancel;
private ColorListBox m_colorList;
}
}
| |
using System;
using System.Collections.Generic;
using IdmNet.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// ReSharper disable ObjectCreationAsStatement
// ReSharper disable UseObjectOrCollectionInitializer
namespace IdmNet.Models.Tests
{
[TestClass]
public class msidmPamRequestTests
{
private msidmPamRequest _it;
public msidmPamRequestTests()
{
_it = new msidmPamRequest();
}
[TestMethod]
public void It_has_a_paremeterless_constructor()
{
Assert.AreEqual("msidmPamRequest", _it.ObjectType);
}
[TestMethod]
public void It_has_a_constructor_that_takes_an_IdmResource()
{
var resource = new IdmResource
{
DisplayName = "My Display Name",
Creator = new Person { DisplayName = "Creator Display Name", ObjectID = "Creator ObjectID"},
};
var it = new msidmPamRequest(resource);
Assert.AreEqual("msidmPamRequest", it.ObjectType);
Assert.AreEqual("My Display Name", it.DisplayName);
Assert.AreEqual("Creator Display Name", it.Creator.DisplayName);
}
[TestMethod]
public void It_has_a_constructor_that_takes_an_IdmResource_without_Creator()
{
var resource = new IdmResource
{
DisplayName = "My Display Name",
};
var it = new msidmPamRequest(resource);
Assert.AreEqual("My Display Name", it.DisplayName);
Assert.IsNull(it.Creator);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void It_throws_when_you_try_to_set_ObjectType_to_anything_other_than_its_primary_ObjectType()
{
_it.ObjectType = "Invalid Object Type";
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestCreationMethod()
{
// Act
_it.msidmPamRequestCreationMethod = "A string";
// Assert
Assert.AreEqual("A string", _it.msidmPamRequestCreationMethod);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestElevatedUserSid()
{
// Act
_it.msidmPamRequestElevatedUserSid = "A string";
// Assert
Assert.AreEqual("A string", _it.msidmPamRequestElevatedUserSid);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestExpirationProcessedState()
{
// Act
_it.msidmPamRequestExpirationProcessedState = "A string";
// Assert
Assert.AreEqual("A string", _it.msidmPamRequestExpirationProcessedState);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestExpirationStatusInfo()
{
// Act
_it.msidmPamRequestExpirationStatusInfo = "A string";
// Assert
Assert.AreEqual("A string", _it.msidmPamRequestExpirationStatusInfo);
}
[TestMethod]
public void It_has_msidmPamRequestGroupSidList_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmPamRequestGroupSidList);
}
[TestMethod]
public void It_has_msidmPamRequestGroupSidList_which_can_be_set_back_to_null()
{
// Arrange
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
_it.msidmPamRequestGroupSidList = list;
// Act
_it.msidmPamRequestGroupSidList = null;
// Assert
Assert.IsNull(_it.msidmPamRequestGroupSidList);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestGroupSidList()
{
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
// Act
_it.msidmPamRequestGroupSidList = list;
// Assert
Assert.AreEqual("foo1", _it.msidmPamRequestGroupSidList[0]);
Assert.AreEqual("foo2", _it.msidmPamRequestGroupSidList[1]);
}
[TestMethod]
public void It_has_msidmPamRequestExpirationDate_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmPamRequestExpirationDate);
}
[TestMethod]
public void It_has_msidmPamRequestExpirationDate_which_can_be_set_back_to_null()
{
// Arrange
var now = DateTime.Now;
var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
_it.msidmPamRequestExpirationDate = testTime;
// Act
_it.msidmPamRequestExpirationDate = null;
// Assert
Assert.IsNull(_it.msidmPamRequestExpirationDate);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestExpirationDate()
{
// Act
var now = DateTime.Now;
var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
_it.msidmPamRequestExpirationDate = testTime;
// Assert
Assert.AreEqual(testTime, _it.msidmPamRequestExpirationDate);
}
[TestMethod]
public void It_has_msidmPamRequestRole_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmPamRequestRole);
}
[TestMethod]
public void It_has_msidmPamRequestRole_which_can_be_set_back_to_null()
{
// Arrange
var testIdmResource = new IdmResource { DisplayName = "Test IdmResource" };
_it.msidmPamRequestRole = testIdmResource;
// Act
_it.msidmPamRequestRole = null;
// Assert
Assert.IsNull(_it.msidmPamRequestRole);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestRole()
{
// Act
var testIdmResource = new IdmResource { DisplayName = "Test IdmResource" };
_it.msidmPamRequestRole = testIdmResource;
// Assert
Assert.AreEqual(testIdmResource.DisplayName, _it.msidmPamRequestRole.DisplayName);
}
[TestMethod]
public void It_has_msidmPamRequestTime_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmPamRequestTime);
}
[TestMethod]
public void It_has_msidmPamRequestTime_which_can_be_set_back_to_null()
{
// Arrange
var now = DateTime.Now;
var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
_it.msidmPamRequestTime = testTime;
// Act
_it.msidmPamRequestTime = null;
// Assert
Assert.IsNull(_it.msidmPamRequestTime);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestTime()
{
// Act
var now = DateTime.Now;
var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
_it.msidmPamRequestTime = testTime;
// Assert
Assert.AreEqual(testTime, _it.msidmPamRequestTime);
}
[TestMethod]
public void It_has_msidmPamRequestWasClosed_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmPamRequestWasClosed);
}
[TestMethod]
public void It_has_msidmPamRequestWasClosed_which_can_be_set_back_to_null()
{
// Arrange
_it.msidmPamRequestWasClosed = true;
// Act
_it.msidmPamRequestWasClosed = null;
// Assert
Assert.IsNull(_it.msidmPamRequestWasClosed);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestWasClosed()
{
// Act
_it.msidmPamRequestWasClosed = true;
// Assert
Assert.AreEqual(true, _it.msidmPamRequestWasClosed);
}
[TestMethod]
public void It_has_msidmPamRequestTTL_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmPamRequestTTL);
}
[TestMethod]
public void It_has_msidmPamRequestTTL_which_can_be_set_back_to_null()
{
// Arrange
_it.msidmPamRequestTTL = 123;
// Act
_it.msidmPamRequestTTL = null;
// Assert
Assert.IsNull(_it.msidmPamRequestTTL);
}
[TestMethod]
public void It_can_get_and_set_msidmPamRequestTTL()
{
// Act
_it.msidmPamRequestTTL = 123;
// Assert
Assert.AreEqual(123, _it.msidmPamRequestTTL);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace LaunchAtlanta.FaceSwap.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// System.Data.SqlTypes.SqlDouble
//
// Author:
// Tim Coleman <tim@timcoleman.com>
// Ville Palo <vi64pa@koti.soon.fi>
//
// (C) Copyright 2002 Tim Coleman
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
namespace System.Data.SqlTypes
{
public struct SqlDouble : INullable, IComparable
{
#region Fields
double value;
private bool notNull;
public static readonly SqlDouble MaxValue = new SqlDouble (1.7976931348623157E+308);
public static readonly SqlDouble MinValue = new SqlDouble (-1.7976931348623157E+308);
public static readonly SqlDouble Null;
public static readonly SqlDouble Zero = new SqlDouble (0);
#endregion
#region Constructors
public SqlDouble (double value)
{
this.value = value;
notNull = true;
}
#endregion
#region Properties
public bool IsNull {
get { return !notNull; }
}
public double Value {
get {
if (this.IsNull)
throw new SqlNullValueException ();
else
return value;
}
}
#endregion
#region Methods
public static SqlDouble Add (SqlDouble x, SqlDouble y)
{
return (x + y);
}
public int CompareTo (object value)
{
if (value == null)
return 1;
else if (!(value is SqlDouble))
throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlDouble"));
else if (((SqlDouble)value).IsNull)
return 1;
else
return this.value.CompareTo (((SqlDouble)value).Value);
}
public static SqlDouble Divide (SqlDouble x, SqlDouble y)
{
return (x / y);
}
public override bool Equals (object value)
{
if (!(value is SqlDouble))
return false;
if (this.IsNull && ((SqlDouble)value).IsNull)
return true;
else if (((SqlDouble)value).IsNull)
return false;
else
return (bool) (this == (SqlDouble)value);
}
public static SqlBoolean Equals (SqlDouble x, SqlDouble y)
{
return (x == y);
}
public override int GetHashCode ()
{
long LongValue = (long)value;
return (int)(LongValue ^ (LongValue >> 32));
}
public static SqlBoolean GreaterThan (SqlDouble x, SqlDouble y)
{
return (x > y);
}
public static SqlBoolean GreaterThanOrEqual (SqlDouble x, SqlDouble y)
{
return (x >= y);
}
public static SqlBoolean LessThan (SqlDouble x, SqlDouble y)
{
return (x < y);
}
public static SqlBoolean LessThanOrEqual (SqlDouble x, SqlDouble y)
{
return (x <= y);
}
public static SqlDouble Multiply (SqlDouble x, SqlDouble y)
{
return (x * y);
}
public static SqlBoolean NotEquals (SqlDouble x, SqlDouble y)
{
return (x != y);
}
public static SqlDouble Parse (string s)
{
return new SqlDouble (Double.Parse (s));
}
public static SqlDouble Subtract (SqlDouble x, SqlDouble y)
{
return (x - y);
}
public SqlBoolean ToSqlBoolean ()
{
return ((SqlBoolean)this);
}
public SqlByte ToSqlByte ()
{
return ((SqlByte)this);
}
public SqlDecimal ToSqlDecimal ()
{
return ((SqlDecimal)this);
}
public SqlInt16 ToSqlInt16 ()
{
return ((SqlInt16)this);
}
public SqlInt32 ToSqlInt32 ()
{
return ((SqlInt32)this);
}
public SqlInt64 ToSqlInt64 ()
{
return ((SqlInt64)this);
}
public SqlMoney ToSqlMoney ()
{
return ((SqlMoney)this);
}
public SqlSingle ToSqlSingle ()
{
return ((SqlSingle)this);
}
public SqlString ToSqlString ()
{
return ((SqlString)this);
}
public override string ToString ()
{
if (!notNull)
return "Null";
else
return value.ToString ();
}
public static SqlDouble operator + (SqlDouble x, SqlDouble y)
{
double d = 0;
d = x.Value + y.Value;
if (Double.IsInfinity (d))
throw new OverflowException ();
return new SqlDouble (d);
}
public static SqlDouble operator / (SqlDouble x, SqlDouble y)
{
double d = x.Value / y.Value;
if (Double.IsInfinity (d)) {
if (y.Value == 0)
throw new DivideByZeroException ();
}
return new SqlDouble (d);
}
public static SqlBoolean operator == (SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value == y.Value);
}
public static SqlBoolean operator > (SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value > y.Value);
}
public static SqlBoolean operator >= (SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value >= y.Value);
}
public static SqlBoolean operator != (SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (!(x.Value == y.Value));
}
public static SqlBoolean operator < (SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value < y.Value);
}
public static SqlBoolean operator <= (SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
else
return new SqlBoolean (x.Value <= y.Value);
}
public static SqlDouble operator * (SqlDouble x, SqlDouble y)
{
double d = x.Value * y.Value;
if (Double.IsInfinity (d))
throw new OverflowException ();
return new SqlDouble (d);
}
public static SqlDouble operator - (SqlDouble x, SqlDouble y)
{
double d = x.Value - y.Value;
if (Double.IsInfinity (d))
throw new OverflowException ();
return new SqlDouble (d);
}
public static SqlDouble operator - (SqlDouble n)
{
return new SqlDouble (-(n.Value));
}
public static explicit operator SqlDouble (SqlBoolean x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.ByteValue);
}
public static explicit operator double (SqlDouble x)
{
return x.Value;
}
public static explicit operator SqlDouble (SqlString x)
{
checked {
return SqlDouble.Parse (x.Value);
}
}
public static implicit operator SqlDouble (double x)
{
return new SqlDouble (x);
}
public static implicit operator SqlDouble (SqlByte x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.Value);
}
public static implicit operator SqlDouble (SqlDecimal x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble (x.ToDouble ());
}
public static implicit operator SqlDouble (SqlInt16 x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.Value);
}
public static implicit operator SqlDouble (SqlInt32 x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.Value);
}
public static implicit operator SqlDouble (SqlInt64 x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.Value);
}
public static implicit operator SqlDouble (SqlMoney x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.Value);
}
public static implicit operator SqlDouble (SqlSingle x)
{
if (x.IsNull)
return Null;
else
return new SqlDouble ((double)x.Value);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IfacesEnumsStructsClasses;
namespace DemoApp
{
#region HtmlColorSelectorComboBox control
/// <summary>
/// A control simiulating a combobox with
/// ToolStripHtmlColorSelector as the dropdown part
/// </summary>
public class HtmlColorSelectorComboBox : Control
{
public HtmlColorSelectorComboBox()
{
//To stop flickering and stuff
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.CacheText, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.StandardClick, true);
this.SetStyle(ControlStyles.Opaque, true);
this.Size = new Size(140, MAXIMUM_HEIGHT);
//When dropdown is closed we reset focus back to this control
m_DropDown.Closed += new ToolStripDropDownClosedEventHandler(m_DropDown_Closed);
}
void m_DropDown_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
//Set the focus back to us
this.Focus();
Invalidate();
}
#region Variables
private System.ComponentModel.IContainer components = null;
private ToolStripHtmlColorSelector m_DropDown = new ToolStripHtmlColorSelector();
private Brush m_BackgroundBrush = new SolidBrush(SystemColors.Control);
private bool m_IsHot = false;
private bool m_HasFocus = false;
private bool m_IsDropDownPressed = false;
private int m_Padding = 3;
private int m_colorwidth = 30;
private int m_DropdownDimensions = 15;
private const int MAXIMUM_HEIGHT = 21;
private Rectangle m_textrect = Rectangle.Empty;
private Rectangle m_dropdownrect = Rectangle.Empty;
private Rectangle m_colorrect = Rectangle.Empty;
private string m_DefaultText = "Default";
private System.Drawing.Drawing2D.LinearGradientBrush gradBrush = null;
private int opacity = 0x99;
private string m_strText = string.Empty;
private Color m_tempforecolor = Control.DefaultForeColor;
private Color m_GradientEndColor = Color.White; //ProfessionalColors.ButtonSelectedGradientEnd;
private Color m_GradientStartColor = Color.White; //ProfessionalColors.MenuStripGradientEnd;
private Color m_hovercolor = Color.Blue;
#endregion
#region Properties
public Color SelectedColor
{
get { return m_DropDown.Selector.SelectedColor; }
set { m_DropDown.Selector.SelectedColor = value; }
}
public Color DefaultColor
{
get { return m_DropDown.Selector.DefaultColor; }
set { m_DropDown.Selector.DefaultColor = value; }
}
public string DefaultColorText
{
get { return m_DefaultText; }
set { m_DefaultText = value; }
}
public ToolStripHtmlColorSelector DropDownToolStripContainer
{
get { return m_DropDown; }
}
public HtmlColorSelector ColorSelector
{
get { return m_DropDown.Selector; }
}
public new Size Size
{
get { return new Size(base.Size.Width, MAXIMUM_HEIGHT); }
set
{
if (value.Height == MAXIMUM_HEIGHT)
base.Size = value;
}
}
public override Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
Invalidate();
}
}
public Color TextHoverColor
{
get { return m_hovercolor; }
set
{
m_hovercolor = value;
Invalidate();
}
}
public Color GradientStartColor
{
get { return m_GradientStartColor; }
set
{
m_GradientStartColor = value;
Invalidate();
}
}
public Color GradientEndColor
{
get { return m_GradientEndColor; }
set
{
m_GradientEndColor = value;
Invalidate();
}
}
#endregion
#region Overrides
protected override void OnBackColorChanged(EventArgs e)
{
m_BackgroundBrush = new SolidBrush(this.BackColor);
base.OnBackColorChanged(e);
Invalidate();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if ((components != null))
components.Dispose();
}
base.Dispose(disposing);
}
protected override void OnGotFocus(EventArgs e)
{
m_HasFocus = true;
base.OnGotFocus(e);
Invalidate();
}
protected override void OnLostFocus(EventArgs e)
{
m_HasFocus = false;
base.OnLostFocus(e);
Invalidate();
}
private const int WM_KEYDOWN = 0x0100;
private int m_msgkey = 0;
public override bool PreProcessMessage(ref Message msg)
{
if (msg.Msg == WM_KEYDOWN)
{
m_msgkey = (int)msg.WParam;
if (((Keys)m_msgkey) == Keys.Down)
{
Point location = this.PointToScreen(new Point(this.ClientRectangle.Left, this.ClientRectangle.Top + this.ClientRectangle.Height));
//display color picker
m_DropDown.Show(location, ToolStripDropDownDirection.Default);
return true;
}
else
return base.PreProcessMessage(ref msg);
}
else
return base.PreProcessMessage(ref msg);
}
protected override void OnResize(EventArgs e)
{
if (this.Height > MAXIMUM_HEIGHT)
this.Size = new Size(this.Size.Width, MAXIMUM_HEIGHT);
else
base.OnResize(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (this.Enabled == false)
return;
m_IsHot = true;
base.OnMouseMove(e);
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
if (this.Enabled == false)
return;
m_IsHot = false;
m_IsDropDownPressed = false;
base.OnMouseLeave(e);
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (this.Enabled == false)
return;
m_IsDropDownPressed = true;
base.OnMouseDown(e);
Invalidate();
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (this.Enabled == false)
return;
m_IsDropDownPressed = false;
base.OnMouseUp(e);
Invalidate();
if ((m_dropdownrect.Contains(e.Location)) ||
(m_textrect.Contains(e.Location)))
{
Point location = this.PointToScreen(new Point(this.ClientRectangle.Left, this.ClientRectangle.Top + this.ClientRectangle.Height));
//display color picker
m_DropDown.Show(location, ToolStripDropDownDirection.Default);
}
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(m_BackgroundBrush, this.ClientRectangle);
m_textrect = new Rectangle(this.ClientRectangle.X + m_Padding,
this.ClientRectangle.Y + m_Padding,
this.ClientRectangle.Width - ((m_Padding * 2) + m_DropdownDimensions),
this.ClientRectangle.Height - (m_Padding * 2));
opacity = 0x99; //153
if ((m_IsDropDownPressed) || (!this.Enabled))
opacity = (int)(.4f * opacity + .5f);
gradBrush = new System.Drawing.Drawing2D.LinearGradientBrush(m_textrect,
Color.FromArgb(opacity, m_GradientStartColor),
Color.FromArgb(opacity / 3, m_GradientEndColor),
System.Drawing.Drawing2D.LinearGradientMode.Vertical);
e.Graphics.FillRectangle(gradBrush, m_textrect);
m_dropdownrect = new Rectangle(m_textrect.X + m_textrect.Width,
m_textrect.Y, m_DropdownDimensions, m_DropdownDimensions); //m_textrect.Height);
if (m_IsHot)
{
System.Windows.Forms.ControlPaint.DrawBorder3D(e.Graphics, this.ClientRectangle, Border3DStyle.RaisedOuter);
if (m_IsDropDownPressed)
System.Windows.Forms.ControlPaint.DrawComboButton(e.Graphics, m_dropdownrect, ButtonState.Pushed);
else
System.Windows.Forms.ControlPaint.DrawComboButton(e.Graphics, m_dropdownrect, ButtonState.Normal);
}
else
{
if (this.Enabled)
{
if (m_HasFocus)
System.Windows.Forms.ControlPaint.DrawFocusRectangle(e.Graphics, this.ClientRectangle);
else
System.Windows.Forms.ControlPaint.DrawBorder3D(e.Graphics, this.ClientRectangle, Border3DStyle.SunkenOuter);
if (m_IsDropDownPressed)
System.Windows.Forms.ControlPaint.DrawComboButton(e.Graphics, m_dropdownrect, ButtonState.Pushed);
else
System.Windows.Forms.ControlPaint.DrawComboButton(e.Graphics, m_dropdownrect, ButtonState.Flat);
}
else
{
System.Windows.Forms.ControlPaint.DrawBorder3D(e.Graphics, this.ClientRectangle, Border3DStyle.SunkenOuter);
System.Windows.Forms.ControlPaint.DrawComboButton(e.Graphics, m_dropdownrect, ButtonState.Flat | ButtonState.Inactive);
}
}
m_colorrect = new Rectangle(m_textrect.X, m_textrect.Y,
m_colorwidth, m_textrect.Height);
if (m_DropDown.Selector.SelectedColor != Color.Empty)
{
using (Brush br = new SolidBrush(m_DropDown.Selector.SelectedColor))
{
e.Graphics.FillRectangle(br, m_colorrect);
}
m_strText = m_DropDown.Selector.SelectedColor.Name;
}
else
m_strText = m_DefaultText;
if (this.Enabled)
{
if ((m_IsHot) || (m_IsDropDownPressed))
m_tempforecolor = m_hovercolor;
else
m_tempforecolor = this.ForeColor;
}
else
m_tempforecolor = SystemColors.GrayText; //Color.LightSlateGray;
//Draw text
m_textrect.X = m_textrect.X + m_colorwidth + 1;
m_textrect.Width -= m_colorwidth + 1;
TextRenderer.DrawText(e.Graphics,
m_strText,
this.Font,
m_textrect,
m_tempforecolor,
TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
}
#endregion
}
#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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Buffers;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
public abstract partial class TextReader : MarshalByRefObject, IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n;
for (n = 0; n < count; n++)
{
int ch = Read();
if (ch == -1) break;
buffer[index + n] = (char)ch;
}
return n;
}
// Reads a span of characters. This method will read up to
// count characters from this TextReader into the
// span of characters Returns the actual number of characters read.
//
public virtual int Read(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = Read(array, 0, buffer.Length);
if ((uint)numRead > buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Blocking version of read for span of characters. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = ReadBlock(array, 0, buffer.Length);
if ((uint)numRead > buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public async virtual Task<string> ReadToEndAsync()
{
var sb = new StringBuilder(4096);
char[] chars = ArrayPool<char>.Shared.Rent(4096);
try
{
int len;
while ((len = await ReadAsyncInternal(chars, default).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadAsync(array.Array, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state;
return t.Item1.Read(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
var tuple = new Tuple<TextReader, Memory<char>>(this, buffer);
return new ValueTask<int>(Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state;
return t.Item1.Read(t.Item2.Span);
},
tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadBlockAsync(array.Array, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state;
return t.Item1.ReadBlock(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
int n = 0, i;
do
{
i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false);
n += i;
} while (i > 0 && n < buffer.Length);
return n;
}
#endregion
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string ReadLine()
{
return null;
}
}
public static TextReader Synchronized(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return reader is SyncTextReader ? reader : new SyncTextReader(reader);
}
internal sealed class SyncTextReader : TextReader
{
internal readonly TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => _in.Close();
[MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Peek() => _in.Peek();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read() => _in.Read();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadLine() => _in.ReadLine();
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadToEnd() => _in.ReadToEnd();
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadLineAsync() => Task.FromResult(ReadLine());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(ReadBlock(buffer, index, count));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
/* ====================================================================
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.Collections.ObjectModel;
namespace TestCases.SS.Formula.Eval
{
using System;
using System.IO;
using NUnit.Framework;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using TestCases.HSSF;
using TestCases.SS.Formula.Functions;
using System.Diagnostics;
/**
* Tests formulas and operators as loaded from a Test data spreadsheet.<p/>
* This class does not Test implementors of <c>Function</c> and <c>OperationEval</c> in
* isolation. Much of the Evaluation engine (i.e. <c>HSSFFormulaEvaluator</c>, ...) Gets
* exercised as well. Tests for bug fixes and specific/tricky behaviour can be found in the
* corresponding Test class (<c>TestXxxx</c>) of the target (<c>Xxxx</c>) implementor,
* where execution can be observed more easily.
*
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*/
[TestFixture]
public class TestFormulasFromSpreadsheet
{
private static class Result
{
public const int SOME_EVALUATIONS_FAILED = -1;
public const int ALL_EVALUATIONS_SUCCEEDED = +1;
public const int NO_EVALUATIONS_FOUND = 0;
}
/**
* This class defines constants for navigating around the Test data spreadsheet used for these Tests.
*/
private static class SS
{
/**
* Name of the Test spreadsheet (found in the standard Test data folder)
*/
public static String FILENAME = "FormulaEvalTestData.xls";
/**
* Row (zero-based) in the Test spreadsheet where the operator examples start.
*/
public static int START_OPERATORS_ROW_INDEX = 22; // Row '23'
/**
* Row (zero-based) in the Test spreadsheet where the function examples start.
*/
public static int START_FUNCTIONS_ROW_INDEX = 95; // Row '96'
/**
* Index of the column that Contains the function names
*/
public static int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B'
/**
* Used to indicate when there are no more functions left
*/
public static String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>";
/**
* Index of the column where the Test values start (for each function)
*/
public static short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D'
/**
* Each function takes 4 rows in the Test spreadsheet
*/
public static int NUMBER_OF_ROWS_PER_FUNCTION = 4;
}
private HSSFWorkbook workbook;
private ISheet sheet;
// Note - multiple failures are aggregated before ending.
// If one or more functions fail, a single AssertionException is thrown at the end
private int _functionFailureCount;
private int _functionSuccessCount;
private int _EvaluationFailureCount;
private int _EvaluationSuccessCount;
private static ICell GetExpectedValueCell(IRow row, int columnIndex)
{
if (row == null)
{
return null;
}
return row.GetCell(columnIndex);
}
private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual)
{
if (expected == null)
{
throw new AssertionException(msg + " - Bad Setup data expected value is null");
}
if (actual == null)
{
throw new AssertionException(msg + " - actual value was null");
}
switch (expected.CellType)
{
case CellType.Blank:
Assert.AreEqual(CellType.Blank, actual.CellType, msg);
break;
case CellType.Boolean:
Assert.AreEqual(CellType.Boolean, actual.CellType, msg);
Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg);
break;
case CellType.Error:
Assert.AreEqual(CellType.Error, actual.CellType, msg);
Assert.AreEqual(ErrorEval.GetText(expected.ErrorCellValue), ErrorEval.GetText(actual.ErrorValue), msg);
break;
case CellType.Formula: // will never be used, since we will call method After formula Evaluation
throw new AssertionException("Cannot expect formula as result of formula Evaluation: " + msg);
case CellType.Numeric:
Assert.AreEqual(CellType.Numeric, actual.CellType, msg);
AbstractNumericTestCase.AssertEquals(msg, expected.NumericCellValue, actual.NumberValue,
AbstractNumericTestCase.POS_ZERO, AbstractNumericTestCase.DIFF_TOLERANCE_FACTOR);
break;
case CellType.String:
Assert.AreEqual(CellType.String, actual.CellType, msg);
Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg);
break;
}
}
[SetUp]
protected void SetUp()
{
if (workbook == null)
{
workbook = HSSFTestDataSamples.OpenSampleWorkbook(SS.FILENAME);
sheet = workbook.GetSheetAt(0);
}
_functionFailureCount = 0;
_functionSuccessCount = 0;
_EvaluationFailureCount = 0;
_EvaluationSuccessCount = 0;
}
[Test]
public void TestFunctionsFromTestSpreadsheet()
{
ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, null);
ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null);
// example for debugging individual functions/operators:
// ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, "ConcatEval");
// ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, "AVERAGE");
// confirm results
String successMsg = "There were "
+ _EvaluationSuccessCount + " successful Evaluation(s) and "
+ _functionSuccessCount + " function(s) without error";
if (_functionFailureCount > 0)
{
String msg = _functionFailureCount + " function(s) failed in "
+ _EvaluationFailureCount + " Evaluation(s). " + successMsg;
throw new AssertionException(msg);
}
Debug.WriteLine(this.GetType().Name + ": " + successMsg);
}
/**
* @param startRowIndex row index in the spreadsheet where the first function/operator is found
* @param TestFocusFunctionName name of a single function/operator to Test alone.
* Typically pass <code>null</code> to Test all functions
*/
private void ProcessFunctionGroup(int startRowIndex, String testFocusFunctionName)
{
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
ReadOnlyCollection<String> funcs = FunctionEval.GetSupportedFunctionNames();
int rowIndex = startRowIndex;
while (true)
{
IRow r = sheet.GetRow(rowIndex);
String targetFunctionName = GetTargetFunctionName(r);
if (targetFunctionName == null)
{
throw new AssertionException("Test spreadsheet cell empty on row ("
+ (rowIndex + 1) + "). Expected function name or '"
+ SS.FUNCTION_NAMES_END_SENTINEL + "'");
}
if (targetFunctionName.Equals(SS.FUNCTION_NAMES_END_SENTINEL))
{
// found end of functions list
break;
}
if (testFocusFunctionName == null || targetFunctionName.Equals(testFocusFunctionName, StringComparison.CurrentCultureIgnoreCase))
{
// expected results are on the row below
IRow expectedValuesRow = sheet.GetRow(rowIndex + 1);
if (expectedValuesRow == null)
{
int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row
throw new AssertionException("Missing expected values row for function '"
+ targetFunctionName + " (row " + missingRowNum + ")");
}
switch (ProcessFunctionRow(evaluator, targetFunctionName, r, expectedValuesRow))
{
case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break;
case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break;
default:
throw new SystemException("unexpected result");
case Result.NO_EVALUATIONS_FOUND: // do nothing
String uname = targetFunctionName.ToUpper();
if (startRowIndex >= SS.START_FUNCTIONS_ROW_INDEX &&
funcs.Contains(uname))
{
Debug.WriteLine(uname + ": function is supported but missing test data", "");
}
break;
}
}
rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION;
}
}
/**
*
* @return a constant from the local Result class denoting whether there were any Evaluation
* cases, and whether they all succeeded.
*/
private int ProcessFunctionRow(HSSFFormulaEvaluator Evaluator, String targetFunctionName,
IRow formulasRow, IRow expectedValuesRow)
{
int result = Result.NO_EVALUATIONS_FOUND; // so far
short endcolnum = (short)formulasRow.LastCellNum;
// iterate across the row for all the Evaluation cases
for (int colnum = SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++)
{
ICell c = formulasRow.GetCell(colnum);
if (c == null || c.CellType != CellType.Formula)
{
continue;
}
CellValue actualValue = Evaluator.Evaluate(c);
ICell expectedValueCell = GetExpectedValueCell(expectedValuesRow, colnum);
try
{
ConfirmExpectedResult("Function '" + targetFunctionName + "': Formula: " + c.CellFormula + " @ " + formulasRow.RowNum + ":" + colnum,
expectedValueCell, actualValue);
_EvaluationSuccessCount++;
if (result != Result.SOME_EVALUATIONS_FAILED)
{
result = Result.ALL_EVALUATIONS_SUCCEEDED;
}
}
catch (AssertionException e)
{
_EvaluationFailureCount++;
printshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
}
}
return result;
}
/**
* Useful to keep output concise when expecting many failures to be reported by this Test case
*/
private static void printshortStackTrace(TextWriter ps, AssertionException e)
{
ps.WriteLine(e.Message);
ps.WriteLine(e.StackTrace);
/*StackTraceElement[] stes = e.GetStackTrace();
int startIx = 0;
// skip any top frames inside junit.framework.Assert
while(startIx<stes.Length) {
if(!stes[startIx].GetClassName().Equals(typeof(Assert).Name)) {
break;
}
startIx++;
}
// skip bottom frames (part of junit framework)
int endIx = startIx+1;
while(endIx < stes.Length) {
if (stes[endIx].GetClassName().Equals(typeof(Assert).Name))
{
break;
}
endIx++;
}
if(startIx >= endIx) {
// something went wrong. just print the whole stack trace
e.printStackTrace(ps);
}
endIx -= 4; // skip 4 frames of reflection invocation
ps.println(e.ToString());
for(int i=startIx; i<endIx; i++) {
ps.println("\tat " + stes[i].ToString());
}*/
}
/**
* @return <code>null</code> if cell is missing, empty or blank
*/
private static String GetTargetFunctionName(IRow r)
{
if (r == null)
{
System.Console.Error.WriteLine("Warning - given null row, can't figure out function name");
return null;
}
ICell cell = r.GetCell(SS.COLUMN_INDEX_FUNCTION_NAME);
if (cell == null)
{
System.Console.Error.WriteLine("Warning - Row " + r.RowNum + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name");
return null;
}
if (cell.CellType == CellType.Blank)
{
return null;
}
if (cell.CellType == CellType.String)
{
return cell.RichStringCellValue.String;
}
throw new AssertionException("Bad cell type for 'function name' column: ("
+ cell.CellType + ") row (" + (r.RowNum + 1) + ")");
}
}
}
| |
// 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.
// Build a Directed Graph with 10 nodes
namespace Default {
using System;
public class Graph
{
private Vertex Vfirst = null;
private Vertex Vlast = null;
private Edge Efirst = null;
private Edge Elast = null;
private int WeightSum = 0;
public static int Nodes;
public Graph(int n) { Nodes = n;}
public void SetWeightSum() {
Edge temp = Efirst;
WeightSum = 0;
while(temp != null) {
WeightSum += temp.Weight;
temp = temp.Next;
}
}
public int GetWeightSum() {
return WeightSum;
}
public void BuildEdge(int v1,int v2) {
Vertex n1 = null,n2 = null;
Vertex temp = Vfirst;
while(temp != null) {
if (v1 == temp.Name)
{
//found 1st node..
n1 = temp;
break;
}
else temp = temp.Next;
}
//check if edge already exists
for(int i=0;i<n1.Num_Edges;i++) {
if (v2 == n1.Adjacent[i].Name) return;
}
temp = Vfirst;
while(temp != null) {
if (v2 == temp.Name)
{
//found 2nd node..
n2 = temp;
break;
}
else temp = temp.Next;
}
n1.Adjacent[n1.Num_Edges++]=n2;
Edge temp2 = new Edge(n1,n2);
if(Efirst==null) {
Efirst = temp2;
Elast = temp2;
}
else {
temp2.AddEdge(Elast,temp2);
Elast = temp2;
}
}
public void BuildGraph() {
// Build Nodes
Console.WriteLine("Building Vertices...");
for(int i=0;i< Nodes; i++) {
Vertex temp = new Vertex(i);
if(Vfirst==null) {
Vfirst = temp;
Vlast = temp;
}
else {
temp.AddVertex(Vlast,temp);
Vlast = temp;
}
}
// Build Edges
Console.WriteLine("Building Edges...");
Int32 seed = System.Environment.TickCount;
Random rand = new Random(seed);
for(int i=0;i< Nodes;i++) {
int j = rand.Next(0,Nodes);
for(int k=0;k<j;k++) {
int v2;
while((v2 = rand.Next(0,Nodes))==i); //select a random node, also avoid self-loops
BuildEdge(i,v2); //build edge betn node i and v2
}
}
}
public void CheckIfReachable() {
int[] temp = new int[Nodes];
Vertex t1 = Vfirst;
Console.WriteLine("Making all vertices reachable...");
while(t1 != null) {
for(int i=0;i<t1.Num_Edges;i++) {
if(temp[t1.Adjacent[i].Name] == 0)
temp[t1.Adjacent[i].Name]=1;
}
t1 = t1.Next;
}
for(int v2=0;v2<Nodes;v2++) {
if(temp[v2]==0) { //this vertex is not connected
Int32 seed = System.Environment.TickCount;
Random rand = new Random(seed);
int v1;
while((v1 = rand.Next(0,Nodes))==v2); //select a random node, also avoid self-loops
BuildEdge(v1,v2);
temp[v2]=1;
}
}
}
public void DeleteVertex() {
DeleteVertex(Vfirst);
}
public void DeleteVertex(Vertex v) {
if(v == Vlast) {
Vfirst=null;
Vlast=null;
GC.Collect();
GC.WaitForPendingFinalizers();
return;
}
Vertex temp = v.Next;
v=null;
GC.Collect();
GC.WaitForPendingFinalizers();
DeleteVertex(temp);
temp=null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
public class Vertex
{
public int Name;
//public bool Visited = false;
public Vertex Next;
public Vertex[] Adjacent;
public Edge[] Edges;
public int Num_Edges = 0;
public static int count=0;
public Vertex(int val) {
Name = val;
Next = null;
Adjacent = new Vertex[Graph.Nodes];
}
~Vertex() {
Console.WriteLine("In Finalize of Vertex");
count++;
if(count==100) {
Test.exitCode=100;
}
}
public void AddVertex(Vertex x, Vertex y) {
x.Next = y;
}
public void DeleteAdjacentEntry(int n) {
int temp=Num_Edges;
for(int i=0;i< temp;i++) {
if(n == Adjacent[i].Name) {
for(int j=i;j<Num_Edges;j++)
Adjacent[j] = Adjacent[j+1];
Num_Edges--;
return;
}
}
}
}
public class Edge
{
public int Weight;
public Vertex v1,v2;
public Edge Next;
public Edge(Vertex n1, Vertex n2) {
v1=n1;
v2=n2;
int seed = n1.Name+n2.Name;
Random rand = new Random(seed);
Weight = rand.Next(0,50);
}
public void AddEdge(Edge x, Edge y) {
x.Next = y;
}
}
public class Test
{
public static int exitCode;
public static int Main()
{
exitCode=1;
Console.WriteLine("Test should pass with ExitCode 100");
Console.WriteLine("Building Graph with 100 vertices...");
Graph MyGraph = new Graph(100); // graph with 10 nodes
MyGraph.BuildGraph();
MyGraph.CheckIfReachable();
Console.WriteLine("Deleting all vertices...");
MyGraph.DeleteVertex();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Done...");
return exitCode;
}
}
}
| |
//
// System.IO.BinaryReader
//
// Author:
// Matt Kimball (matt@kimball.net)
// Dick Porter (dick@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright 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 System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using Java.IO;
using Java.Util;
namespace System.IO {
[ComVisible (true)]
public class BinaryReader : IDisposable {
Stream m_stream;
Encoding m_encoding;
byte[] m_buffer;
Decoder decoder;
char[] charBuffer;
byte[] charByteBuffer;
//
// 128 chars should cover most strings in one grab.
//
const int MaxBufferSize = 128;
private bool m_disposed;
public BinaryReader(Stream input)
: this(input, Encoding.UTF8)
{
}
#if NET_4_5
readonly bool leave_open;
public BinaryReader(Stream input, Encoding encoding)
: this (input, encoding, false)
{
}
public BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
#else
const bool leave_open = false;
public BinaryReader(Stream input, Encoding encoding)
#endif
{
if (input == null || encoding == null)
throw new ArgumentNullException("Input or Encoding is a null reference.");
if (!input.CanRead)
throw new ArgumentException("The stream doesn't support reading.");
m_stream = input;
m_encoding = encoding;
#if NET_4_5
leave_open = leaveOpen;
#endif
decoder = encoding.GetDecoder ();
// internal buffer size is documented to be between 16 and the value
// returned by GetMaxByteCount for the specified encoding
m_buffer = new byte [Math.Max (16, encoding.GetMaxByteCount (1))];
}
public virtual Stream BaseStream {
get {
return m_stream;
}
}
public virtual void Close() {
Dispose (true);
m_disposed = true;
}
protected virtual void Dispose (bool disposing)
{
if (disposing && m_stream != null && !leave_open)
m_stream.Close ();
m_disposed = true;
m_buffer = null;
m_encoding = null;
m_stream = null;
charBuffer = null;
}
#if NET_4_0
public void Dispose ()
#else
void IDisposable.Dispose()
#endif
{
Dispose (true);
}
protected virtual void FillBuffer (int numBytes)
{
if (numBytes > m_buffer.Length)
throw new ArgumentOutOfRangeException ("numBytes");
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
if (m_stream==null)
throw new IOException("Stream is invalid");
/* Cope with partial reads */
int pos=0;
while(pos<numBytes) {
int n=m_stream.Read(m_buffer, pos, numBytes-pos);
if(n==0) {
throw new EndOfStreamException();
}
pos+=n;
}
}
public virtual int PeekChar() {
if(m_stream==null) {
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
throw new IOException("Stream is invalid");
}
if ( !m_stream.CanSeek )
{
return -1;
}
char[] result = new char[1];
int bcount;
int ccount = ReadCharBytes (result, 0, 1, out bcount);
// Reposition the stream
m_stream.Position -= bcount;
// If we read 0 characters then return -1
if (ccount == 0)
{
return -1;
}
// Return the single character we read
return result[0];
}
public virtual int Read() {
if (charBuffer == null)
charBuffer = new char [MaxBufferSize];
int count = Read (charBuffer, 0, 1);
if(count == 0) {
/* No chars available */
return -1;
}
return charBuffer [0];
}
public virtual int Read(byte[] buffer, int index, int count) {
if(m_stream==null) {
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
throw new IOException("Stream is invalid");
}
if (buffer == null) {
throw new ArgumentNullException("buffer is null");
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index is less than 0");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count is less than 0");
}
if (buffer.Length - index < count) {
throw new ArgumentException("buffer is too small");
}
int bytes_read=m_stream.Read(buffer, index, count);
return(bytes_read);
}
public virtual int Read(char[] buffer, int index, int count) {
if(m_stream==null) {
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
throw new IOException("Stream is invalid");
}
if (buffer == null) {
throw new ArgumentNullException("buffer is null");
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index is less than 0");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count is less than 0");
}
if (buffer.Length - index < count) {
throw new ArgumentException("buffer is too small");
}
int bytes_read;
return ReadCharBytes (buffer, index, count, out bytes_read);
}
private int ReadCharBytes (char[] buffer, int index, int count, out int bytes_read)
{
int chars_read = 0;
bytes_read = 0;
while (chars_read < count) {
int pos = 0;
while (true) {
CheckBuffer (pos + 1);
int read_byte = m_stream.ReadByte ();
if (read_byte == -1)
/* EOF */
return chars_read;
m_buffer [pos ++] = (byte)read_byte;
bytes_read ++;
int n = m_encoding.GetChars (m_buffer, 0, pos, buffer, index + chars_read);
if (n > 0)
break;
}
chars_read ++;
}
return chars_read;
}
protected int Read7BitEncodedInt() {
int ret = 0;
int shift = 0;
int len;
byte b;
for (len = 0; len < 5; ++len) {
b = ReadByte();
ret = ret | ((b & 0x7f) << shift);
shift += 7;
if ((b & 0x80) == 0)
break;
}
if (len < 5)
return ret;
else
throw new FormatException ("Too many bytes in what should have been a 7 bit encoded Int32.");
}
public virtual bool ReadBoolean() {
// Return value:
// true if the byte is non-zero; otherwise false.
return ReadByte() != 0;
}
public virtual byte ReadByte() {
if (m_stream == null) {
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
throw new IOException ("Stream is invalid");
}
int val = m_stream.ReadByte ();
if (val != -1)
return (byte) val;
throw new EndOfStreamException ();
}
public virtual byte[] ReadBytes(int count) {
if(m_stream==null) {
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
throw new IOException("Stream is invalid");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count is less than 0");
}
/* Can't use FillBuffer() here, because it's OK to
* return fewer bytes than were requested
*/
byte[] buf = new byte[count];
int pos=0;
while(pos < count)
{
int n=m_stream.Read(buf, pos, count-pos);
if(n==0) {
/* EOF */
break;
}
pos+=n;
}
if (pos!=count) {
return Arrays.CopyOf(buf, pos);
}
return buf;
}
public virtual char ReadChar() {
int ch=Read();
if(ch==-1) {
throw new EndOfStreamException();
}
return((char)ch);
}
public virtual char[] ReadChars (int count)
{
if (count < 0) {
throw new ArgumentOutOfRangeException("count is less than 0");
}
if (m_stream == null) {
if (m_disposed)
throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
throw new IOException("Stream is invalid");
}
if (count == 0)
return new char[0];
char[] full = new char[count];
int bytes_read;
int chars = ReadCharBytes (full, 0, count, out bytes_read);
if (chars == 0)
throw new EndOfStreamException();
if (chars != count) {
return Arrays.CopyOf(full, chars);
}
return full;
}
public virtual decimal ReadDecimal() {
var bits = new int[4];
bits[0] = ReadInt32();
bits[1] = ReadInt32();
bits[2] = ReadInt32();
bits[3] = ReadInt32();
return new decimal(bits);
}
public virtual double ReadDouble() {
FillBuffer(8);
var byteArrayInputStream = new ByteArrayInputStream(ReadSwapped(8));
var dataInputStream = new DataInputStream(byteArrayInputStream);
var result = dataInputStream.ReadDouble();
byteArrayInputStream.Close();
dataInputStream.Close();
return result;
}
public virtual short ReadInt16() {
FillBuffer(2);
return((short) (m_buffer[0] | (m_buffer[1] << 8)));
}
public virtual int ReadInt32() {
FillBuffer(4);
return(m_buffer[0] | (m_buffer[1] << 8) |
(m_buffer[2] << 16) | (m_buffer[3] << 24));
}
public virtual long ReadInt64() {
var ret_low = ReadUInt32();
var ret_high = ReadUInt32();
return (long) ((((ulong) ret_high) << 32) | ret_low);
}
[CLSCompliant(false)]
public virtual sbyte ReadSByte() {
return (sbyte) ReadByte ();
}
public virtual string ReadString() {
/* Inspection of BinaryWriter-written files
* shows that the length is given in bytes,
* not chars
*/
int len = Read7BitEncodedInt();
if (len < 0)
throw new IOException ("Invalid binary file (string len < 0)");
if (len == 0)
return String.Empty;
if (charByteBuffer == null) {
charBuffer = new char [m_encoding.GetMaxByteCount (MaxBufferSize)];
charByteBuffer = new byte [MaxBufferSize];
}
//
// We read the string here in small chunks. Also, we
// Attempt to optimize the common case of short strings.
//
StringBuilder sb = null;
do {
int readLen = Math.Min (MaxBufferSize, len);
int n = m_stream.Read (charByteBuffer, 0, readLen);
if (n == 0)
throw new EndOfStreamException();
int cch = decoder.GetChars (charByteBuffer, 0, n, charBuffer, 0);
if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
return new String (charBuffer, 0, cch);
if (sb == null)
// Len is a fairly good estimate of the number of chars in a string
// Most of the time 1 byte == 1 char
sb = new StringBuilder (len);
sb.Append (charBuffer, 0, cch);
len -= readLen;
} while (len > 0);
return sb.ToString();
}
public virtual float ReadSingle() {
FillBuffer(4);
var byteArrayInputStream = new ByteArrayInputStream(ReadSwapped(4));
var dataInputStream = new DataInputStream(byteArrayInputStream);
var result = dataInputStream.ReadFloat();
byteArrayInputStream.Close();
dataInputStream.Close();
return result;
}
[CLSCompliant(false)]
public virtual ushort ReadUInt16() {
FillBuffer(2);
return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
}
[CLSCompliant(false)]
public virtual uint ReadUInt32() {
FillBuffer(4);
return((uint) (m_buffer[0] |
(m_buffer[1] << 8) |
(m_buffer[2] << 16) |
(m_buffer[3] << 24)));
}
[CLSCompliant(false)]
public virtual ulong ReadUInt64()
{
var ret_low = ReadUInt32();
var ret_high = ReadUInt32();
return (((ulong) ret_high) << 32) | ret_low;
}
/* Ensures that m_buffer is at least length bytes
* long, growing it if necessary
*/
private void CheckBuffer(int length)
{
if(m_buffer.Length <= length)
{
m_buffer=Arrays.CopyOf(m_buffer, length);
}
}
private byte[] ReadSwapped(int count)
{
var swappedBytes = new byte[count];
for (int i = 0, j = count - 1; i < count; i++, j--)
swappedBytes[i] = m_buffer[j];
return swappedBytes;
}
}
}
| |
using System;
using System.Globalization;
using TestLibrary;
/// <summary>
/// UInt64.ToString(System.IFormatProvider)
/// </summary>
public class UInt64ToString1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
if (Utilities.IsWindows)
{
// retVal = NegTest1() && retVal; // Disabled until neutral cultures are available
}
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert UInt64MaxValue to string value and using cultureinfo \"en-US\"");
try
{
UInt64 u64 = UInt64.MaxValue;
CultureInfo cultureInfo = new CultureInfo("en-US");
string str = u64.ToString(cultureInfo);
if (str != "18446744073709551615")
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert UInt64MinValue to string value and using cultureinfo \"fr-FR\"");
try
{
UInt64 u64 = UInt64.MinValue;
CultureInfo cultureInfo = new CultureInfo("fr-FR");
string str = u64.ToString(cultureInfo);
if (str != "0")
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: A UInt64 number begin with zeros and using cultureinfo \"en-US\"");
try
{
UInt64 u64 = 00009876;
CultureInfo cultureInfo = new CultureInfo("en-US");
string str = u64.ToString(cultureInfo);
if (str != "9876")
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert a random uint64 to string value and using \"en-GB\"");
try
{
UInt64 u64 = this.GetInt64(0, UInt64.MaxValue);
CultureInfo cultureInfo = new CultureInfo("en-GB");
string str = u64.ToString(cultureInfo);
string str2 = Convert.ToString(u64);
if (str != str2)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: The provider is a null reference");
try
{
UInt64 u64 = 000217639083000;
CultureInfo cultureInfo = null;
string str = u64.ToString(cultureInfo);
if (str != "217639083000")
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The provider argument is invalid");
try
{
UInt64 u64 = 1234500233;
CultureInfo cultureInfo = new CultureInfo("pl");
string str = u64.ToString(cultureInfo);
TestLibrary.TestFramework.LogError("101", "The NotSupportedException is not thrown as expected");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
UInt64ToString1 test = new UInt64ToString1();
TestLibrary.TestFramework.BeginTestCase("UInt64ToString1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region ForTestObject
private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlWriterSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Versioning;
#if !SILVERLIGHT
#if !HIDE_XSL
using System.Xml.Xsl.Runtime;
#endif
#endif
namespace System.Xml {
#if !SILVERLIGHT
public enum XmlOutputMethod {
Xml = 0, // Use Xml 1.0 rules to serialize
Html = 1, // Use Html rules specified by Xslt specification to serialize
Text = 2, // Only serialize text blocks
AutoDetect = 3, // Choose between Xml and Html output methods at runtime (using Xslt rules to do so)
}
#endif
/// <summary>
/// Three-state logic enumeration.
/// </summary>
internal enum TriState {
Unknown = -1,
False = 0,
True = 1,
};
internal enum XmlStandalone {
// Do not change the constants - XmlBinaryWriter depends in it
Omit = 0,
Yes = 1,
No = 2,
}
// XmlWriterSettings class specifies basic features of an XmlWriter.
#if !SILVERLIGHT
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#endif
public sealed class XmlWriterSettings {
//
// Fields
//
#if ASYNC || FEATURE_NETCORE
bool useAsync;
#endif
// Text settings
Encoding encoding;
#if FEATURE_LEGACYNETCF
private bool dontWriteEncodingTag;
#endif
bool omitXmlDecl;
NewLineHandling newLineHandling;
string newLineChars;
TriState indent;
string indentChars;
bool newLineOnAttributes;
bool closeOutput;
NamespaceHandling namespaceHandling;
// Conformance settings
ConformanceLevel conformanceLevel;
bool checkCharacters;
bool writeEndDocumentOnClose;
#if !SILVERLIGHT
// Xslt settings
XmlOutputMethod outputMethod;
List<XmlQualifiedName> cdataSections = new List<XmlQualifiedName>();
bool doNotEscapeUriAttributes;
bool mergeCDataSections;
string mediaType;
string docTypeSystem;
string docTypePublic;
XmlStandalone standalone;
bool autoXmlDecl;
#endif
// read-only flag
bool isReadOnly;
//
// Constructor
//
public XmlWriterSettings() {
Initialize();
}
//
// Properties
//
#if ASYNC || FEATURE_NETCORE
public bool Async {
get {
return useAsync;
}
set {
CheckReadOnly("Async");
useAsync = value;
}
}
#endif
// Text
public Encoding Encoding {
get {
return encoding;
}
set {
CheckReadOnly("Encoding");
encoding = value;
}
}
#if FEATURE_LEGACYNETCF
internal bool DontWriteEncodingTag
{
get
{
return dontWriteEncodingTag;
}
set
{
CheckReadOnly("DontWriteEncodingTag");
dontWriteEncodingTag = value;
}
}
#endif
// True if an xml declaration should *not* be written.
public bool OmitXmlDeclaration {
get {
return omitXmlDecl;
}
set {
CheckReadOnly("OmitXmlDeclaration");
omitXmlDecl = value;
}
}
// See NewLineHandling enum for details.
public NewLineHandling NewLineHandling {
get {
return newLineHandling;
}
set {
CheckReadOnly("NewLineHandling");
if ((uint)value > (uint)NewLineHandling.None) {
throw new ArgumentOutOfRangeException("value");
}
newLineHandling = value;
}
}
// Line terminator string. By default, this is a carriage return followed by a line feed ("\r\n").
public string NewLineChars {
get {
return newLineChars;
}
set {
CheckReadOnly("NewLineChars");
if (value == null) {
throw new ArgumentNullException("value");
}
newLineChars = value;
}
}
// True if output should be indented using rules that are appropriate to the output rules (i.e. Xml, Html, etc).
public bool Indent {
get {
return indent == TriState.True;
}
set {
CheckReadOnly("Indent");
indent = value ? TriState.True : TriState.False;
}
}
// Characters to use when indenting. This is usually tab or some spaces, but can be anything.
public string IndentChars {
get {
return indentChars;
}
set {
CheckReadOnly("IndentChars");
if (value == null) {
throw new ArgumentNullException("value");
}
indentChars = value;
}
}
// Whether or not indent attributes on new lines.
public bool NewLineOnAttributes {
get {
return newLineOnAttributes;
}
set {
CheckReadOnly("NewLineOnAttributes");
newLineOnAttributes = value;
}
}
// Whether or not the XmlWriter should close the underlying stream or TextWriter when Close is called on the XmlWriter.
public bool CloseOutput {
get {
return closeOutput;
}
set {
CheckReadOnly("CloseOutput");
closeOutput = value;
}
}
// Conformance
// See ConformanceLevel enum for details.
public ConformanceLevel ConformanceLevel {
get {
return conformanceLevel;
}
set {
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document) {
throw new ArgumentOutOfRangeException("value");
}
conformanceLevel = value;
}
}
// Whether or not to check content characters that they are valid XML characters.
public bool CheckCharacters {
get {
return checkCharacters;
}
set {
CheckReadOnly("CheckCharacters");
checkCharacters = value;
}
}
// Whether or not to remove duplicate namespace declarations
public NamespaceHandling NamespaceHandling {
get {
return namespaceHandling;
}
set {
CheckReadOnly("NamespaceHandling");
if ((uint)value > (uint)(NamespaceHandling.OmitDuplicates)) {
throw new ArgumentOutOfRangeException("value");
}
namespaceHandling = value;
}
}
//Whether or not to auto complete end-element when close/dispose
public bool WriteEndDocumentOnClose {
get {
return writeEndDocumentOnClose;
}
set {
CheckReadOnly("WriteEndDocumentOnClose");
writeEndDocumentOnClose = value;
}
}
#if !SILVERLIGHT
// Specifies the method (Html, Xml, etc.) that will be used to serialize the result tree.
public XmlOutputMethod OutputMethod {
get {
return outputMethod;
}
internal set {
outputMethod = value;
}
}
#endif
//
// Public methods
//
public void Reset() {
CheckReadOnly("Reset");
Initialize();
}
// Deep clone all settings (except read-only, which is always set to false). The original and new objects
// can now be set independently of each other.
public XmlWriterSettings Clone() {
XmlWriterSettings clonedSettings = MemberwiseClone() as XmlWriterSettings;
#if !SILVERLIGHT
// Deep clone shared settings that are not immutable
clonedSettings.cdataSections = new List<XmlQualifiedName>(cdataSections);
#endif
clonedSettings.isReadOnly = false;
return clonedSettings;
}
//
// Internal properties
//
#if !SILVERLIGHT
// Set of XmlQualifiedNames that identify any elements that need to have text children wrapped in CData sections.
internal List<XmlQualifiedName> CDataSectionElements {
get {
Debug.Assert(cdataSections != null);
return cdataSections;
}
}
// Used in Html writer to disable encoding of uri attributes
public bool DoNotEscapeUriAttributes
{
get
{
return doNotEscapeUriAttributes;
}
set
{
CheckReadOnly("DoNotEscapeUriAttributes");
doNotEscapeUriAttributes = value;
}
}
internal bool MergeCDataSections {
get {
return mergeCDataSections;
}
set {
CheckReadOnly("MergeCDataSections");
mergeCDataSections = value;
}
}
// Used in Html writer when writing Meta element. Null denotes the default media type.
internal string MediaType {
get {
return mediaType;
}
set {
CheckReadOnly("MediaType");
mediaType = value;
}
}
// System Id in doc-type declaration. Null denotes the absence of the system Id.
internal string DocTypeSystem {
get {
return docTypeSystem;
}
set {
CheckReadOnly("DocTypeSystem");
docTypeSystem = value;
}
}
// Public Id in doc-type declaration. Null denotes the absence of the public Id.
internal string DocTypePublic {
get {
return docTypePublic;
}
set {
CheckReadOnly("DocTypePublic");
docTypePublic = value;
}
}
// Yes for standalone="yes", No for standalone="no", and Omit for no standalone.
internal XmlStandalone Standalone {
get {
return standalone;
}
set {
CheckReadOnly("Standalone");
standalone = value;
}
}
// True if an xml declaration should automatically be output (no need to call WriteStartDocument)
internal bool AutoXmlDeclaration {
get {
return autoXmlDecl;
}
set {
CheckReadOnly("AutoXmlDeclaration");
autoXmlDecl = value;
}
}
// If TriState.Unknown, then Indent property was not explicitly set. In this case, the AutoDetect output
// method will default to Indent=true for Html and Indent=false for Xml.
internal TriState IndentInternal {
get {
return indent;
}
set {
indent = value;
}
}
internal bool IsQuerySpecific {
get {
return cdataSections.Count != 0 || docTypePublic != null ||
docTypeSystem != null || standalone == XmlStandalone.Yes;
}
}
#endif
#if !SILVERLIGHT
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
internal XmlWriter CreateWriter(string outputFileName) {
if (outputFileName == null) {
throw new ArgumentNullException("outputFileName");
}
// need to clone the settigns so that we can set CloseOutput to true to make sure the stream gets closed in the end
XmlWriterSettings newSettings = this;
if (!newSettings.CloseOutput) {
newSettings = newSettings.Clone();
newSettings.CloseOutput = true;
}
FileStream fs = null;
try {
// open file stream
#if !ASYNC
fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
#else
fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, useAsync);
#endif
// create writer
return newSettings.CreateWriter(fs);
}
catch {
if (fs != null) {
fs.Close();
}
throw;
}
}
#endif
internal XmlWriter CreateWriter(Stream output) {
if (output == null) {
throw new ArgumentNullException("output");
}
XmlWriter writer;
// create raw writer
#if SILVERLIGHT
Debug.Assert(Encoding.UTF8.WebName == "utf-8");
if (this.Encoding.WebName == "utf-8") { // Encoding.CodePage is not supported in Silverlight
// create raw UTF-8 writer
if (this.Indent) {
writer = new XmlUtf8RawTextWriterIndent(output, this);
}
else {
writer = new XmlUtf8RawTextWriter(output, this);
}
}
else {
// create raw writer for other encodings
if (this.Indent) {
writer = new XmlEncodedRawTextWriterIndent(output, this);
}
else {
writer = new XmlEncodedRawTextWriter(output, this);
}
}
#else
Debug.Assert(Encoding.UTF8.WebName == "utf-8");
if (this.Encoding.WebName == "utf-8") { // Encoding.CodePage is not supported in Silverlight
// create raw UTF-8 writer
switch (this.OutputMethod) {
case XmlOutputMethod.Xml:
if (this.Indent) {
writer = new XmlUtf8RawTextWriterIndent(output, this);
}
else {
writer = new XmlUtf8RawTextWriter(output, this);
}
break;
case XmlOutputMethod.Html:
if (this.Indent) {
writer = new HtmlUtf8RawTextWriterIndent(output, this);
}
else {
writer = new HtmlUtf8RawTextWriter(output, this);
}
break;
case XmlOutputMethod.Text:
writer = new TextUtf8RawTextWriter(output, this);
break;
case XmlOutputMethod.AutoDetect:
writer = new XmlAutoDetectWriter(output, this);
break;
default:
Debug.Assert(false, "Invalid XmlOutputMethod setting.");
return null;
}
}
else {
// Otherwise, create a general-purpose writer than can do any encoding
switch (this.OutputMethod) {
case XmlOutputMethod.Xml:
if (this.Indent) {
writer = new XmlEncodedRawTextWriterIndent(output, this);
}
else {
writer = new XmlEncodedRawTextWriter(output, this);
}
break;
case XmlOutputMethod.Html:
if (this.Indent) {
writer = new HtmlEncodedRawTextWriterIndent(output, this);
}
else {
writer = new HtmlEncodedRawTextWriter(output, this);
}
break;
case XmlOutputMethod.Text:
writer = new TextEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.AutoDetect:
writer = new XmlAutoDetectWriter(output, this);
break;
default:
Debug.Assert(false, "Invalid XmlOutputMethod setting.");
return null;
}
}
// Wrap with Xslt/XQuery specific writer if needed;
// XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer.
if (this.OutputMethod != XmlOutputMethod.AutoDetect) {
if (this.IsQuerySpecific) {
// Create QueryOutputWriter if CData sections or DocType need to be tracked
writer = new QueryOutputWriter((XmlRawWriter)writer, this);
}
}
#endif // !SILVERLIGHT
// wrap with well-formed writer
writer = new XmlWellFormedWriter(writer, this);
#if ASYNC
if (useAsync) {
writer = new XmlAsyncCheckWriter(writer);
}
#endif
return writer;
}
internal XmlWriter CreateWriter(TextWriter output) {
if (output == null) {
throw new ArgumentNullException("output");
}
XmlWriter writer;
// create raw writer
#if SILVERLIGHT
if (this.Indent) {
writer = new XmlEncodedRawTextWriterIndent(output, this);
}
else {
writer = new XmlEncodedRawTextWriter(output, this);
}
#else
switch (this.OutputMethod) {
case XmlOutputMethod.Xml:
if (this.Indent) {
writer = new XmlEncodedRawTextWriterIndent(output, this);
}
else {
writer = new XmlEncodedRawTextWriter(output, this);
}
break;
case XmlOutputMethod.Html:
if (this.Indent) {
writer = new HtmlEncodedRawTextWriterIndent(output, this);
}
else {
writer = new HtmlEncodedRawTextWriter(output, this);
}
break;
case XmlOutputMethod.Text:
writer = new TextEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.AutoDetect:
writer = new XmlAutoDetectWriter(output, this);
break;
default:
Debug.Assert(false, "Invalid XmlOutputMethod setting.");
return null;
}
// XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer.
if (this.OutputMethod != XmlOutputMethod.AutoDetect) {
if (this.IsQuerySpecific) {
// Create QueryOutputWriter if CData sections or DocType need to be tracked
writer = new QueryOutputWriter((XmlRawWriter)writer, this);
}
}
#endif //SILVERLIGHT
// wrap with well-formed writer
writer = new XmlWellFormedWriter(writer, this);
#if ASYNC
if (useAsync) {
writer = new XmlAsyncCheckWriter(writer);
}
#endif
return writer;
}
internal XmlWriter CreateWriter(XmlWriter output) {
if (output == null) {
throw new ArgumentNullException("output");
}
return AddConformanceWrapper(output);
}
internal bool ReadOnly {
get {
return isReadOnly;
}
set {
isReadOnly = value;
}
}
void CheckReadOnly(string propertyName) {
if (isReadOnly) {
throw new XmlException(Res.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName);
}
}
//
// Private methods
//
void Initialize() {
encoding = Encoding.UTF8;
omitXmlDecl = false;
newLineHandling = NewLineHandling.Replace;
newLineChars = Environment.NewLine; // "\r\n" on Windows, "\n" on Unix
indent = TriState.Unknown;
indentChars = " ";
newLineOnAttributes = false;
closeOutput = false;
namespaceHandling = NamespaceHandling.Default;
conformanceLevel = ConformanceLevel.Document;
checkCharacters = true;
writeEndDocumentOnClose = true;
#if !SILVERLIGHT
outputMethod = XmlOutputMethod.Xml;
cdataSections.Clear();
mergeCDataSections = false;
mediaType = null;
docTypeSystem = null;
docTypePublic = null;
standalone = XmlStandalone.Omit;
doNotEscapeUriAttributes = false;
#endif
#if ASYNC || FEATURE_NETCORE
useAsync = false;
#endif
isReadOnly = false;
}
private XmlWriter AddConformanceWrapper(XmlWriter baseWriter) {
ConformanceLevel confLevel = ConformanceLevel.Auto;
XmlWriterSettings baseWriterSettings = baseWriter.Settings;
bool checkValues = false;
bool checkNames = false;
bool replaceNewLines = false;
bool needWrap = false;
if (baseWriterSettings == null) {
// assume the V1 writer already do all conformance checking;
// wrap only if NewLineHandling == Replace or CheckCharacters is true
if (this.newLineHandling == NewLineHandling.Replace) {
replaceNewLines = true;
needWrap = true;
}
if (this.checkCharacters) {
checkValues = true;
needWrap = true;
}
}
else {
if (this.conformanceLevel != baseWriterSettings.ConformanceLevel) {
confLevel = this.ConformanceLevel;
needWrap = true;
}
if (this.checkCharacters && !baseWriterSettings.CheckCharacters) {
checkValues = true;
checkNames = confLevel == ConformanceLevel.Auto;
needWrap = true;
}
if (this.newLineHandling == NewLineHandling.Replace &&
baseWriterSettings.NewLineHandling == NewLineHandling.None) {
replaceNewLines = true;
needWrap = true;
}
}
XmlWriter writer = baseWriter;
if (needWrap) {
if (confLevel != ConformanceLevel.Auto) {
writer = new XmlWellFormedWriter(writer, this);
}
if (checkValues || replaceNewLines) {
writer = new XmlCharCheckingWriter(writer, checkValues, checkNames, replaceNewLines, this.NewLineChars);
}
}
#if !SILVERLIGHT
if (this.IsQuerySpecific && (baseWriterSettings == null || !baseWriterSettings.IsQuerySpecific)) {
// Create QueryOutputWriterV1 if CData sections or DocType need to be tracked
writer = new QueryOutputWriterV1(writer, this);
}
#endif
return writer;
}
//
// Internal methods
//
#if !SILVERLIGHT
#if !HIDE_XSL
/// <summary>
/// Serialize the object to BinaryWriter.
/// </summary>
internal void GetObjectData(XmlQueryDataWriter writer) {
// Encoding encoding;
// NOTE: For Encoding we serialize only CodePage, and ignore EncoderFallback/DecoderFallback.
// It suffices for XSLT purposes, but not in the general case.
Debug.Assert(Encoding.Equals(Encoding.GetEncoding(Encoding.CodePage)), "Cannot serialize encoding correctly");
writer.Write(Encoding.CodePage);
// bool omitXmlDecl;
writer.Write(OmitXmlDeclaration);
// NewLineHandling newLineHandling;
writer.Write((sbyte)NewLineHandling);
// string newLineChars;
writer.WriteStringQ(NewLineChars);
// TriState indent;
writer.Write((sbyte)IndentInternal);
// string indentChars;
writer.WriteStringQ(IndentChars);
// bool newLineOnAttributes;
writer.Write(NewLineOnAttributes);
// bool closeOutput;
writer.Write(CloseOutput);
// ConformanceLevel conformanceLevel;
writer.Write((sbyte)ConformanceLevel);
// bool checkCharacters;
writer.Write(CheckCharacters);
// XmlOutputMethod outputMethod;
writer.Write((sbyte)outputMethod);
// List<XmlQualifiedName> cdataSections;
writer.Write(cdataSections.Count);
foreach (XmlQualifiedName qname in cdataSections) {
writer.Write(qname.Name);
writer.Write(qname.Namespace);
}
// bool mergeCDataSections;
writer.Write(mergeCDataSections);
// string mediaType;
writer.WriteStringQ(mediaType);
// string docTypeSystem;
writer.WriteStringQ(docTypeSystem);
// string docTypePublic;
writer.WriteStringQ(docTypePublic);
// XmlStandalone standalone;
writer.Write((sbyte)standalone);
// bool autoXmlDecl;
writer.Write(autoXmlDecl);
// bool isReadOnly;
writer.Write(ReadOnly);
}
/// <summary>
/// Deserialize the object from BinaryReader.
/// </summary>
internal XmlWriterSettings(XmlQueryDataReader reader) {
// Encoding encoding;
Encoding = Encoding.GetEncoding(reader.ReadInt32());
// bool omitXmlDecl;
OmitXmlDeclaration = reader.ReadBoolean();
// NewLineHandling newLineHandling;
NewLineHandling = (NewLineHandling)reader.ReadSByte(0, (sbyte)NewLineHandling.None);
// string newLineChars;
NewLineChars = reader.ReadStringQ();
// TriState indent;
IndentInternal = (TriState)reader.ReadSByte((sbyte)TriState.Unknown, (sbyte)TriState.True);
// string indentChars;
IndentChars = reader.ReadStringQ();
// bool newLineOnAttributes;
NewLineOnAttributes = reader.ReadBoolean();
// bool closeOutput;
CloseOutput = reader.ReadBoolean();
// ConformanceLevel conformanceLevel;
ConformanceLevel = (ConformanceLevel)reader.ReadSByte(0, (sbyte)ConformanceLevel.Document);
// bool checkCharacters;
CheckCharacters = reader.ReadBoolean();
// XmlOutputMethod outputMethod;
outputMethod = (XmlOutputMethod)reader.ReadSByte(0, (sbyte)XmlOutputMethod.AutoDetect);
// List<XmlQualifiedName> cdataSections;
int length = reader.ReadInt32();
cdataSections = new List<XmlQualifiedName>(length);
for (int idx = 0; idx < length; idx++) {
cdataSections.Add(new XmlQualifiedName(reader.ReadString(), reader.ReadString()));
}
// bool mergeCDataSections;
mergeCDataSections = reader.ReadBoolean();
// string mediaType;
mediaType = reader.ReadStringQ();
// string docTypeSystem;
docTypeSystem = reader.ReadStringQ();
// string docTypePublic;
docTypePublic = reader.ReadStringQ();
// XmlStandalone standalone;
Standalone = (XmlStandalone)reader.ReadSByte(0, (sbyte)XmlStandalone.No);
// bool autoXmlDecl;
autoXmlDecl = reader.ReadBoolean();
// bool isReadOnly;
ReadOnly = reader.ReadBoolean();
}
#else
internal void GetObjectData(object writer) { }
internal XmlWriterSettings(object reader) { }
#endif
#endif
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.HighLevelAPI.MechanismParams;
using Net.Pkcs11Interop.LowLevelAPI81.MechanismParams;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.HighLevelAPI81.MechanismParams
{
/// <summary>
/// Resulting key handles and initialization vectors after performing a DeriveKey method with the CKM_SSL3_KEY_AND_MAC_DERIVE mechanism
/// </summary>
public class CkSsl3KeyMatOut : ICkSsl3KeyMatOut
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Low level structure
/// </summary>
internal CK_SSL3_KEY_MAT_OUT _lowLevelStruct = new CK_SSL3_KEY_MAT_OUT();
/// <summary>
/// Key handle for the resulting Client MAC Secret key
/// </summary>
public IObjectHandle ClientMacSecret
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ClientMacSecret);
}
}
/// <summary>
/// Key handle for the resulting Server MAC Secret key
/// </summary>
public IObjectHandle ServerMacSecret
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ServerMacSecret);
}
}
/// <summary>
/// Key handle for the resulting Client Secret key
/// </summary>
public IObjectHandle ClientKey
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ClientKey);
}
}
/// <summary>
/// Key handle for the resulting Server Secret key
/// </summary>
public IObjectHandle ServerKey
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ServerKey);
}
}
/// <summary>
/// Initialization vector (IV) created for the client
/// </summary>
public byte[] IVClient
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return (_ivLength < 1) ? null : UnmanagedMemory.Read(_lowLevelStruct.IVClient, ConvertUtils.UInt64ToInt32(_ivLength));
}
}
/// <summary>
/// Initialization vector (IV) created for the server
/// </summary>
public byte[] IVServer
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return (_ivLength < 1) ? null : UnmanagedMemory.Read(_lowLevelStruct.IVServer, ConvertUtils.UInt64ToInt32(_ivLength));
}
}
/// <summary>
/// The length of initialization vectors
/// </summary>
private NativeULong _ivLength = 0;
/// <summary>
/// Initializes a new instance of the CkSsl3KeyMatOut class.
/// </summary>
/// <param name='ivLength'>Length of initialization vectors or 0 if IVs are not required</param>
internal CkSsl3KeyMatOut(NativeULong ivLength)
{
_lowLevelStruct.ClientMacSecret = 0;
_lowLevelStruct.ServerMacSecret = 0;
_lowLevelStruct.ClientKey = 0;
_lowLevelStruct.ServerKey = 0;
_lowLevelStruct.IVClient = IntPtr.Zero;
_lowLevelStruct.IVServer = IntPtr.Zero;
_ivLength = ivLength;
if (_ivLength > 0)
{
_lowLevelStruct.IVClient = UnmanagedMemory.Allocate(ConvertUtils.UInt64ToInt32(_ivLength));
_lowLevelStruct.IVServer = UnmanagedMemory.Allocate(ConvertUtils.UInt64ToInt32(_ivLength));
}
}
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
}
// Dispose unmanaged objects
UnmanagedMemory.Free(ref _lowLevelStruct.IVClient);
UnmanagedMemory.Free(ref _lowLevelStruct.IVServer);
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkSsl3KeyMatOut()
{
Dispose(false);
}
#endregion
}
}
| |
// 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.Globalization;
using Xunit;
public static class ByteTests
{
[Fact]
public static void TestCtor()
{
Byte i = new Byte();
Assert.True(i == 0);
i = 41;
Assert.True(i == 41);
}
[Fact]
public static void TestMaxValue()
{
Byte max = Byte.MaxValue;
Assert.True(max == (Byte)0xFF);
}
[Fact]
public static void TestMinValue()
{
Byte min = Byte.MinValue;
Assert.True(min == 0);
}
[Fact]
public static void TestCompareToObject()
{
Byte i = 234;
IComparable comparable = i;
Assert.Equal(1, comparable.CompareTo(null));
Assert.Equal(0, comparable.CompareTo((Byte)234));
Assert.True(comparable.CompareTo(Byte.MinValue) > 0);
Assert.True(comparable.CompareTo((Byte)0) > 0);
Assert.True(comparable.CompareTo((Byte)(23)) > 0);
Assert.True(comparable.CompareTo((Byte)123) > 0);
Assert.True(comparable.CompareTo((Byte)45) > 0);
Assert.True(comparable.CompareTo(Byte.MaxValue) < 0);
Assert.Throws<ArgumentException>(() => comparable.CompareTo("a"));
}
[Fact]
public static void TestCompareTo()
{
Byte i = 234;
Assert.Equal(0, i.CompareTo((Byte)234));
Assert.True(i.CompareTo(Byte.MinValue) > 0);
Assert.True(i.CompareTo((Byte)0) > 0);
Assert.True(i.CompareTo((Byte)123) > 0);
Assert.True(i.CompareTo((Byte)45) > 0);
Assert.True(i.CompareTo(Byte.MaxValue) < 0);
}
[Fact]
public static void TestEqualsObject()
{
Byte i = 78;
object obj1 = (Byte)78;
Assert.True(i.Equals(obj1));
object obj3 = (Byte)0;
Assert.True(!i.Equals(obj3));
}
[Fact]
public static void TestEquals()
{
Byte i = 91;
Assert.True(i.Equals((Byte)91));
Assert.True(!i.Equals((Byte)0));
}
[Fact]
public static void TestGetHashCode()
{
Byte i1 = 123;
Byte i2 = 65;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
Byte i1 = 63;
Assert.Equal("63", i1.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new System.Globalization.NumberFormatInfo();
Byte i1 = 63;
Assert.Equal("63", i1.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
Byte i1 = 63;
Assert.Equal("63", i1.ToString("G"));
Byte i2 = 82;
Assert.Equal("82", i2.ToString("g"));
Byte i3 = 246;
Assert.Equal(string.Format("{0:N}", 246.00), i3.ToString("N"));
Byte i4 = 0x24;
Assert.Equal("24", i4.ToString("x"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new System.Globalization.NumberFormatInfo();
Byte i1 = 63;
Assert.Equal("63", i1.ToString("G", numberFormat));
Byte i2 = 82;
Assert.Equal("82", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
numberFormat.NumberDecimalSeparator = ".";
Byte i3 = 24;
Assert.Equal("24.00", i3.ToString("N", numberFormat));
}
[Fact]
public static void TestParse()
{
Assert.Equal<Byte>(123, Byte.Parse("123"));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseNumberStyle()
{
Assert.Equal<Byte>(0x12, Byte.Parse("12", NumberStyles.HexNumber));
Assert.Equal<Byte>(10, Byte.Parse("10", NumberStyles.AllowThousands));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseFormatProvider()
{
var nfi = new NumberFormatInfo();
Assert.Equal<Byte>(123, Byte.Parse("123", nfi));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseNumberStyleFormatProvider()
{
var nfi = new NumberFormatInfo();
Assert.Equal<Byte>(0x12, Byte.Parse("12", NumberStyles.HexNumber, nfi));
nfi.CurrencySymbol = "$";
Assert.Equal<Byte>(100, Byte.Parse("$100", NumberStyles.Currency, nfi));
//TODO: Negative tests once we get better exception support
}
[Fact]
public static void TestTryParse()
{
// Defaults NumberStyles.Integer = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign
Byte i;
Assert.True(Byte.TryParse("123", out i)); // Simple
Assert.Equal<Byte>(123, i);
Assert.False(Byte.TryParse("-38", out i)); // LeadingSign negative
Assert.True(Byte.TryParse(" 67 ", out i)); // Leading/Trailing whitespace
Assert.Equal<Byte>(67, i);
Assert.False(Byte.TryParse((100).ToString("C0"), out i)); // Currency
Assert.False(Byte.TryParse((1000).ToString("N0"), out i)); // Thousands
Assert.False(Byte.TryParse("ab", out i)); // Hex digits
Assert.False(Byte.TryParse((67.90).ToString("F2"), out i)); // Decimal
Assert.False(Byte.TryParse("(135)", out i)); // Parentheses
Assert.False(Byte.TryParse("1E23", out i)); // Exponent
}
[Fact]
public static void TestTryParseNumberStyleFormatProvider()
{
Byte i;
var nfi = new NumberFormatInfo();
Assert.True(Byte.TryParse("123", NumberStyles.Any, nfi, out i)); // Simple positive
Assert.Equal<Byte>(123, i);
Assert.True(Byte.TryParse("12", NumberStyles.HexNumber, nfi, out i)); // Simple Hex
Assert.Equal<Byte>(0x12, i);
nfi.CurrencySymbol = "$";
Assert.True(Byte.TryParse("$100", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive
Assert.Equal<Byte>(100, i);
Assert.False(Byte.TryParse("ab", NumberStyles.None, nfi, out i)); // Hex Number negative
Assert.True(Byte.TryParse("ab", NumberStyles.HexNumber, nfi, out i)); // Hex Number positive
Assert.Equal<Byte>(0xab, i);
nfi.NumberDecimalSeparator = ".";
Assert.False(Byte.TryParse("67.90", NumberStyles.Integer, nfi, out i)); // Decimal
Assert.False(Byte.TryParse(" 67 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative
Assert.False(Byte.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese negative
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace KGSBrowseMVC.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using OrchardCore.Environment.Shell;
namespace OrchardCore.Navigation
{
public class NavigationManager : INavigationManager
{
private readonly IEnumerable<INavigationProvider> _navigationProviders;
private readonly ILogger _logger;
protected readonly ShellSettings _shellSettings;
private readonly IUrlHelperFactory _urlHelperFactory;
private readonly IAuthorizationService _authorizationService;
private IUrlHelper _urlHelper;
public NavigationManager(
IEnumerable<INavigationProvider> navigationProviders,
ILogger<NavigationManager> logger,
ShellSettings shellSettings,
IUrlHelperFactory urlHelperFactory,
IAuthorizationService authorizationService
)
{
_navigationProviders = navigationProviders;
_logger = logger;
_shellSettings = shellSettings;
_urlHelperFactory = urlHelperFactory;
_authorizationService = authorizationService;
}
public async Task<IEnumerable<MenuItem>> BuildMenuAsync(string name, ActionContext actionContext)
{
var builder = new NavigationBuilder();
// Processes all navigation builders to create a flat list of menu items.
// If a navigation builder fails, it is ignored.
foreach (var navigationProvider in _navigationProviders)
{
try
{
await navigationProvider.BuildNavigationAsync(name, builder);
}
catch (Exception e)
{
_logger.LogError(e, "An exception occurred while building the menu '{MenuName}'", name);
}
}
var menuItems = builder.Build();
// Merge all menu hierarchies into a single one
Merge(menuItems);
// Remove unauthorized menu items
menuItems = await AuthorizeAsync(menuItems, actionContext.HttpContext.User);
// Compute Url and RouteValues properties to Href
menuItems = ComputeHref(menuItems, actionContext);
// Keep only menu items with an Href, or that have child items with an Href
menuItems = Reduce(menuItems);
return menuItems;
}
/// <summary>
/// Mutates a list of <see cref="MenuItem"/> into a hierarchy
/// </summary>
private static void Merge(List<MenuItem> items)
{
// Use two cursors to find all similar captions. If the same caption is represented
// by multiple menu item, try to merge it recursively.
for (var i = 0; i < items.Count; i++)
{
var source = items[i];
var merged = false;
for (var j = items.Count - 1; j > i; j--)
{
var cursor = items[j];
// A match is found, add all its items to the source
if (String.Equals(cursor.Text.Name, source.Text.Name, StringComparison.OrdinalIgnoreCase))
{
merged = true;
foreach (var child in cursor.Items)
{
source.Items.Add(child);
}
items.RemoveAt(j);
// If the item to merge is more authoritative then use its values
if (cursor.Priority > source.Priority)
{
source.Culture = cursor.Culture;
source.Href = cursor.Href;
source.Id = cursor.Id;
source.LinkToFirstChild = cursor.LinkToFirstChild;
source.LocalNav = cursor.LocalNav;
source.Position = cursor.Position;
source.Resource = cursor.Resource;
source.RouteValues = cursor.RouteValues;
source.Text = cursor.Text;
source.Url = cursor.Url;
source.Permissions.Clear();
source.Permissions.AddRange(cursor.Permissions);
source.Classes.Clear();
source.Classes.AddRange(cursor.Classes);
}
//Fallback to get the same behavior than before having the Priority var
if (cursor.Priority == source.Priority)
{
if (cursor.Position != null && source.Position == null)
{
source.Culture = cursor.Culture;
source.Href = cursor.Href;
source.Id = cursor.Id;
source.LinkToFirstChild = cursor.LinkToFirstChild;
source.LocalNav = cursor.LocalNav;
source.Position = cursor.Position;
source.Resource = cursor.Resource;
source.RouteValues = cursor.RouteValues;
source.Text = cursor.Text;
source.Url = cursor.Url;
source.Permissions.Clear();
source.Permissions.AddRange(cursor.Permissions);
source.Classes.Clear();
source.Classes.AddRange(cursor.Classes);
}
}
}
}
// If some items have been merged, apply recursively
if (merged)
{
Merge(source.Items);
}
}
}
/// <summary>
/// Computes the <see cref="MenuItem.Href"/> properties based on <see cref="MenuItem.Url"/>
/// and <see cref="MenuItem.RouteValues"/> values.
/// </summary>
private List<MenuItem> ComputeHref(List<MenuItem> menuItems, ActionContext actionContext)
{
foreach (var menuItem in menuItems)
{
menuItem.Href = GetUrl(menuItem.Url, menuItem.RouteValues, actionContext);
menuItem.Items = ComputeHref(menuItem.Items, actionContext);
}
return menuItems;
}
/// <summary>
/// Gets the url.from a menu item url a routeValueDictionary and an actionContext.
/// </summary>
/// <param name="menuItemUrl">The </param>
/// <param name="routeValueDictionary"></param>
/// <param name="actionContext"></param>
/// <returns></returns>
private string GetUrl(string menuItemUrl, RouteValueDictionary routeValueDictionary, ActionContext actionContext)
{
if (routeValueDictionary?.Count > 0)
{
if (_urlHelper == null)
{
_urlHelper = _urlHelperFactory.GetUrlHelper(actionContext);
}
return _urlHelper.RouteUrl(new UrlRouteContext { Values = routeValueDictionary });
}
if (String.IsNullOrEmpty(menuItemUrl))
{
return "#";
}
if (menuItemUrl[0] == '/' || menuItemUrl.IndexOf("://", StringComparison.Ordinal) >= 0)
{
// Return the unescaped url and let the browser generate all uri components.
return menuItemUrl;
}
if (menuItemUrl.StartsWith("~/", StringComparison.Ordinal))
{
menuItemUrl = menuItemUrl.Substring(2);
}
// Use the unescaped 'Value' to not encode some possible reserved delimiters.
return actionContext.HttpContext.Request.PathBase.Add('/' + menuItemUrl).Value;
}
/// <summary>
/// Updates the items by checking for permissions
/// </summary>
private async Task<List<MenuItem>> AuthorizeAsync(IEnumerable<MenuItem> items, ClaimsPrincipal user)
{
var filtered = new List<MenuItem>();
foreach (var item in items)
{
// TODO: Attach actual user and remove this clause
if (user == null)
{
filtered.Add(item);
}
else if (!item.Permissions.Any())
{
filtered.Add(item);
}
else
{
foreach (var permission in item.Permissions)
{
if (await _authorizationService.AuthorizeAsync(user, permission, item.Resource))
{
filtered.Add(item);
}
}
}
// Process child items
var oldItems = item.Items;
item.Items = (await AuthorizeAsync(item.Items, user)).ToList();
}
return filtered;
}
/// <summary>
/// Retains only menu items with an Href, or that have child items with an Href
/// </summary>
private List<MenuItem> Reduce(IEnumerable<MenuItem> items)
{
var filtered = items.ToList();
foreach (var item in items)
{
if (!HasHrefOrChildHref(item))
{
filtered.Remove(item);
}
item.Items = Reduce(item.Items);
}
return filtered;
}
private static bool HasHrefOrChildHref(MenuItem item)
{
if (item.Href != "#")
{
return true;
}
return item.Items.Any(HasHrefOrChildHref);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Threading;
namespace System.Globalization
{
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
public class GregorianCalendar : Calendar
{
/*
A.D. = anno Domini
*/
public const int ADEra = 1;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
internal const int MaxYear = 9999;
internal GregorianCalendarTypes m_type;
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
private static volatile Calendar s_defaultInstance;
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance()
{
if (s_defaultInstance == null)
{
s_defaultInstance = new GregorianCalendar();
}
return (s_defaultInstance);
}
// Construct an instance of gregorian calendar.
public GregorianCalendar() :
this(GregorianCalendarTypes.Localized)
{
}
public GregorianCalendar(GregorianCalendarTypes type)
{
if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench)
{
throw new ArgumentOutOfRangeException(
nameof(type),
SR.Format(SR.ArgumentOutOfRange_Range,
GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench));
}
this.m_type = type;
}
public virtual GregorianCalendarTypes CalendarType
{
get
{
return (m_type);
}
set
{
VerifyWritable();
switch (value)
{
case GregorianCalendarTypes.Localized:
case GregorianCalendarTypes.USEnglish:
case GregorianCalendarTypes.MiddleEastFrench:
case GregorianCalendarTypes.Arabic:
case GregorianCalendarTypes.TransliteratedEnglish:
case GregorianCalendarTypes.TransliteratedFrench:
m_type = value;
break;
default:
throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum);
}
}
}
internal override CalendarId ID
{
get
{
// By returning different ID for different variations of GregorianCalendar,
// we can support the Transliterated Gregorian calendar.
// DateTimeFormatInfo will use this ID to get formatting information about
// the calendar.
return ((CalendarId)m_type);
}
}
/*=================================GetAbsoluteDate==========================
**Action: Gets the absolute date for the given Gregorian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns: the absolute date
**Arguments:
** year the Gregorian year
** month the Gregorian month
** day the day
**Exceptions:
** ArgumentOutOfRangException if year, month, day value is valid.
**Note:
** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
** Number of Days in Prior Years (both common and leap years) +
** Number of Days in Prior Months of Current Year +
** Number of Days in Current Month
**
============================================================================*/
internal static long GetAbsoluteDate(int year, int month, int day)
{
if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12)
{
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
if (day >= 1 && (day <= days[month] - days[month - 1]))
{
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
internal virtual long DateToTicks(int year, int month, int day)
{
return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
time.GetDatePart(out int y, out int m, out int d);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return time.Day;
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return time.DayOfYear;
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range,
1, MaxYear));
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
return (days[month] - days[month - 1]);
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year >= 1 && year <= MaxYear)
{
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
return (ADEra);
}
public override int[] Eras
{
get
{
return (new int[] { ADEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return time.Month;
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year >= 1 && year <= MaxYear)
{
return (12);
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public override int GetYear(DateTime time)
{
return time.Year;
}
internal override bool IsValidYear(int year, int era) => year >= 1 && year <= MaxYear;
internal override bool IsValidDay(int year, int month, int day, int era)
{
if ((era != CurrentEra && era != ADEra) ||
year < 1 || year > MaxYear ||
month < 1 || month > 12 ||
day < 1)
{
return false;
}
int[] days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
return day <= (days[month] - days[month - 1]);
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
if (day < 1 || day > GetDaysInMonth(year, month))
{
throw new ArgumentOutOfRangeException(nameof(day), SR.Format(SR.ArgumentOutOfRange_Range,
1, GetDaysInMonth(year, month)));
}
if (!IsLeapYear(year))
{
return (false);
}
if (month == 2 && day == 29)
{
return (true);
}
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year >= 1 && year <= MaxYear)
{
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
if (era == CurrentEra || era == ADEra)
{
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
internal override bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
if (era == CurrentEra || era == ADEra)
{
return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result);
}
result = DateTime.MinValue;
return false;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ContentPatcher.Framework.Conditions;
using ContentPatcher.Framework.ConfigModels;
using ContentPatcher.Framework.Constants;
using ContentPatcher.Framework.Patches.EditData;
using ContentPatcher.Framework.Tokens;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StardewModdingAPI;
using xTile;
namespace ContentPatcher.Framework.Patches
{
/// <summary>Metadata for data to edit into a data file.</summary>
internal class EditDataPatch : Patch
{
/*********
** Fields
*********/
/// <summary>Encapsulates monitoring and logging.</summary>
private readonly IMonitor Monitor;
/// <summary>Constructs key/value editors for arbitrary data.</summary>
private readonly KeyValueEditorFactory EditorFactory = new();
/// <summary>The field within the data asset to which edits should be applied, or empty to apply to the root asset.</summary>
private readonly IManagedTokenString[] TargetField;
/// <summary>The data records to edit.</summary>
private EditDataPatchRecord[] Records;
/// <summary>The data fields to edit.</summary>
private EditDataPatchField[] Fields;
/// <summary>The records to reorder, if the target is a list asset.</summary>
private EditDataPatchMoveRecord[] MoveRecords;
/// <summary>The text operations to apply to existing values.</summary>
private readonly TextOperation[] TextOperations;
/// <summary>Parse the data change fields for an <see cref="PatchType.EditData"/> patch.</summary>
private readonly TryParseFieldsDelegate TryParseFields;
/// <summary>Whether the patch already tried loading the <see cref="Patch.FromAsset"/> asset for the current context. This doesn't necessarily means it succeeded (e.g. the file may not have existed).</summary>
private bool AttemptedDataLoad;
/// <summary>The cached JSON serializer used to apply JSON structures to a model.</summary>
private readonly Lazy<JsonSerializer> Serializer = new(() => new()
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
/*********
** Accessors
*********/
/// <summary>Parse the data change fields for an <see cref="PatchType.EditData"/> patch.</summary>
/// <param name="context">The tokens available for this content pack.</param>
/// <param name="entry">The change to load.</param>
/// <param name="entries">The parsed data entry changes.</param>
/// <param name="fields">The parsed data field changes.</param>
/// <param name="moveEntries">The parsed move entry records.</param>
/// <param name="targetFields">The field within the data asset to which edits should be applied, or empty to apply to the root asset.</param>
/// <param name="error">The error message indicating why parsing failed, if applicable.</param>
/// <returns>Returns whether parsing succeeded.</returns>
public delegate bool TryParseFieldsDelegate(IContext context, PatchConfig entry, out List<EditDataPatchRecord> entries, out List<EditDataPatchField> fields, out List<EditDataPatchMoveRecord> moveEntries, out List<IManagedTokenString> targetFields, out string error);
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="indexPath">The path of indexes from the root <c>content.json</c> to this patch; see <see cref="IPatch.IndexPath"/>.</param>
/// <param name="path">The path to the patch from the root content file.</param>
/// <param name="assetName">The normalized asset name to intercept.</param>
/// <param name="conditions">The conditions which determine whether this patch should be applied.</param>
/// <param name="fromFile">The normalized asset key from which to load entries (if applicable), including tokens.</param>
/// <param name="records">The data records to edit.</param>
/// <param name="fields">The data fields to edit.</param>
/// <param name="moveRecords">The records to reorder, if the target is a list asset.</param>
/// <param name="textOperations">The text operations to apply to existing values.</param>
/// <param name="targetField">The field within the data asset to which edits should be applied, or empty to apply to the root asset.</param>
/// <param name="updateRate">When the patch should be updated.</param>
/// <param name="contentPack">The content pack which requested the patch.</param>
/// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="normalizeAssetName">Normalize an asset name.</param>
/// <param name="tryParseFields">Parse the data change fields for an <see cref="PatchType.EditData"/> patch.</param>
public EditDataPatch(int[] indexPath, LogPathBuilder path, IManagedTokenString assetName, IEnumerable<Condition> conditions, IManagedTokenString fromFile, IEnumerable<EditDataPatchRecord> records, IEnumerable<EditDataPatchField> fields, IEnumerable<EditDataPatchMoveRecord> moveRecords, IEnumerable<TextOperation> textOperations, IEnumerable<IManagedTokenString> targetField, UpdateRate updateRate, IContentPack contentPack, IPatch parentPatch, IMonitor monitor, Func<string, string> normalizeAssetName, TryParseFieldsDelegate tryParseFields)
: base(
indexPath: indexPath,
path: path,
type: PatchType.EditData,
assetName: assetName,
conditions: conditions,
updateRate: updateRate,
contentPack: contentPack,
parentPatch: parentPatch,
normalizeAssetName: normalizeAssetName,
fromAsset: fromFile
)
{
// set fields
this.Records = records?.ToArray();
this.Fields = fields?.ToArray();
this.MoveRecords = moveRecords?.ToArray();
this.TextOperations = textOperations?.ToArray() ?? Array.Empty<TextOperation>();
this.TargetField = targetField?.ToArray() ?? Array.Empty<IManagedTokenString>();
this.Monitor = monitor;
this.TryParseFields = tryParseFields;
// track contextuals
this.Contextuals
.Add(this.Records)
.Add(this.Fields)
.Add(this.MoveRecords)
.Add(this.TextOperations)
.Add(this.TargetField)
.Add(this.Conditions);
}
/// <inheritdoc />
public override bool UpdateContext(IContext context)
{
// skip: don't need to handle a data file
if (this.RawFromAsset == null)
return base.UpdateContext(context);
// skip: file already loaded and target didn't change
if (!this.ManagedRawTargetAsset.UpdateContext(context) && this.AttemptedDataLoad)
return base.UpdateContext(context);
// reload non-data changes
this.Contextuals
.Remove(this.Records)
.Remove(this.Fields)
.Remove(this.MoveRecords);
base.UpdateContext(context);
// reload data
this.Records = Array.Empty<EditDataPatchRecord>();
this.Fields = Array.Empty<EditDataPatchField>();
this.MoveRecords = Array.Empty<EditDataPatchMoveRecord>();
if (this.IsReady)
{
if (this.TryLoadFile(this.RawFromAsset, context, out List<EditDataPatchRecord> records, out List<EditDataPatchField> fields, out List<EditDataPatchMoveRecord> moveEntries, out string error))
{
this.Records = records.ToArray();
this.Fields = fields.ToArray();
this.MoveRecords = moveEntries.ToArray();
}
else
this.Monitor.Log($"Can't load \"{this.Path}\" fields from file '{this.RawFromAsset}': {error}.", LogLevel.Warn);
this.AttemptedDataLoad = true;
}
// update context
this.Contextuals
.Add(this.Records)
.Add(this.Fields)
.Add(this.MoveRecords)
.UpdateContext(context);
this.IsReady = this.IsReady && this.Contextuals.IsReady;
return this.MarkUpdated();
}
/// <inheritdoc />
public override void Edit<T>(IAssetData asset)
{
string errorPrefix = $"Can't apply data patch \"{this.Path}\" to {this.TargetAsset}";
// get editor
IKeyValueEditor editor = this.EditorFactory.GetEditorFor(asset.Data);
if (editor is null)
{
this.Monitor.Log($"{errorPrefix}: {this.GetEditorNotCompatibleError("the target asset", asset.Data, entryExists: true)}", LogLevel.Warn);
return;
}
// apply target field
if (this.TargetField.Any())
{
var path = new List<string>(this.TargetField.Length);
foreach (IManagedTokenString fieldName in this.TargetField)
{
path.Add(fieldName.Value);
IKeyValueEditor parentEditor = editor;
object key = parentEditor.ParseKey(fieldName.Value);
object data = parentEditor.GetEntry(key);
editor = this.EditorFactory.GetEditorFor(data);
if (editor is null)
{
this.Monitor.Log($"{errorPrefix}: {this.GetEditorNotCompatibleError($"the field '{string.Join("' > '", path)}'", data, entryExists: parentEditor.HasEntry(key))}", LogLevel.Warn);
return;
}
}
}
// apply edits
char fieldDelimiter = this.GetStringFieldDelimiter(asset);
this.ApplyEdits(editor, fieldDelimiter);
}
/// <inheritdoc />
public override IEnumerable<string> GetChangeLabels()
{
if (this.Records?.Any(p => p.Value?.Value == null) == true)
yield return "deleted entries";
if (this.Fields?.Any() == true || this.Records?.Any(p => p.Value?.Value != null) == true)
yield return "changed entries";
if (this.MoveRecords?.Any() == true)
yield return "reordered entries";
if (this.TextOperations.Any())
yield return "applied text operations";
}
/*********
** Private methods
*********/
/// <summary>Parse the data change fields for an <see cref="PatchType.EditData"/> patch.</summary>
/// <param name="fromFile">The normalized asset key from which to load entries (if applicable), including tokens.</param>
/// <param name="context">The tokens available for this content pack.</param>
/// <param name="entries">The parsed data entry changes.</param>
/// <param name="fields">The parsed data field changes.</param>
/// <param name="moveEntries">The parsed move entry records.</param>
/// <param name="error">The error message indicating why parsing failed, if applicable.</param>
/// <returns>Returns whether parsing succeeded.</returns>
private bool TryLoadFile(ITokenString fromFile, IContext context, out List<EditDataPatchRecord> entries, out List<EditDataPatchField> fields, out List<EditDataPatchMoveRecord> moveEntries, out string error)
{
if (fromFile.IsMutable && !fromFile.IsReady)
{
error = $"the {nameof(fromFile)} contains tokens which aren't available yet"; // this shouldn't happen, since the patch should check before calling this method
entries = null;
fields = null;
moveEntries = null;
return false;
}
// validate path
if (!this.ContentPack.HasFile(fromFile.Value))
{
error = "that file doesn't exist in the content pack";
entries = null;
fields = null;
moveEntries = null;
return false;
}
// load JSON file
PatchConfig model;
try
{
model = this.ContentPack.ReadJsonFile<PatchConfig>(fromFile.Value);
}
catch (JsonException ex)
{
error = $"could not parse that file: {ex}";
entries = null;
fields = null;
moveEntries = null;
return false;
}
// parse fields
// note: this is only used for the legacy FromFile field, so it shouldn't allow
// features added in Content Patcher 1.18.0+ (like TargetField).
return this.TryParseFields(context, model, out entries, out fields, out moveEntries, out _, out error);
}
/// <summary>Apply the patch to a data asset.</summary>
/// <param name="editor">The asset editor to apply.</param>
/// <param name="fieldDelimiter">The field delimiter for the data asset's string values, if applicable.</param>
private void ApplyEdits(IKeyValueEditor editor, char fieldDelimiter)
{
this.ApplyRecords(editor);
this.ApplyFields(editor, fieldDelimiter);
this.ApplyTextOperations(editor, fieldDelimiter);
this.ApplyMoveEntries(editor);
}
/// <summary>Apply entry overwrites to the data asset.</summary>
/// <param name="editor">The asset editor to apply.</param>
private void ApplyRecords(IKeyValueEditor editor)
{
if (this.Records == null)
return;
int i = 0;
foreach (EditDataPatchRecord record in this.Records)
{
string errorPrefix = $"Can't apply data patch \"{this.Path} > entry #{i}\" to {this.TargetAsset}";
i++;
// get entry info
object key = editor.ParseKey(record.Key.Value);
Type valueType = editor.GetEntryType(key);
// validate
if (!editor.CanAddEntries && !editor.HasEntry(key))
this.Monitor.Log($"{errorPrefix}: this asset is a data model, which doesn't allow adding new entries. The entry '{record.Key.Value}' isn't defined in the model.", LogLevel.Warn);
// apply string
else if (valueType == typeof(string))
{
if (record.Value?.Value == null)
editor.RemoveEntry(key);
else if (record.Value.Value is JValue field)
editor.SetEntry(key, field);
else
this.Monitor.Log($"{errorPrefix}: this asset has string values (but {record.Value.Value.Type} values were provided).", LogLevel.Warn);
}
// apply object
else
{
if (record.Value?.Value == null)
editor.RemoveEntry(key);
else if (record.Value.Value is JObject field)
editor.SetEntry(key, field);
else
this.Monitor.Log($"{errorPrefix}: this asset has {valueType} values (but {record.Value.Value.Type} values were provided).", LogLevel.Warn);
}
}
}
/// <summary>Apply field overwrites to the data asset.</summary>
/// <param name="editor">The asset editor to apply.</param>
/// <param name="fieldDelimiter">The field delimiter for the data asset's string values, if applicable.</param>
private void ApplyFields(IKeyValueEditor editor, char fieldDelimiter)
{
if (this.Fields == null)
return;
foreach (IGrouping<string, EditDataPatchField> recordGroup in this.Fields.GroupByIgnoreCase(p => p.EntryKey.Value))
{
string errorPrefix = $"Can't apply data patch \"{this.Path}\" to {this.TargetAsset}";
// get entry info
object key = editor.ParseKey(recordGroup.Key);
Type valueType = editor.GetEntryType(key);
// skip if doesn't exist
if (!editor.HasEntry(key))
{
this.Monitor.Log($"{errorPrefix}: there's no record matching key '{key}' under {nameof(PatchConfig.Fields)}.", LogLevel.Warn);
continue;
}
// apply string
if (valueType == typeof(string))
{
string[] actualFields = ((string)editor.GetEntry(key)).Split(fieldDelimiter);
foreach (EditDataPatchField field in recordGroup)
{
if (!int.TryParse(field.FieldKey.Value, out int index))
{
this.Monitor.Log($"{errorPrefix}: record '{key}' under {nameof(PatchConfig.Fields)} is a string, so it requires a field index between 0 and {actualFields.Length - 1} (received \"{field.FieldKey}\" instead)).", LogLevel.Warn);
continue;
}
if (index < 0 || index > actualFields.Length - 1)
{
this.Monitor.Log($"{errorPrefix}: record '{key}' under {nameof(PatchConfig.Fields)} has no field with index {index} (must be 0 to {actualFields.Length - 1}).", LogLevel.Warn);
continue;
}
actualFields[index] = field.Value.Value.Value<string>();
}
editor.SetEntry(key, string.Join(fieldDelimiter.ToString(), actualFields));
}
// apply object
else
{
JObject obj = new();
foreach (EditDataPatchField field in recordGroup)
obj[field.FieldKey.Value] = field.Value.Value;
using JsonReader reader = obj.CreateReader();
this.Serializer.Value.Populate(reader, editor.GetEntry(key));
}
}
}
/// <summary>Apply text operations to the data asset.</summary>
/// <param name="editor">The asset editor to apply.</param>
/// <param name="fieldDelimiter">The field delimiter for the data asset's string values, if applicable.</param>
private void ApplyTextOperations(IKeyValueEditor editor, char fieldDelimiter)
{
for (int i = 0; i < this.TextOperations.Length; i++)
{
if (!this.TryApplyTextOperation(this.TextOperations[i], editor, fieldDelimiter, out string error))
this.Monitor.Log($"Can't apply data patch \"{this.Path} > text operation #{i}\" to {this.TargetAsset}: {error}", LogLevel.Warn);
}
}
/// <summary>Apply entry moves to the data asset.</summary>
/// <param name="editor">The asset editor to apply.</param>
private void ApplyMoveEntries(IKeyValueEditor editor)
{
if (!this.MoveRecords.Any())
return;
if (!editor.CanMoveEntries)
{
this.Monitor.LogOnce($"Can't move records for \"{this.Path}\" > {nameof(PatchConfig.MoveEntries)}: target asset '{this.TargetAsset}' isn't an ordered list.", LogLevel.Warn);
return;
}
foreach (EditDataPatchMoveRecord moveRecord in this.MoveRecords)
{
if (!moveRecord.IsReady)
continue;
object key = editor.ParseKey(moveRecord.ID.Value);
string errorLabel = $"record \"{this.Path}\" > {nameof(PatchConfig.MoveEntries)} > \"{moveRecord.ID}\"";
// move record
MoveResult result = MoveResult.Success;
if (moveRecord.ToPosition is MoveEntryPosition.Top or MoveEntryPosition.Bottom)
result = editor.MoveEntry(key, moveRecord.ToPosition);
else if (moveRecord.AfterID.IsMeaningful() || moveRecord.BeforeID.IsMeaningful())
{
// get config
bool isAfter = moveRecord.AfterID.IsMeaningful();
string rawAnchorKey = isAfter ? moveRecord.AfterID.Value : moveRecord.BeforeID.Value;
object anchorKey = editor.ParseKey(rawAnchorKey);
// move entry
errorLabel += $" {(isAfter ? nameof(PatchMoveEntryConfig.AfterID) : nameof(PatchMoveEntryConfig.BeforeID))} \"{rawAnchorKey}\"";
result = editor.MoveEntry(key, anchorKey, isAfter);
}
// log error
if (result != MoveResult.Success)
{
switch (result)
{
case MoveResult.TargetNotFound:
this.Monitor.LogOnce($"Can't move {errorLabel}: no entry with that ID exists.");
break;
case MoveResult.AnchorNotFound:
this.Monitor.LogOnce($"Can't move {errorLabel}: no entry with the relative ID exists.");
break;
case MoveResult.AnchorIsMain:
this.Monitor.LogOnce($"Can't move {errorLabel}: can't move entry relative to itself.");
break;
default:
this.Monitor.LogOnce($"Can't move {errorLabel}: an unknown error occurred.");
break;
}
}
}
}
/// <summary>Try to apply a text operation.</summary>
/// <param name="operation">The text operation to apply.</param>
/// <param name="editor">The asset editor to apply.</param>
/// <param name="fieldDelimiter">The field delimiter for the data asset's string values, if applicable.</param>
/// <param name="error">An error indicating why applying the operation failed, if applicable.</param>
/// <returns>Returns whether applying the operation succeeded.</returns>
private bool TryApplyTextOperation(TextOperation operation, IKeyValueEditor editor, char fieldDelimiter, out string error)
{
var targetRoot = operation.GetTargetRoot();
switch (targetRoot)
{
case TextOperationTargetRoot.Entries:
{
// validate format
if (operation.Target.Length != 2)
return this.Fail($"an '{TextOperationTargetRoot.Entries}' path must have exactly one other segment: the entry key.", out error);
// get entry
object key = editor.ParseKey(operation.Target[1].Value);
Type entryType = editor.GetEntryType(key);
if (entryType != typeof(string))
return this.Fail($"can't apply text operation to the '{operation.Target[1].Value}' entry because it's not a string value.", out error);
string value = (string)editor.GetEntry(key);
// set value
editor.SetEntry(key, operation.Apply(value));
}
break;
case TextOperationTargetRoot.Fields:
{
// validate format
if (operation.Target.Length != 3)
return this.Fail($"a '{TextOperationTargetRoot.Fields}' path must have exactly two other segments: one for the entry key, and one for the field key or index.", out error);
// get entry editor
string rawEntryKey = operation.Target[1].Value;
string rawFieldKey = operation.Target[2].Value;
IKeyValueEditor entryEditor;
{
object key = editor.ParseKey(rawEntryKey);
Type entryType = editor.GetEntryType(key);
object entry = editor.GetEntry(key);
if (entry is null)
return this.Fail($"record '{rawEntryKey}' has no value, so field '{rawFieldKey}' can't be modified using text operations.", out error);
// get entry editor
entryEditor = this.EditorFactory.GetEditorFor(entry);
if (entryEditor is null)
{
if (entryType == typeof(string))
entryEditor = new DelimitedStringKeyValueEditor(editor, key, fieldDelimiter);
else
return this.Fail($"record '{rawEntryKey}' > field '{rawFieldKey}' can't be modified using text operations because its type ({entryType.FullName}) isn't supported.", out error);
}
}
// get field
object fieldKey = entryEditor.ParseKey(rawFieldKey);
Type fieldType = entryEditor.GetEntryType(fieldKey);
object fieldValue = entryEditor.GetEntry(fieldKey);
// validate type
if (fieldType != typeof(string))
return this.Fail($"field '{rawEntryKey}' > '{rawFieldKey}' has type '{fieldType}', but you can only apply text operations to a text field.", out error);
// edit value
if (fieldValue is null)
entryEditor.SetEntry(fieldKey, operation.Apply(""));
else
entryEditor.SetEntry(fieldKey, operation.Apply((string)fieldValue));
}
break;
default:
return this.Fail(
targetRoot == null
? $"unknown path root '{operation.Target[0]}'."
: $"path root '{targetRoot}' isn't valid for an {nameof(PatchType.EditMap)} patch",
out error
);
}
error = null;
return true;
}
/// <summary>Get the delimiter used in string entries for an asset.</summary>
/// <param name="asset">The asset being edited.</param>
private char GetStringFieldDelimiter(IAssetInfo asset)
{
return asset.AssetNameEquals("Data/Achievements")
? '^'
: '/';
}
/// <summary>If an editor can't be constructed for a given data structure, get a human-readable error indicating why.</summary>
/// <param name="nounPhrase">A noun phase </param>
/// <param name="data">The data for which an editor couldn't be constructed.</param>
/// <param name="entryExists">Whether the entry exists in the asset.</param>
private string GetEditorNotCompatibleError(string nounPhrase, object data, bool entryExists)
{
if (!entryExists || data is null)
return $"{nounPhrase} is null and can't be targeted for edits";
Type type = data.GetType();
if (typeof(Texture2D).IsAssignableFrom(type))
return $"{nounPhrase} is an image, not data";
if (typeof(Map).IsAssignableFrom(type))
return $"{nounPhrase} is a map, not data";
return $"{nounPhrase} has type '{type.FullName}', which isn't recognized by Content Patcher";
}
}
}
| |
// 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.Diagnostics;
namespace System.Xml
{
internal class Base64Decoder : IncrementalReadDecoder
{
//
// Fields
//
private byte[] _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
private int _bits;
private int _bitsFilled;
private const string CharsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static readonly byte[] s_mapBase64 = ConstructMapBase64();
private const int MaxValidChar = (int)'z';
private const byte Invalid = unchecked((byte)-1);
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount
{
get
{
return _curIndex - _startIndex;
}
}
internal override bool IsFull
{
get
{
return _curIndex == _endIndex;
}
}
internal override unsafe int Decode(char[] chars, int startPos, int len)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException(nameof(startPos));
}
if (chars.Length - startPos < len)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = &chars[startPos])
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override unsafe int Decode(string str, int startPos, int len)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException(nameof(startPos));
}
if (str.Length - startPos < len)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = str)
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset()
{
_bitsFilled = 0;
_bits = 0;
}
internal override void SetNextOutputBuffer(Array buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(buffer.Length - index >= count);
Debug.Assert((buffer as byte[]) != null);
_buffer = (byte[])buffer;
_startIndex = index;
_curIndex = index;
_endIndex = index + count;
}
//
// Private methods
//
private static byte[] ConstructMapBase64()
{
byte[] mapBase64 = new byte[MaxValidChar + 1];
for (int i = 0; i < mapBase64.Length; i++)
{
mapBase64[i] = Invalid;
}
for (int i = 0; i < CharsBase64.Length; i++)
{
mapBase64[(int)CharsBase64[i]] = (byte)i;
}
return mapBase64;
}
private unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
out int charsDecoded, out int bytesDecoded)
{
#if DEBUG
Debug.Assert(pCharsEndPos - pChars >= 0);
Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif
// walk hex digits pairing them up and shoving the value of each pair into a byte
byte* pByte = pBytes;
char* pChar = pChars;
int b = _bits;
int bFilled = _bitsFilled;
XmlCharType xmlCharType = XmlCharType.Instance;
while (pChar < pCharsEndPos && pByte < pBytesEndPos)
{
char ch = *pChar;
// end?
if (ch == '=')
{
break;
}
pChar++;
// ignore whitespace
if (xmlCharType.IsWhiteSpace(ch))
{
continue;
}
int digit;
if (ch > 122 || (digit = s_mapBase64[ch]) == Invalid)
{
throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
}
b = (b << 6) | digit;
bFilled += 6;
if (bFilled >= 8)
{
// get top eight valid bits
*pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF);
bFilled -= 8;
if (pByte == pBytesEndPos)
{
goto Return;
}
}
}
if (pChar < pCharsEndPos && *pChar == '=')
{
bFilled = 0;
// ignore padding chars
do
{
pChar++;
} while (pChar < pCharsEndPos && *pChar == '=');
// ignore whitespace after the padding chars
if (pChar < pCharsEndPos)
{
do
{
if (!(xmlCharType.IsWhiteSpace(*pChar++)))
{
throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
}
} while (pChar < pCharsEndPos);
}
}
Return:
_bits = b;
_bitsFilled = bFilled;
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: math/math.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Math {
/// <summary>Holder for reflection information generated from math/math.proto</summary>
public static partial class MathReflection {
#region Descriptor
/// <summary>File descriptor for math/math.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MathReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg9tYXRoL21hdGgucHJvdG8SBG1hdGgiLAoHRGl2QXJncxIQCghkaXZpZGVu",
"ZBgBIAEoAxIPCgdkaXZpc29yGAIgASgDIi8KCERpdlJlcGx5EhAKCHF1b3Rp",
"ZW50GAEgASgDEhEKCXJlbWFpbmRlchgCIAEoAyIYCgdGaWJBcmdzEg0KBWxp",
"bWl0GAEgASgDIhIKA051bRILCgNudW0YASABKAMiGQoIRmliUmVwbHkSDQoF",
"Y291bnQYASABKAMypAEKBE1hdGgSJgoDRGl2Eg0ubWF0aC5EaXZBcmdzGg4u",
"bWF0aC5EaXZSZXBseSIAEi4KB0Rpdk1hbnkSDS5tYXRoLkRpdkFyZ3MaDi5t",
"YXRoLkRpdlJlcGx5IgAoATABEiMKA0ZpYhINLm1hdGguRmliQXJncxoJLm1h",
"dGguTnVtIgAwARIfCgNTdW0SCS5tYXRoLk51bRoJLm1hdGguTnVtIgAoAWIG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Math.DivArgs), global::Math.DivArgs.Parser, new[]{ "Dividend", "Divisor" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Math.DivReply), global::Math.DivReply.Parser, new[]{ "Quotient", "Remainder" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Math.FibArgs), global::Math.FibArgs.Parser, new[]{ "Limit" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Math.Num), global::Math.Num.Parser, new[]{ "Num_" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Math.FibReply), global::Math.FibReply.Parser, new[]{ "Count" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class DivArgs : pb::IMessage<DivArgs> {
private static readonly pb::MessageParser<DivArgs> _parser = new pb::MessageParser<DivArgs>(() => new DivArgs());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DivArgs> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.MathReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DivArgs() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DivArgs(DivArgs other) : this() {
dividend_ = other.dividend_;
divisor_ = other.divisor_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DivArgs Clone() {
return new DivArgs(this);
}
/// <summary>Field number for the "dividend" field.</summary>
public const int DividendFieldNumber = 1;
private long dividend_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Dividend {
get { return dividend_; }
set {
dividend_ = value;
}
}
/// <summary>Field number for the "divisor" field.</summary>
public const int DivisorFieldNumber = 2;
private long divisor_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Divisor {
get { return divisor_; }
set {
divisor_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DivArgs);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DivArgs other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Dividend != other.Dividend) return false;
if (Divisor != other.Divisor) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Dividend != 0L) hash ^= Dividend.GetHashCode();
if (Divisor != 0L) hash ^= Divisor.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Dividend != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Dividend);
}
if (Divisor != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Divisor);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Dividend != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Dividend);
}
if (Divisor != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Divisor);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DivArgs other) {
if (other == null) {
return;
}
if (other.Dividend != 0L) {
Dividend = other.Dividend;
}
if (other.Divisor != 0L) {
Divisor = other.Divisor;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Dividend = input.ReadInt64();
break;
}
case 16: {
Divisor = input.ReadInt64();
break;
}
}
}
}
}
public sealed partial class DivReply : pb::IMessage<DivReply> {
private static readonly pb::MessageParser<DivReply> _parser = new pb::MessageParser<DivReply>(() => new DivReply());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DivReply> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.MathReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DivReply() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DivReply(DivReply other) : this() {
quotient_ = other.quotient_;
remainder_ = other.remainder_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DivReply Clone() {
return new DivReply(this);
}
/// <summary>Field number for the "quotient" field.</summary>
public const int QuotientFieldNumber = 1;
private long quotient_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Quotient {
get { return quotient_; }
set {
quotient_ = value;
}
}
/// <summary>Field number for the "remainder" field.</summary>
public const int RemainderFieldNumber = 2;
private long remainder_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Remainder {
get { return remainder_; }
set {
remainder_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DivReply);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DivReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Quotient != other.Quotient) return false;
if (Remainder != other.Remainder) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Quotient != 0L) hash ^= Quotient.GetHashCode();
if (Remainder != 0L) hash ^= Remainder.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Quotient != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Quotient);
}
if (Remainder != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Remainder);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Quotient != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Quotient);
}
if (Remainder != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Remainder);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DivReply other) {
if (other == null) {
return;
}
if (other.Quotient != 0L) {
Quotient = other.Quotient;
}
if (other.Remainder != 0L) {
Remainder = other.Remainder;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Quotient = input.ReadInt64();
break;
}
case 16: {
Remainder = input.ReadInt64();
break;
}
}
}
}
}
public sealed partial class FibArgs : pb::IMessage<FibArgs> {
private static readonly pb::MessageParser<FibArgs> _parser = new pb::MessageParser<FibArgs>(() => new FibArgs());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FibArgs> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.MathReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FibArgs() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FibArgs(FibArgs other) : this() {
limit_ = other.limit_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FibArgs Clone() {
return new FibArgs(this);
}
/// <summary>Field number for the "limit" field.</summary>
public const int LimitFieldNumber = 1;
private long limit_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Limit {
get { return limit_; }
set {
limit_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FibArgs);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FibArgs other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Limit != other.Limit) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Limit != 0L) hash ^= Limit.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Limit != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Limit);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Limit != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Limit);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FibArgs other) {
if (other == null) {
return;
}
if (other.Limit != 0L) {
Limit = other.Limit;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Limit = input.ReadInt64();
break;
}
}
}
}
}
public sealed partial class Num : pb::IMessage<Num> {
private static readonly pb::MessageParser<Num> _parser = new pb::MessageParser<Num>(() => new Num());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Num> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.MathReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Num() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Num(Num other) : this() {
num_ = other.num_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Num Clone() {
return new Num(this);
}
/// <summary>Field number for the "num" field.</summary>
public const int Num_FieldNumber = 1;
private long num_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Num_ {
get { return num_; }
set {
num_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Num);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Num other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Num_ != other.Num_) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Num_ != 0L) hash ^= Num_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Num_ != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Num_);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Num_ != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Num_);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Num other) {
if (other == null) {
return;
}
if (other.Num_ != 0L) {
Num_ = other.Num_;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Num_ = input.ReadInt64();
break;
}
}
}
}
}
public sealed partial class FibReply : pb::IMessage<FibReply> {
private static readonly pb::MessageParser<FibReply> _parser = new pb::MessageParser<FibReply>(() => new FibReply());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FibReply> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.MathReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FibReply() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FibReply(FibReply other) : this() {
count_ = other.count_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FibReply Clone() {
return new FibReply(this);
}
/// <summary>Field number for the "count" field.</summary>
public const int CountFieldNumber = 1;
private long count_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Count {
get { return count_; }
set {
count_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FibReply);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FibReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Count != other.Count) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Count != 0L) hash ^= Count.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Count != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Count);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Count != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FibReply other) {
if (other == null) {
return;
}
if (other.Count != 0L) {
Count = other.Count;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Count = input.ReadInt64();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for PoolOperations.
/// </summary>
public static partial class PoolOperationsExtensions
{
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListPoolUsageMetricsOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<PoolUsageMetrics> ListPoolUsageMetrics(this IPoolOperations operations, PoolListPoolUsageMetricsOptions poolListPoolUsageMetricsOptions = default(PoolListPoolUsageMetricsOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).ListPoolUsageMetricsAsync(poolListPoolUsageMetricsOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListPoolUsageMetricsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<PoolUsageMetrics>> ListPoolUsageMetricsAsync(this IPoolOperations operations, PoolListPoolUsageMetricsOptions poolListPoolUsageMetricsOptions = default(PoolListPoolUsageMetricsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListPoolUsageMetricsWithHttpMessagesAsync(poolListPoolUsageMetricsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets lifetime summary statistics for all of the pools in the specified
/// account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all pools that have ever existed in the
/// account, from account creation to the last update time of the statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolGetAllPoolsLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolStatistics GetAllPoolsLifetimeStatistics(this IPoolOperations operations, PoolGetAllPoolsLifetimeStatisticsOptions poolGetAllPoolsLifetimeStatisticsOptions = default(PoolGetAllPoolsLifetimeStatisticsOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).GetAllPoolsLifetimeStatisticsAsync(poolGetAllPoolsLifetimeStatisticsOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets lifetime summary statistics for all of the pools in the specified
/// account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all pools that have ever existed in the
/// account, from account creation to the last update time of the statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolGetAllPoolsLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolStatistics> GetAllPoolsLifetimeStatisticsAsync(this IPoolOperations operations, PoolGetAllPoolsLifetimeStatisticsOptions poolGetAllPoolsLifetimeStatisticsOptions = default(PoolGetAllPoolsLifetimeStatisticsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetAllPoolsLifetimeStatisticsWithHttpMessagesAsync(poolGetAllPoolsLifetimeStatisticsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Adds a pool to the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pool'>
/// The pool to be added.
/// </param>
/// <param name='poolAddOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolAddHeaders Add(this IPoolOperations operations, PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).AddAsync(pool, poolAddOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Adds a pool to the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pool'>
/// The pool to be added.
/// </param>
/// <param name='poolAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolAddHeaders> AddAsync(this IPoolOperations operations, PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddWithHttpMessagesAsync(pool, poolAddOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudPool> List(this IPoolOperations operations, PoolListOptions poolListOptions = default(PoolListOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).ListAsync(poolListOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CloudPool>> ListAsync(this IPoolOperations operations, PoolListOptions poolListOptions = default(PoolListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(poolListOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a pool from the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to delete.
/// </param>
/// <param name='poolDeleteOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolDeleteHeaders Delete(this IPoolOperations operations, string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).DeleteAsync(poolId, poolDeleteOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pool from the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to delete.
/// </param>
/// <param name='poolDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolDeleteHeaders> DeleteAsync(this IPoolOperations operations, string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(poolId, poolDeleteOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets basic properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to get.
/// </param>
/// <param name='poolExistsOptions'>
/// Additional parameters for the operation
/// </param>
public static bool Exists(this IPoolOperations operations, string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).ExistsAsync(poolId, poolExistsOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets basic properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to get.
/// </param>
/// <param name='poolExistsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<bool> ExistsAsync(this IPoolOperations operations, string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ExistsWithHttpMessagesAsync(poolId, poolExistsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to get.
/// </param>
/// <param name='poolGetOptions'>
/// Additional parameters for the operation
/// </param>
public static CloudPool Get(this IPoolOperations operations, string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).GetAsync(poolId, poolGetOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to get.
/// </param>
/// <param name='poolGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CloudPool> GetAsync(this IPoolOperations operations, string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(poolId, poolGetOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to update.
/// </param>
/// <param name='poolPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolPatchOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolPatchHeaders Patch(this IPoolOperations operations, string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).PatchAsync(poolId, poolPatchParameter, poolPatchOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to update.
/// </param>
/// <param name='poolPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolPatchHeaders> PatchAsync(this IPoolOperations operations, string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(poolId, poolPatchParameter, poolPatchOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Disables automatic scaling for a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool on which to disable automatic scaling.
/// </param>
/// <param name='poolDisableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolDisableAutoScaleHeaders DisableAutoScale(this IPoolOperations operations, string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).DisableAutoScaleAsync(poolId, poolDisableAutoScaleOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Disables automatic scaling for a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool on which to disable automatic scaling.
/// </param>
/// <param name='poolDisableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolDisableAutoScaleHeaders> DisableAutoScaleAsync(this IPoolOperations operations, string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DisableAutoScaleWithHttpMessagesAsync(poolId, poolDisableAutoScaleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Enables automatic scaling for a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool on which to enable automatic scaling.
/// </param>
/// <param name='poolEnableAutoScaleParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolEnableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolEnableAutoScaleHeaders EnableAutoScale(this IPoolOperations operations, string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).EnableAutoScaleAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Enables automatic scaling for a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool on which to enable automatic scaling.
/// </param>
/// <param name='poolEnableAutoScaleParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolEnableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolEnableAutoScaleHeaders> EnableAutoScaleAsync(this IPoolOperations operations, string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.EnableAutoScaleWithHttpMessagesAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets the result of evaluating an automatic scaling formula on the pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool on which to evaluate the automatic scaling formula.
/// </param>
/// <param name='autoScaleFormula'>
/// A formula for the desired number of compute nodes in the pool.
/// </param>
/// <param name='poolEvaluateAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
public static AutoScaleRun EvaluateAutoScale(this IPoolOperations operations, string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).EvaluateAutoScaleAsync(poolId, autoScaleFormula, poolEvaluateAutoScaleOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the result of evaluating an automatic scaling formula on the pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool on which to evaluate the automatic scaling formula.
/// </param>
/// <param name='autoScaleFormula'>
/// A formula for the desired number of compute nodes in the pool.
/// </param>
/// <param name='poolEvaluateAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<AutoScaleRun> EvaluateAutoScaleAsync(this IPoolOperations operations, string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.EvaluateAutoScaleWithHttpMessagesAsync(poolId, autoScaleFormula, poolEvaluateAutoScaleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Changes the number of compute nodes that are assigned to a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to resize.
/// </param>
/// <param name='poolResizeParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolResizeOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolResizeHeaders Resize(this IPoolOperations operations, string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).ResizeAsync(poolId, poolResizeParameter, poolResizeOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Changes the number of compute nodes that are assigned to a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to resize.
/// </param>
/// <param name='poolResizeParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolResizeHeaders> ResizeAsync(this IPoolOperations operations, string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ResizeWithHttpMessagesAsync(poolId, poolResizeParameter, poolResizeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Stops an ongoing resize operation on the pool.
/// </summary>
/// <remarks>
/// This does not restore the pool to its previous state before the resize
/// operation: it only stops any further changes being made, and the pool
/// maintains its current state.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool whose resizing you want to stop.
/// </param>
/// <param name='poolStopResizeOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolStopResizeHeaders StopResize(this IPoolOperations operations, string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).StopResizeAsync(poolId, poolStopResizeOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Stops an ongoing resize operation on the pool.
/// </summary>
/// <remarks>
/// This does not restore the pool to its previous state before the resize
/// operation: it only stops any further changes being made, and the pool
/// maintains its current state.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool whose resizing you want to stop.
/// </param>
/// <param name='poolStopResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolStopResizeHeaders> StopResizeAsync(this IPoolOperations operations, string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.StopResizeWithHttpMessagesAsync(poolId, poolStopResizeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Updates the properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to update.
/// </param>
/// <param name='poolUpdatePropertiesParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolUpdatePropertiesOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolUpdatePropertiesHeaders UpdateProperties(this IPoolOperations operations, string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).UpdatePropertiesAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to update.
/// </param>
/// <param name='poolUpdatePropertiesParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolUpdatePropertiesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolUpdatePropertiesHeaders> UpdatePropertiesAsync(this IPoolOperations operations, string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpdatePropertiesWithHttpMessagesAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Upgrades the operating system of the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to upgrade.
/// </param>
/// <param name='targetOSVersion'>
/// The Azure Guest OS version to be installed on the virtual machines in the
/// pool.
/// </param>
/// <param name='poolUpgradeOSOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolUpgradeOSHeaders UpgradeOS(this IPoolOperations operations, string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).UpgradeOSAsync(poolId, targetOSVersion, poolUpgradeOSOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Upgrades the operating system of the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool to upgrade.
/// </param>
/// <param name='targetOSVersion'>
/// The Azure Guest OS version to be installed on the virtual machines in the
/// pool.
/// </param>
/// <param name='poolUpgradeOSOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolUpgradeOSHeaders> UpgradeOSAsync(this IPoolOperations operations, string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpgradeOSWithHttpMessagesAsync(poolId, targetOSVersion, poolUpgradeOSOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Removes compute nodes from the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool from which you want to remove nodes.
/// </param>
/// <param name='nodeRemoveParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolRemoveNodesOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolRemoveNodesHeaders RemoveNodes(this IPoolOperations operations, string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).RemoveNodesAsync(poolId, nodeRemoveParameter, poolRemoveNodesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Removes compute nodes from the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool from which you want to remove nodes.
/// </param>
/// <param name='nodeRemoveParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolRemoveNodesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolRemoveNodesHeaders> RemoveNodesAsync(this IPoolOperations operations, string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.RemoveNodesWithHttpMessagesAsync(poolId, nodeRemoveParameter, poolRemoveNodesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListPoolUsageMetricsNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<PoolUsageMetrics> ListPoolUsageMetricsNext(this IPoolOperations operations, string nextPageLink, PoolListPoolUsageMetricsNextOptions poolListPoolUsageMetricsNextOptions = default(PoolListPoolUsageMetricsNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).ListPoolUsageMetricsNextAsync(nextPageLink, poolListPoolUsageMetricsNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListPoolUsageMetricsNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<PoolUsageMetrics>> ListPoolUsageMetricsNextAsync(this IPoolOperations operations, string nextPageLink, PoolListPoolUsageMetricsNextOptions poolListPoolUsageMetricsNextOptions = default(PoolListPoolUsageMetricsNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListPoolUsageMetricsNextWithHttpMessagesAsync(nextPageLink, poolListPoolUsageMetricsNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudPool> ListNext(this IPoolOperations operations, string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPoolOperations)s).ListNextAsync(nextPageLink, poolListNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CloudPool>> ListNextAsync(this IPoolOperations operations, string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, poolListNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using NUnit.Framework;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Core.UnitTests
{
[TestFixture]
public class ViewUnitTests : BaseTestFixture
{
[SetUp]
public override void Setup ()
{
base.Setup ();
Device.PlatformServices = new MockPlatformServices ();
}
[TearDown]
public override void TearDown ()
{
base.TearDown ();
Device.PlatformServices = null;
}
[Test]
public void TestLayout ()
{
View view = new View ();
view.Layout (new Rectangle (50, 25, 100, 200));
Assert.AreEqual (view.X, 50);
Assert.AreEqual (view.Y, 25);
Assert.AreEqual (view.Width, 100);
Assert.AreEqual (view.Height, 200);
}
[Test]
public void TestPreferredSize ()
{
View view = new View {
IsPlatformEnabled = true,
Platform = new UnitPlatform ()
};
bool fired = false;
view.MeasureInvalidated += (sender, e) => fired = true;
view.WidthRequest = 200;
view.HeightRequest = 300;
Assert.True (fired);
var result = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity).Request;
Assert.AreEqual (new Size (200, 300), result);
}
[Test]
public void TestSizeChangedEvent ()
{
View view = new View ();
bool fired = false;
view.SizeChanged += (sender, e) => fired = true;
view.Layout (new Rectangle (0, 0, 100, 100));
Assert.True (fired);
}
[Test]
public void TestOpacityClamping ()
{
var view = new View ();
view.Opacity = -1;
Assert.AreEqual (0, view.Opacity);
view.Opacity = 2;
Assert.AreEqual (1, view.Opacity);
}
[Test]
public void TestMeasureInvalidatedFiredOnVisibilityChanged ()
{
var view = new View {IsVisible = false};
bool signaled = false;
view.MeasureInvalidated += (sender, e) => {
signaled = true;
};
view.IsVisible = true;
Assert.True (signaled);
}
[Test]
public void TestOnPlatformiOS ()
{
var view = new View ();
bool ios = false;
bool android = false;
bool winphone = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.iOS;
Device.OnPlatform (
iOS: () => ios = true,
Android: () => android = true,
WinPhone: () => winphone = true);
Assert.True (ios);
Assert.False (android);
Assert.False (winphone);
}
[Test]
public void TestOnPlatformAndroid ()
{
var view = new View ();
bool ios = false;
bool android = false;
bool winphone = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.Android;
Device.OnPlatform (
iOS: () => ios = true,
Android: () => android = true,
WinPhone: () => winphone = true);
Assert.False (ios);
Assert.True (android);
Assert.False (winphone);
}
[Test]
public void TestOnPlatformWinPhone ()
{
var view = new View ();
bool ios = false;
bool android = false;
bool winphone = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.WinPhone;
Device.OnPlatform (
iOS: () => ios = true,
Android: () => android = true,
WinPhone: () => winphone = true);
Assert.False (ios);
Assert.False (android);
Assert.True (winphone);
}
[Test]
public void TestOnPlatformDefault ()
{
var view = new View ();
bool ios = false;
bool android = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.Android;
Device.OnPlatform (
iOS: () => ios = false,
Default: () => android = true);
Assert.False (ios);
Assert.True (android);
}
[Test]
public void TestOnPlatformNoOpWithoutDefault ()
{
bool any = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = "Other";
Device.OnPlatform (
iOS: () => any = true,
Android: () => any = true,
WinPhone: () => any = true);
Assert.False (any);
}
[Test]
public void TestDefaultOniOS ()
{
bool defaultExecuted = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.iOS;
Device.OnPlatform (
Android: () => { },
WinPhone: () => { },
Default:() => defaultExecuted = true);
Assert.True (defaultExecuted);
}
[Test]
public void TestDefaultOnAndroid ()
{
bool defaultExecuted = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.Android;
Device.OnPlatform (
iOS: () => { },
WinPhone: () => { },
Default:() => defaultExecuted = true);
Assert.True (defaultExecuted);
}
[Test]
public void TestDefaultOnWinPhone ()
{
bool defaultExecuted = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.WinPhone;
Device.OnPlatform (
iOS: () => { },
Android: () => { },
Default:() => defaultExecuted = true);
Assert.True (defaultExecuted);
}
[Test]
public void TestDefaultOnOther ()
{
bool defaultExecuted = false;
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = "Other";
Device.OnPlatform (
iOS: () => { },
Android: () => { },
WinPhone: () => { },
Default:() => defaultExecuted = true);
Assert.True (defaultExecuted);
}
[Test]
public void TestNativeStateConsistent ()
{
var view = new View { IsPlatformEnabled = true };
Assert.True (view.IsNativeStateConsistent);
view.IsNativeStateConsistent = false;
Assert.False (view.IsNativeStateConsistent);
bool sizeChanged = false;
view.MeasureInvalidated += (sender, args) => {
sizeChanged = true;
};
view.IsNativeStateConsistent = true;
Assert.True (sizeChanged);
sizeChanged = false;
view.IsNativeStateConsistent = true;
Assert.False (sizeChanged);
}
[Test]
public void TestFadeTo ()
{
var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.FadeTo (0.1);
Assert.True (Math.Abs (0.1 - view.Opacity) < 0.001);
}
[Test]
public void TestTranslateTo ()
{
var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.TranslateTo (100, 50);
Assert.AreEqual (100, view.TranslationX);
Assert.AreEqual (50, view.TranslationY);
}
[Test]
public void ScaleTo ()
{
var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.ScaleTo (2);
Assert.AreEqual (2, view.Scale);
}
[Test]
public void TestNativeSizeChanged ()
{
var view = new View ();
bool sizeChanged = false;
view.MeasureInvalidated += (sender, args) => sizeChanged = true;
((IVisualElementController)view).NativeSizeChanged ();
Assert.True (sizeChanged);
}
[Test]
public void TestRotateTo ()
{
var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.RotateTo (25);
Assert.That (view.Rotation, Is.EqualTo (25).Within (0.001));
}
[Test]
public void TestRotateYTo ()
{
var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.RotateYTo (25);
Assert.That (view.RotationY, Is.EqualTo (25).Within (0.001));
}
[Test]
public void TestRotateXTo ()
{
var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.RotateXTo (25);
Assert.That (view.RotationX, Is.EqualTo (25).Within (0.001));
}
[Test]
public void TestRelRotateTo ()
{
var view = new View {Rotation = 30, IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.RelRotateTo (20);
Assert.That (view.Rotation, Is.EqualTo (50).Within (0.001));
}
[Test]
public void TestRelScaleTo ()
{
var view = new View {Scale = 1, IsPlatformEnabled = true, Platform = new UnitPlatform ()};
Ticker.Default = new BlockingTicker ();
view.RelScaleTo (1);
Assert.That (view.Scale, Is.EqualTo (2).Within (0.001));
}
class ParentSignalView : View
{
public bool ParentSet { get; set; }
protected override void OnParentSet ()
{
ParentSet = true;
base.OnParentSet ();
}
}
[Test]
public void TestDoubleSetParent ()
{
var view = new ParentSignalView ();
var parent = new NaiveLayout {Children = {view}};
view.ParentSet = false;
view.Parent = parent;
Assert.False (view.ParentSet, "OnParentSet should not be called in the event the parent is already properly set");
}
[Test]
public void TestAncestorAdded ()
{
var child = new NaiveLayout ();
var view = new NaiveLayout {Children = {child}};
bool added = false;
view.DescendantAdded += (sender, arg) => added = true;
child.Children.Add (new View ());
Assert.True (added, "AncestorAdded must fire when adding a child to an ancestor of a view.");
}
[Test]
public void TestAncestorRemoved ()
{
var ancestor = new View ();
var child = new NaiveLayout {Children = {ancestor}};
var view = new NaiveLayout {Children = {child}};
bool removed = false;
view.DescendantRemoved += (sender, arg) => removed = true;
child.Children.Remove (ancestor);
Assert.True (removed, "AncestorRemoved must fire when removing a child from an ancestor of a view.");
}
[Test]
public void TestOnPlatformGeneric ()
{
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.WinPhone;
Assert.AreEqual (3, Device.OnPlatform (1, 2, 3));
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.iOS;
Assert.AreEqual (1, Device.OnPlatform (1, 2, 3));
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.Android;
Assert.AreEqual (2, Device.OnPlatform (1, 2, 3));
((MockPlatformServices)Device.PlatformServices).RuntimePlatform = "Other";
Assert.AreEqual (1, Device.OnPlatform (1, 2, 3));
}
[Test]
public void TestBatching ()
{
var view = new View ();
bool committed = false;
view.BatchCommitted += (sender, arg) => committed = true;
view.BatchBegin ();
Assert.True (view.Batched);
view.BatchBegin ();
Assert.True (view.Batched);
view.BatchCommit ();
Assert.True (view.Batched);
Assert.False (committed);
view.BatchCommit ();
Assert.False (view.Batched);
Assert.True (committed);
}
[Test]
public void IsPlatformEnabled ()
{
var view = new View ();
Assert.False (view.IsPlatformEnabled);
view.IsPlatformEnabled = true;
Assert.True (view.IsPlatformEnabled);
view.IsPlatformEnabled = false;
Assert.False (view.IsPlatformEnabled);
}
[Test]
public void TestBindingContextChaining ()
{
View child;
var group = new NaiveLayout {
Children = { (child = new View ()) }
};
var context = new object ();
group.BindingContext = context;
Assert.AreEqual (context, child.BindingContext);
}
[Test]
public void FocusWithoutSubscriber ()
{
var view = new View ();
Assert.False (view.Focus ());
}
[Test]
public void FocusWithSubscriber ([Values(true, false)] bool result)
{
var view = new View ();
view.FocusChangeRequested += (sender, arg) => arg.Result = result;
Assert.True (view.Focus () == result);
}
[Test]
public void DoNotSignalWhenAlreadyFocused ()
{
var view = new View ();
view.SetValueCore (VisualElement.IsFocusedPropertyKey, true);
bool signaled = false;
view.FocusChangeRequested += (sender, args) => signaled = true;
Assert.True (view.Focus (), "View.Focus returned false");
Assert.False (signaled, "FocusRequested was raised");
}
[Test]
public void UnFocus ()
{
var view = new View ();
view.SetValueCore (VisualElement.IsFocusedPropertyKey, true);
var requested = false;
view.FocusChangeRequested += (sender, args) => {
requested = !args.Focus;
};
view.Unfocus ();
Assert.True (requested);
}
[Test]
public void UnFocusDoesNotFireWhenNotFocused ()
{
var view = new View ();
view.SetValueCore (VisualElement.IsFocusedPropertyKey, false);
var requested = false;
view.FocusChangeRequested += (sender, args) => {
requested = args.Focus;
};
view.Unfocus ();
Assert.False (requested);
}
[Test]
public void PlatformSet ()
{
var view = new View ();
bool set = false;
view.PlatformSet += (sender, args) => set = true;
view.Platform = new UnitPlatform ();
Assert.True (set);
}
[Test]
public void TestFocusedEvent ()
{
var view = new View ();
bool fired = false;
view.Focused += (sender, args) => fired = true;
view.SetValueCore (VisualElement.IsFocusedPropertyKey, true);
Assert.True (fired);
}
[Test]
public void TestUnFocusedEvent ()
{
var view = new View ();
view.SetValueCore (VisualElement.IsFocusedPropertyKey, true);
bool fired = false;
view.Unfocused += (sender, args) => fired = true;
view.SetValueCore (VisualElement.IsFocusedPropertyKey, false);
Assert.True (fired);
}
[Test]
public void TestBeginInvokeOnMainThread ()
{
Device.PlatformServices = new MockPlatformServices (invokeOnMainThread: action => action ());
bool invoked = false;
Device.BeginInvokeOnMainThread (() => invoked = true);
Assert.True (invoked);
}
[Test]
public void InvokeOnMainThreadThrowsWhenNull ()
{
Device.PlatformServices = null;
Assert.Throws<InvalidOperationException>(() => Device.BeginInvokeOnMainThread (() => { }));
}
[Test]
public void TestOpenUriAction ()
{
var uri = new Uri ("http://www.xamarin.com/");
var invoked = false;
Device.PlatformServices = new MockPlatformServices (openUriAction: u => {
Assert.AreSame (uri, u);
invoked = true;
});
Device.OpenUri (uri);
Assert.True (invoked);
}
[Test]
public void OpenUriThrowsWhenNull ()
{
Device.PlatformServices = null;
var uri = new Uri ("http://www.xamarin.com/");
Assert.Throws<InvalidOperationException> (() => Device.OpenUri (uri));
}
[Test]
public void MinimumWidthRequest ()
{
var view = new View ();
bool signaled = false;
view.MeasureInvalidated += (sender, args) => signaled = true;
view.MinimumWidthRequest = 10;
Assert.True (signaled);
Assert.AreEqual (10, view.MinimumWidthRequest);
signaled = false;
view.MinimumWidthRequest = 10;
Assert.False (signaled);
}
[Test]
public void MinimumHeightRequest ()
{
var view = new View ();
bool signaled = false;
view.MeasureInvalidated += (sender, args) => signaled = true;
view.MinimumHeightRequest = 10;
Assert.True (signaled);
Assert.AreEqual (10, view.MinimumHeightRequest);
signaled = false;
view.MinimumHeightRequest = 10;
Assert.False (signaled);
}
[Test]
public void MinimumWidthRequestInSizeRequest ()
{
var view = new View {
Platform = new UnitPlatform (),
IsPlatformEnabled = true
};
view.HeightRequest = 20;
view.WidthRequest = 200;
view.MinimumWidthRequest = 100;
var result = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity);
Assert.AreEqual (new Size (200, 20), result.Request);
Assert.AreEqual (new Size (100, 20), result.Minimum);
}
[Test]
public void MinimumHeightRequestInSizeRequest ()
{
var view = new View {
Platform = new UnitPlatform (),
IsPlatformEnabled = true
};
view.HeightRequest = 200;
view.WidthRequest = 20;
view.MinimumHeightRequest = 100;
var result = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity);
Assert.AreEqual (new Size (20, 200), result.Request);
Assert.AreEqual (new Size (20, 100), result.Minimum);
}
[Test]
public void StartTimerSimple ()
{
Device.PlatformServices = new MockPlatformServices ();
var task = new TaskCompletionSource<bool> ();
Task.Factory.StartNew (() => Device.StartTimer (TimeSpan.FromMilliseconds (200), () => {
task.SetResult (false);
return false;
}));
task.Task.Wait ();
Assert.False (task.Task.Result);
Device.PlatformServices = null;
}
[Test]
public void StartTimerMultiple ()
{
Device.PlatformServices = new MockPlatformServices ();
var task = new TaskCompletionSource<int> ();
int steps = 0;
Task.Factory.StartNew (() => Device.StartTimer (TimeSpan.FromMilliseconds (200), () => {
steps++;
if (steps < 2)
return true;
task.SetResult (steps);
return false;
}));
task.Task.Wait ();
Assert.AreEqual (2, task.Task.Result);
Device.PlatformServices = null;
}
[Test]
public void BindingsApplyAfterViewAddedToParentWithContextSet()
{
var parent = new NaiveLayout();
parent.BindingContext = new MockViewModel { Text = "test" };
var child = new Entry();
child.SetBinding (Entry.TextProperty, new Binding ("Text"));
parent.Children.Add (child);
Assert.That (child.BindingContext, Is.SameAs (parent.BindingContext));
Assert.That (child.Text, Is.EqualTo ("test"));
}
[Test]
public void IdIsUnique ()
{
var view1 = new View ();
var view2 = new View ();
Assert.True (view1.Id != view2.Id);
}
[Test]
public void MockBounds ()
{
var view = new View ();
view.Layout (new Rectangle (10, 20, 30, 40));
bool changed = false;
view.PropertyChanged += (sender, args) => {
if (args.PropertyName == View.XProperty.PropertyName ||
args.PropertyName == View.YProperty.PropertyName ||
args.PropertyName == View.WidthProperty.PropertyName ||
args.PropertyName == View.HeightProperty.PropertyName)
changed = true;
};
view.SizeChanged += (sender, args) => changed = true;
view.MockBounds (new Rectangle (5, 10, 15, 20));
Assert.AreEqual (new Rectangle (5, 10, 15, 20), view.Bounds);
Assert.False (changed);
view.UnmockBounds ();
Assert.AreEqual (new Rectangle (10, 20, 30, 40), view.Bounds);
Assert.False (changed);
}
[Test]
public void AddGestureRecognizer ()
{
var view = new View ();
var gestureRecognizer = new TapGestureRecognizer ();
view.GestureRecognizers.Add (gestureRecognizer);
Assert.True (view.GestureRecognizers.Contains (gestureRecognizer));
}
[Test]
public void AddGestureRecognizerSetsParent ()
{
var view = new View ();
var gestureRecognizer = new TapGestureRecognizer ();
view.GestureRecognizers.Add (gestureRecognizer);
Assert.AreEqual (view, gestureRecognizer.Parent);
}
[Test]
public void RemoveGestureRecognizerUnsetsParent ()
{
var view = new View ();
var gestureRecognizer = new TapGestureRecognizer ();
view.GestureRecognizers.Add (gestureRecognizer);
view.GestureRecognizers.Remove (gestureRecognizer);
Assert.Null (gestureRecognizer.Parent);
}
[Test]
public void WidthRequestEffectsGetSizeRequest ()
{
var view = new View ();
view.IsPlatformEnabled = true;
view.Platform = new UnitPlatform ((ve, widthConstraint, heightConstraint) => {
if (widthConstraint < 30)
return new SizeRequest (new Size (40, 50));
return new SizeRequest(new Size(20, 100));
});
view.WidthRequest = 20;
var request = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity);
Assert.AreEqual (new Size (20, 50), request.Request);
}
[Test]
public void HeightRequestEffectsGetSizeRequest ()
{
var view = new View ();
view.IsPlatformEnabled = true;
view.Platform = new UnitPlatform ((ve, widthConstraint, heightConstraint) => {
if (heightConstraint < 30)
return new SizeRequest (new Size (40, 50));
return new SizeRequest(new Size(20, 100));
});
view.HeightRequest = 20;
var request = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity);
Assert.AreEqual (new Size (40, 20), request.Request);
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Globalization;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.WebHooks.Properties;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.WebHooks.Filters
{
/// <summary>
/// Base class for <see cref="IResourceFilter"/> or <see cref="IAsyncResourceFilter"/> implementations that for
/// example verify request signatures or <c>code</c> query parameters. Subclasses may also implement
/// <see cref="IWebHookReceiver"/>. Subclasses by default have an <see cref="IOrderedFilter.Order"/> equal to
/// <see cref="Order"/>.
/// </summary>
public abstract class WebHookSecurityFilter : IOrderedFilter
{
/// <summary>
/// Instantiates a new <see cref="WebHookSecurityFilter"/> instance.
/// </summary>
/// <param name="configuration">
/// The <see cref="IConfiguration"/> used to initialize <see cref="Configuration"/>.
/// </param>
/// <param name="hostingEnvironment">
/// The <see cref="IHostingEnvironment" /> used to initialize <see cref="HostingEnvironment"/>.
/// </param>
/// <param name="loggerFactory">
/// The <see cref="ILoggerFactory"/> used to initialize <see cref="Logger"/>.
/// </param>
protected WebHookSecurityFilter(
IConfiguration configuration,
IHostingEnvironment hostingEnvironment,
ILoggerFactory loggerFactory)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (hostingEnvironment == null)
{
throw new ArgumentNullException(nameof(hostingEnvironment));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
Configuration = configuration;
HostingEnvironment = hostingEnvironment;
Logger = loggerFactory.CreateLogger(GetType());
}
/// <summary>
/// Gets the <see cref="IOrderedFilter.Order"/> recommended for all <see cref="WebHookSecurityFilter"/>
/// instances. The recommended filter sequence is
/// <list type="number">
/// <item>
/// Confirm WebHooks configuration is set up correctly (in <see cref="WebHookReceiverExistsFilter"/>).
/// </item>
/// <item>
/// Confirm signature or <c>code</c> query parameter e.g. in <see cref="WebHookVerifyCodeFilter"/> or other
/// <see cref="WebHookSecurityFilter"/> subclass.
/// </item>
/// <item>
/// Confirm required headers, <see cref="RouteValueDictionary"/> entries and query parameters are provided (in
/// <see cref="WebHookVerifyRequiredValueFilter"/>).
/// </item>
/// <item>
/// Short-circuit GET or HEAD requests, if receiver supports either (in
/// <see cref="WebHookGetHeadRequestFilter"/>).
/// </item>
/// <item>Confirm it's a POST request (in <see cref="WebHookVerifyMethodFilter"/>).</item>
/// <item>Confirm body type (in <see cref="WebHookVerifyBodyTypeFilter"/>).</item>
/// <item>
/// Map event name(s), if not done in <see cref="Routing.WebHookEventNameMapperConstraint"/> for this receiver
/// (in <see cref="WebHookEventNameMapperFilter"/>).
/// </item>
/// <item>
/// Short-circuit ping requests, if not done in <see cref="WebHookGetHeadRequestFilter"/> for this receiver (in
/// <see cref="WebHookPingRequestFilter"/>).
/// </item>
/// </list>
/// </summary>
public static int Order => WebHookReceiverExistsFilter.Order + 10;
/// <inheritdoc />
int IOrderedFilter.Order => Order;
/// <summary>
/// Gets the <see cref="IConfiguration"/> for the application.
/// </summary>
protected IConfiguration Configuration;
/// <summary>
/// Gets the <see cref="IHostingEnvironment" />.
/// </summary>
protected IHostingEnvironment HostingEnvironment { get; }
/// <summary>
/// Gets an <see cref="ILogger"/> for use in this class and any subclasses.
/// </summary>
/// <remarks>
/// Methods in this class use <see cref="EventId"/>s that should be distinct from (higher than) those used in
/// subclasses.
/// </remarks>
protected ILogger Logger { get; }
/// <summary>
/// Some WebHooks rely on HTTPS for sending WebHook requests in a secure manner. A
/// <see cref="WebHookSecurityFilter"/> subclass can call this method to ensure that the incoming WebHook
/// request is using HTTPS. If the request is not using HTTPS an error will be generated and the request will
/// not be further processed.
/// </summary>
/// <remarks>
/// This method allows HTTP requests while the application is in development or if the
/// <see cref="WebHookConstants.DisableHttpsCheckConfigurationKey"/> is <see langword="true"/>.
/// </remarks>
/// <param name="receiverName">The name of an available <see cref="IWebHookReceiver"/>.</param>
/// <param name="request">The current <see cref="HttpRequest"/>.</param>
/// <returns>
/// <see langword="null"/> in the success case. When a check fails, an <see cref="IActionResult"/> that when
/// executed will produce a response containing details about the problem.
/// </returns>
protected virtual IActionResult EnsureSecureConnection(string receiverName, HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
// Check to see if we have been configured to ignore this check.
var disableHttpsCheckString = Configuration[WebHookConstants.DisableHttpsCheckConfigurationKey];
if (HostingEnvironment.IsDevelopment() ||
(bool.TryParse(disableHttpsCheckString, out var disableHttpsCheck) && disableHttpsCheck))
{
return null;
}
// Require HTTPS.
if (!request.IsHttps)
{
Logger.LogWarning(
500,
"The '{ReceiverName}' WebHook receiver requires SSL/TLS in order to be secure. Register a " +
$"WebHook URI of type '{Uri.UriSchemeHttps}'.",
receiverName);
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.Security_NoHttps,
receiverName,
Uri.UriSchemeHttps.ToUpper(),
Uri.UriSchemeHttps);
var noHttps = new BadRequestObjectResult(message);
return noHttps;
}
return null;
}
/// <summary>
/// Gets the locally configured WebHook secret key used to validate any signature header provided in a WebHook
/// request.
/// </summary>
/// <param name="sectionKey">
/// The key (relative to <see cref="WebHookConstants.ReceiverConfigurationSectionKey"/>) of the
/// <see cref="IConfigurationSection"/> containing the receiver-specific
/// <see cref="WebHookConstants.SecretKeyConfigurationKeySectionKey"/> <see cref="IConfigurationSection"/>.
/// Typically this is the name of the receiver e.g. <c>github</c>.
/// </param>
/// <param name="routeData">
/// The <see cref="RouteData"/> for this request. A (potentially empty) ID value in this data allows a
/// <see cref="WebHookSecurityFilter"/> subclass to support multiple senders with individual configurations.
/// </param>
/// <param name="minLength">The minimum length of the key value.</param>
/// <returns>
/// The configured WebHook secret key. <see langword="null"/> if the configuration value does not exist.
/// </returns>
protected virtual string GetSecretKey(string sectionKey, RouteData routeData, int minLength)
{
if (sectionKey == null)
{
throw new ArgumentNullException(nameof(sectionKey));
}
if (routeData == null)
{
throw new ArgumentNullException(nameof(routeData));
}
// Look up configuration for this receiver and instance.
var secrets = GetSecretKeys(sectionKey, routeData);
if (!secrets.Exists())
{
// Have already logged about this case.
return null;
}
var secret = secrets.Value;
if (secret == null)
{
// Strange case: User incorrectly configured this id with sub-keys.
Logger.LogError(
501,
"Found a corrupted configuration for the '{ReceiverName}' WebHook receiver.",
sectionKey);
return null;
}
if (secret.Length < minLength)
{
// Secrete key found but it does not meet the length requirements.
routeData.TryGetWebHookReceiverId(out var id);
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.Security_BadSecret,
sectionKey,
id,
minLength);
throw new InvalidOperationException(message);
}
return secret;
}
/// <summary>
/// Gets the locally configured WebHook secret keys used to validate any signature header provided in a WebHook
/// request.
/// </summary>
/// <param name="sectionKey">
/// The key (relative to <see cref="WebHookConstants.ReceiverConfigurationSectionKey"/>) of the
/// <see cref="IConfigurationSection"/> containing the receiver-specific
/// <see cref="WebHookConstants.SecretKeyConfigurationKeySectionKey"/> <see cref="IConfigurationSection"/>.
/// Typically this is the name of the receiver e.g. <c>github</c>.
/// </param>
/// <param name="routeData">
/// The <see cref="RouteData"/> for this request. A (potentially empty) ID value in this data allows a
/// <see cref="WebHookSecurityFilter"/> subclass to support multiple senders with individual configurations.
/// </param>
/// <returns>
/// The <see cref="IConfigurationSection"/> containing the configured WebHook secret keys.
/// <see langword="null"/> if the <see cref="IConfigurationSection"/> does not exist.
/// </returns>
protected virtual IConfigurationSection GetSecretKeys(string sectionKey, RouteData routeData)
{
if (sectionKey == null)
{
throw new ArgumentNullException(nameof(sectionKey));
}
if (routeData == null)
{
throw new ArgumentNullException(nameof(routeData));
}
routeData.TryGetWebHookReceiverId(out var id);
// Look up configuration for this receiver and instance
var secrets = GetSecretKeys(Configuration, sectionKey, id);
if (!secrets.Exists())
{
if (!HasSecretKeys(Configuration, sectionKey))
{
// No secret key configuration for this receiver at all.
var message = string.Format(CultureInfo.CurrentCulture, Resources.Security_NoSecrets, sectionKey);
throw new InvalidOperationException(message);
}
// ID was not configured. Caller should treat null return value with a Not Found response.
Logger.LogWarning(
502,
"Could not find a valid configuration for the '{ReceiverName}' WebHook receiver, instance '{Id}'.",
sectionKey,
id);
}
return secrets;
}
/// <summary>
/// Provides a time consistent comparison of two secrets in the form of two strings.
/// </summary>
/// <param name="inputA">The first secret to compare.</param>
/// <param name="inputB">The second secret to compare.</param>
/// <returns>
/// Returns <see langword="true"/> if the two secrets are equal; <see langword="false"/> otherwise.
/// </returns>
[MethodImpl(MethodImplOptions.NoOptimization)]
protected internal static bool SecretEqual(string inputA, string inputB)
{
if (ReferenceEquals(inputA, inputB))
{
return true;
}
if (inputA == null || inputB == null || inputA.Length != inputB.Length)
{
return false;
}
var areSame = true;
for (var i = 0; i < inputA.Length; i++)
{
areSame &= inputA[i] == inputB[i];
}
return areSame;
}
private static IConfigurationSection GetSecretKeys(IConfiguration configuration, string sectionKey, string id)
{
if (string.IsNullOrEmpty(id))
{
id = WebHookConstants.DefaultIdConfigurationKey;
}
// Look up configuration value for these keys.
var key = ConfigurationPath.Combine(
WebHookConstants.ReceiverConfigurationSectionKey,
sectionKey,
WebHookConstants.SecretKeyConfigurationKeySectionKey,
id);
return configuration.GetSection(key);
}
private static bool HasSecretKeys(IConfiguration configuration, string sectionKey)
{
var key = ConfigurationPath.Combine(
WebHookConstants.ReceiverConfigurationSectionKey,
sectionKey,
WebHookConstants.SecretKeyConfigurationKeySectionKey);
return configuration.GetSection(key).Exists();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.IO;
using System.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
// ===================== ValidateElement =====================
public class TCValidateElement : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateElement(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Theory]
[InlineData("name", "first")]
[InlineData("name", "second")]
[InlineData("ns", "first")]
[InlineData("ns", "second")]
public void PassNull_LocalName_NamespaceUri_Invalid_First_Second_Overload(string type, string overload)
{
XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root />"));
string name = "root";
string ns = "";
XmlSchemaInfo info = new XmlSchemaInfo();
if (type == "name")
name = null;
else
ns = null;
val.Initialize();
try
{
if (overload == "first")
val.ValidateElement(name, ns, info);
else
val.ValidateElement(name, ns, info, null, null, null, null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Theory]
[InlineData("first")]
[InlineData("second")]
public void PassNullXmlSchemaInfo__Valid_First_Second_Overload(string overload)
{
XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root />"));
val.Initialize();
if (overload == "first")
val.ValidateElement("root", "", null);
else
val.ValidateElement("root", "", null, null, null, null, null);
return;
}
[Theory]
[InlineData("first")]
[InlineData("second")]
public void PassInvalidName_First_Second_Overload(string overload)
{
XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root />"));
val.Initialize();
try
{
if (overload == "first")
val.ValidateElement("$$##", "", null);
else
val.ValidateElement("$$##", "", null, null, null, null, null);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_UndeclaredElement", new string[] { "$$##" });
return;
}
Assert.True(false);
}
[Theory]
[InlineData("SimpleElement", XmlSchemaContentType.TextOnly, "first")]
[InlineData("ElementOnlyElement", XmlSchemaContentType.ElementOnly, "first")]
[InlineData("EmptyElement", XmlSchemaContentType.Empty, "first")]
[InlineData("MixedElement", XmlSchemaContentType.Mixed, "first")]
[InlineData("SimpleElement", XmlSchemaContentType.TextOnly, "second")]
[InlineData("ElementOnlyElement", XmlSchemaContentType.ElementOnly, "second")]
[InlineData("EmptyElement", XmlSchemaContentType.Empty, "second")]
[InlineData("MixedElement", XmlSchemaContentType.Mixed, "second")]
public void CallValidateElementAndCHeckXmlSchemaInfoFOr_Simple_Complex_Empty_Mixed_Element_First_Second_Overload(string elemType, XmlSchemaContentType schemaContentType, string overload)
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
string name = elemType;
schemas.Add("", Path.Combine(TestData, XSDFILE_VALIDATE_TEXT));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
if (overload == "first")
val.ValidateElement(name, "", info);
else
val.ValidateElement(name, "", info, null, null, null, null);
Assert.Equal(info.ContentType, schemaContentType);
Assert.Equal(XmlSchemaValidity.NotKnown, info.Validity);
Assert.Equal(info.SchemaElement, schemas.GlobalElements[new XmlQualifiedName(name)]);
Assert.False(info.IsNil);
Assert.False(info.IsDefault);
if (name == "SimpleElement")
Assert.True(info.SchemaType is XmlSchemaSimpleType);
else
Assert.True(info.SchemaType is XmlSchemaComplexType);
return;
}
[Fact]
public void SanityTestsForNestedElements()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
schemas.Add("", Path.Combine(TestData, XSDFILE_VALIDATE_END_ELEMENT));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
val.ValidateElement("NestedElement", "", info);
val.ValidateEndOfAttributes(null);
Assert.Equal(info.SchemaElement.QualifiedName, new XmlQualifiedName("NestedElement"));
Assert.True(info.SchemaType is XmlSchemaComplexType);
val.ValidateElement("foo", "", info);
val.ValidateEndOfAttributes(null);
Assert.Equal(info.SchemaElement.QualifiedName, new XmlQualifiedName("foo"));
Assert.True(info.SchemaType is XmlSchemaComplexType);
val.ValidateElement("bar", "", info);
Assert.Equal(info.SchemaElement.QualifiedName, new XmlQualifiedName("bar"));
Assert.True(info.SchemaType is XmlSchemaSimpleType);
Assert.Equal(XmlTypeCode.String, info.SchemaType.TypeCode);
return;
}
// ====== second overload ======
[Theory]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation)]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema)]
public void CheckSchemaLocationIs_UsedWhenSpecified_NotUsedWhenFlagIsNotSet(XmlSchemaValidationFlags allFlags)
{
XmlSchemaValidator val;
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
schemas.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:element name=\"root\" />\n" +
"</xs:schema>")));
val = CreateValidator(schemas, ns, allFlags);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
val.ValidateElement("root", "", info, "t:type1", null, "uri:tempuri " + Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE), null);
if ((int)allFlags == (int)AllFlags)
{
Assert.True(!holder.IsCalledA);
Assert.True(info.SchemaType is XmlSchemaComplexType);
}
else
{
Assert.True(holder.IsCalledA);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_XsiTypeNotFound", new string[] { "uri:tempuri:type1" });
}
return;
}
[Theory]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation)]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema)]
public void CheckNoNamespaceSchemaLocationIs_UsedWhenSpecified_NotUsedWhenFlagIsSet(XmlSchemaValidationFlags allFlags)
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
schemas.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:element name=\"root\" />\n" +
"</xs:schema>")));
val = CreateValidator(schemas, allFlags);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("root", "", info, "type1", null, null, Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE));
if ((int)allFlags == (int)AllFlags)
{
Assert.True(!holder.IsCalledA);
Assert.True(info.SchemaType is XmlSchemaComplexType);
}
else
{
Assert.True(holder.IsCalledA);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_XsiTypeNotFound", new string[] { "type1" });
}
return;
}
[Theory]
[InlineData(null)]
[InlineData("false")]
public void CallWith_Null_False_XsiNil(string xsiNil)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.Initialize();
val.ValidateElement("NillableElement", "", info, null, xsiNil, null, null);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateEndElement(info);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, new object[] { "Sch_IncompleteContentExpecting",
new object[] { "Sch_ElementName", "NillableElement" },
new object[] { "Sch_ElementName", "foo" } });
return;
}
Assert.True(false);
}
[Fact]
public void CallWithXsiNilTrue()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.Initialize();
val.ValidateElement("NillableElement", "", info, null, "true", null, null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
return;
}
[Fact]
public void ProvideValidXsiType()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("uri:tempuri", Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE));
val = CreateValidator(schemas, ns, 0);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
val.ValidateElement("foo", "uri:tempuri", null, "t:type1", null, null, null);
return;
}
[Fact]
public void ProvideInvalidXsiType()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("uri:tempuri", Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE));
val = CreateValidator(schemas, ns, 0);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
try
{
val.ValidateElement("foo", "uri:tempuri", null, "type1", null, null, null);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_XsiTypeNotFound", new string[] { "type1" });
return;
}
Assert.True(false);
}
[Fact]
public void CheckThatWarningOccursWhenInvalidSchemaLocationIsProvided()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
schemas.Add("uri:tempuri", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" +
" targetNamespace=\"uri:tempuri\">\n" +
" <xs:complexType name=\"rootType\">\n" +
" <xs:sequence />\n" +
" </xs:complexType>\n" +
"</xs:schema>")));
val = CreateValidator(schemas, ns, AllFlags);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
val.ValidateElement("root", "", info, "t:rootType", null, "uri:tempuri " + Path.Combine(TestData, "__NonExistingFile__.xsd"), null);
Assert.True(holder.IsCalledA);
Assert.Equal(XmlSeverityType.Warning, holder.lastSeverity);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_CannotLoadSchema", new string[] { "uri:tempuri", null });
return;
}
[Fact]
public void CheckThatWarningOccursWhenInvalidNoNamespaceSchemaLocationIsProvided()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
schemas.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:complexType name=\"rootType\">\n" +
" <xs:sequence />\n" +
" </xs:complexType>\n" +
"</xs:schema>")));
val = CreateValidator(schemas);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("root", "", info, "rootType", null, null, Path.Combine(TestData, "__NonExistingFile__.xsd"));
Assert.True(holder.IsCalledA);
Assert.Equal(XmlSeverityType.Warning, holder.lastSeverity);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_CannotLoadSchema", new string[] { "", null });
return;
}
[Fact]
public void CheckThatWarningOccursWhenUndefinedElementIsValidatedWithLaxValidation()
{
XmlSchemaValidator val;
CValidationEventHolder holder = new CValidationEventHolder();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("LaxElement", "", null);
val.ValidateEndOfAttributes(null);
val.ValidateElement("undefined", "", null);
Assert.True(holder.IsCalledA);
Assert.Equal(XmlSeverityType.Warning, holder.lastSeverity);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_NoElementSchemaFound", new string[] { "undefined" });
return;
}
[Fact]
public void CheckThatWarningsDontOccurWhenIgnoreValidationWarningsIsSet()
{
XmlSchemaValidator val;
CValidationEventHolder holder = new CValidationEventHolder();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT, "", XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation);
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("LaxElement", "", null);
val.ValidateEndOfAttributes(null);
val.ValidateElement("undefined", "", null);
Assert.True(!holder.IsCalledA);
return;
}
//342447
[Fact]
public void VerifyThatSubstitutionGroupMembersAreResolvedAndAddedToTheList()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaParticle[] actualParticles;
string[] expectedParticles = { "eleA", "eleB", "eleC" };
schemas.Add("", Path.Combine(TestData, "Bug342447.xsd"));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
val.ValidateElement("eleSeq", "", null);
actualParticles = val.GetExpectedParticles();
Assert.Equal(actualParticles.GetLength(0), expectedParticles.GetLength(0));
int count = 0;
foreach (XmlSchemaElement element in actualParticles)
{
Assert.Equal(element.QualifiedName.ToString(), expectedParticles[count++]);
}
return;
}
[Fact]
public void StringPassedToValidateEndElementDoesNotSatisfyIdentityConstraints()
{
Initialize();
string xsd =
"<xs:schema targetNamespace='http://tempuri.org/XMLSchema.xsd' elementFormDefault='qualified' xmlns='http://tempuri.org/XMLSchema.xsd' xmlns:mstns='http://tempuri.org/XMLSchema.xsd' xmlns:xs='http://www.w3.org/2001/XMLSchema'>" +
"<xs:element name='root'>" +
"<xs:complexType> <xs:sequence> <xs:element name='B' type='mstns:B'/> </xs:sequence> </xs:complexType>" +
"<xs:unique name='pNumKey'><xs:selector xpath='mstns:B/mstns:part'/><xs:field xpath='.'/></xs:unique>" +
"</xs:element>" +
"<xs:complexType name='B'><xs:sequence><xs:element name='part' maxOccurs='unbounded' type='xs:string'></xs:element></xs:sequence></xs:complexType>" +
"</xs:schema>";
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add(XmlSchema.Read(new StringReader(xsd), ValidationCallback));
ss.Compile();
string ns = "http://tempuri.org/XMLSchema.xsd";
XmlNamespaceManager nsmgr = new XmlNamespaceManager(ss.NameTable);
XmlSchemaValidator val = new XmlSchemaValidator(ss.NameTable, ss, nsmgr, XmlSchemaValidationFlags.ProcessIdentityConstraints);
val.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
val.Initialize();
XmlSchemaInfo si = new XmlSchemaInfo();
val.ValidateElement("root", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateElement("B", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateElement("part", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateText("1");
val.ValidateEndElement(si);
val.ValidateElement("part", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateEndElement(si, "1");
val.ValidateElement("part", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateText("1");
val.ValidateEndElement(si);
val.ValidateEndElement(si);
val.ValidateEndElement(si);
Assert.Equal(0, warningCount);
Assert.Equal(2, errorCount);
return;
}
//TFS_469834
[Fact]
public void XmlSchemaValidatorDoesNotEnforceIdentityConstraintsOnDefaultAttributesInSomeCases()
{
Initialize();
string xml = @"<?xml version='1.0'?>
<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='idF016.xsd'>
<uid val='test'/> <uid/></root>";
string xsd = @"<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'>
<xsd:element name='root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element ref='uid' maxOccurs='unbounded'/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique id='foo123' name='uuid'>
<xsd:selector xpath='.//uid'/>
<xsd:field xpath='@val'/>
</xsd:unique>
</xsd:element>
<xsd:element name='uid' nillable='true'>
<xsd:complexType>
<xsd:attribute name='val' type='xsd:string' default='test'/>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, XmlReader.Create(new StringReader(xsd)));
schemas.Compile();
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes;
XmlSchemaValidator validator = new XmlSchemaValidator(namespaceManager.NameTable, schemas, namespaceManager, validationFlags);
validator.Initialize();
using (XmlReader r = XmlReader.Create(new StringReader(xsd)))
{
while (r.Read())
{
switch (r.NodeType)
{
case XmlNodeType.Element:
namespaceManager.PushScope();
if (r.MoveToFirstAttribute())
{
do
{
if (r.NamespaceURI == "http://www.w3.org/2000/xmlns/")
{
namespaceManager.AddNamespace(r.LocalName, r.Value);
}
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
validator.ValidateElement(r.LocalName, r.NamespaceURI, null, null, null, null, null);
if (r.MoveToFirstAttribute())
{
do
{
if (r.NamespaceURI != "http://www.w3.org/2000/xmlns/")
{
validator.ValidateAttribute(r.LocalName, r.NamespaceURI, r.Value, null);
}
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
validator.ValidateEndOfAttributes(null);
if (r.IsEmptyElement) goto case XmlNodeType.EndElement;
break;
case XmlNodeType.EndElement:
validator.ValidateEndElement(null);
namespaceManager.PopScope();
break;
case XmlNodeType.Text:
validator.ValidateText(r.Value);
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
validator.ValidateWhitespace(r.Value);
break;
default:
break;
}
}
validator.EndValidation();
}
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.Schemas.Add(null, XmlReader.Create(new StringReader(xsd)));
using (XmlReader r = XmlReader.Create(new StringReader(xml), rs))
{
try
{
while (r.Read()) ;
}
catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); return; }
}
Assert.True(false);
}
}
}
| |
/*
* Copyright (c) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Firestore;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace GoogleCloudSamples
{
public class FirestoreFixture : IDisposable
{
// Clean-up function to delete all documents in a collection
private static async Task DeleteCollection(string collection)
{
FirestoreDb db = FirestoreDb.Create(Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
CollectionReference collectionReference = db.Collection(collection);
QuerySnapshot snapshot = await collectionReference.GetSnapshotAsync();
IReadOnlyList<DocumentSnapshot> documents = snapshot.Documents;
foreach (DocumentSnapshot document in documents)
{
await document.Reference.DeleteAsync();
}
}
// Clean-up function to delete all indexes in a collection
private static async Task DeleteIndexes(string collection)
{
GoogleCredential credential =
GoogleCredential.GetApplicationDefault();
//Inject the Cloud Platform scope if required.
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped(new[]
{
"https://www.googleapis.com/auth/cloud-platform"
});
}
HttpClient http = new Google.Apis.Http.HttpClientFactory()
.CreateHttpClient(
new Google.Apis.Http.CreateHttpClientArgs()
{
ApplicationName = "Google Cloud Platform Firestore Sample",
GZipEnabled = true,
Initializers = { credential },
});
string uriString = "https://firestore.googleapis.com/v1beta1/projects/"
+ Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID")
+ "/databases/(default)/indexes";
UriBuilder uri = new UriBuilder(uriString);
var resultText = http.GetAsync(uri.Uri).Result.Content
.ReadAsStringAsync().Result;
dynamic result = Newtonsoft.Json.JsonConvert
.DeserializeObject(resultText);
List<string> indexesToBeDeleted = new List<string>();
if (result.indexes != null)
{
foreach (var index in result.indexes)
{
if (index.collection == collection)
{
string name = index.name;
indexesToBeDeleted.Add(name);
}
}
}
foreach (string indexToBeDeleted in indexesToBeDeleted)
{
uriString = "https://firestore.googleapis.com/v1beta1/" + indexToBeDeleted;
UriBuilder deleteUri = new UriBuilder(uriString);
await http.DeleteAsync(deleteUri.Uri);
}
}
// Clean up function to delete all collections and indexes after testing is complete
public void Dispose()
{
DeleteCollection("users").Wait();
DeleteCollection("cities/SF/neighborhoods").Wait();
DeleteCollection("cities").Wait();
DeleteCollection("data").Wait();
DeleteIndexes("cities").Wait();
}
}
public class FirestoreTests : IClassFixture<FirestoreFixture>
{
readonly CommandLineRunner _quickstart = new CommandLineRunner()
{
VoidMain = Quickstart.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunQuickstart(params string[] args)
{
return _quickstart.Run(args);
}
readonly CommandLineRunner _addData = new CommandLineRunner()
{
VoidMain = AddData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunAddData(params string[] args)
{
return _addData.Run(args);
}
readonly CommandLineRunner _deleteData = new CommandLineRunner()
{
VoidMain = DeleteData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunDeleteData(params string[] args)
{
return _deleteData.Run(args);
}
readonly CommandLineRunner _getData = new CommandLineRunner()
{
VoidMain = GetData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunGetData(params string[] args)
{
return _getData.Run(args);
}
readonly CommandLineRunner _listenData = new CommandLineRunner()
{
VoidMain = ListenData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunListenData(params string[] args)
{
return _listenData.Run(args);
}
readonly CommandLineRunner _queryData = new CommandLineRunner()
{
VoidMain = QueryData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunQueryData(params string[] args)
{
return _queryData.Run(args);
}
readonly CommandLineRunner _orderLimitData = new CommandLineRunner()
{
VoidMain = OrderLimitData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunOrderLimitData(params string[] args)
{
return _orderLimitData.Run(args);
}
readonly CommandLineRunner _dataModel = new CommandLineRunner()
{
VoidMain = DataModel.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunDataModel(params string[] args)
{
return _dataModel.Run(args);
}
readonly CommandLineRunner _transactionsAndBatchedWrites = new CommandLineRunner()
{
VoidMain = TransactionsAndBatchedWrites.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunTransactionsAndBatchedWrites(params string[] args)
{
return _transactionsAndBatchedWrites.Run(args);
}
readonly CommandLineRunner _paginateData = new CommandLineRunner()
{
VoidMain = PaginateData.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunPaginateData(params string[] args)
{
return _paginateData.Run(args);
}
readonly CommandLineRunner _manageIndexes = new CommandLineRunner()
{
VoidMain = ManageIndexes.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunManageIndexes(params string[] args)
{
return _manageIndexes.Run(args);
}
readonly CommandLineRunner _distrubutedCounter = new CommandLineRunner()
{
VoidMain = DistributedCounter.Main,
Command = "dotnet run"
};
protected ConsoleOutput RunDistributedCounter(params string[] args)
{
return _distrubutedCounter.Run(args);
}
// QUICKSTART TESTS
[Fact]
public void InitializeProjectIdTest()
{
var output = RunQuickstart("initialize-project-id", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Created Cloud Firestore client with project ID:", output.Stdout);
}
[Fact]
public void AddData1Test()
{
var output = RunQuickstart("add-data-1", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added data to the alovelace document in the users collection.", output.Stdout);
}
[Fact]
public void AddData2Test()
{
var output = RunQuickstart("add-data-2", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added data to the aturing document in the users collection.", output.Stdout);
}
[Fact]
public void RetrieveAllDocumentsTest()
{
RunQuickstart("add-data-1", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
RunQuickstart("add-data-2", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQuickstart("retrieve-all-documents", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("User: alovelace", output.Stdout);
Assert.Contains("First: Ada", output.Stdout);
Assert.Contains("Last: Lovelace", output.Stdout);
Assert.Contains("Born: 1815", output.Stdout);
Assert.Contains("User: aturing", output.Stdout);
Assert.Contains("First: Alan", output.Stdout);
Assert.Contains("Middle: Mathison", output.Stdout);
Assert.Contains("Last: Turing", output.Stdout);
Assert.Contains("Born: 1912", output.Stdout);
}
// ADD DATA TESTS
[Fact]
public void AddDocAsMapTest()
{
var output = RunAddData("add-doc-as-map", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added data to the LA document in the cities collection.", output.Stdout);
}
[Fact]
public void UpdateCreateIfMissingTest()
{
var output = RunAddData("update-create-if-missing", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Merged data into the LA document in the cities collection.", output.Stdout);
}
[Fact]
public void AddDocDataTypesTest()
{
var output = RunAddData("add-doc-data-types", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Set multiple data-type data for the one document in the data collection.", output.Stdout);
}
[Fact]
public void AddSimpleDocAsEntityTest()
{
var output = RunAddData("add-simple-doc-as-entity", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added custom City object to the cities collection.", output.Stdout);
}
[Fact]
public void SetRequiresIdTest()
{
var output = RunAddData("set-requires-id", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added document with ID: new-city-id.", output.Stdout);
}
[Fact]
public void AddDocDataWithAutoIdTest()
{
var output = RunAddData("add-doc-data-with-auto-id", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added document with ID:", output.Stdout);
}
[Fact]
public void AddDocDataAfterAutoIdTest()
{
var output = RunAddData("add-doc-data-after-auto-id", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added document with ID:", output.Stdout);
Assert.Contains("Added data to the", output.Stdout);
Assert.Contains("document in the cities collection.", output.Stdout);
}
[Fact]
public void UpdateDocTest()
{
RunAddData("set-requires-id", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunAddData("update-doc", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Updated the Capital field of the new-city-id document in the cities collection.", output.Stdout);
}
[Fact]
public void UpdateNestedFieldsTest()
{
var output = RunAddData("update-nested-fields", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Updated the age and favorite color fields of the Frank document in the users collection.", output.Stdout);
}
[Fact]
public void UpdateServerTimestampTest()
{
RunAddData("set-requires-id", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunAddData("update-server-timestamp", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Updated the Timestamp field of the new-city-id document in the cities collection.", output.Stdout);
}
[Fact]
public void UpdateDocumentArrayTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunAddData("update-document-array", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Updated the Regions array of the DC document in the cities collection.", output.Stdout);
}
[Fact]
public void UpdateDocumentIncrementTest()
{
RunQueryData("update-document-increment", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunAddData("update-document-increment", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Updated the population of the DC document in the cities collection.", output.Stdout);
}
// DELETE DATA TESTS
[Fact]
public void DeleteDocTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunDeleteData("delete-doc", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Deleted the DC document in the cities collection.", output.Stdout);
}
[Fact]
public void DeleteFieldTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunDeleteData("delete-field", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Deleted the Capital field from the BJ document in the cities collection.", output.Stdout);
}
[Fact]
public void DeleteCollectionTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunDeleteData("delete-collection", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Deleting document BJ", output.Stdout);
Assert.Contains("Deleting document LA", output.Stdout);
Assert.Contains("Deleting document TOK", output.Stdout);
Assert.Contains("Deleting document SF", output.Stdout);
Assert.Contains("Finished deleting all documents from the collection.", output.Stdout);
}
// GET DATA TESTS
[Fact]
public void RetrieveCreateExamplesTest()
{
var output = RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added example cities data to the cities collection.", output.Stdout);
}
[Fact]
public void GetDocAsMapTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunGetData("get-doc-as-map", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document data for SF document:", output.Stdout);
Assert.Contains("Name: San Francisco", output.Stdout);
Assert.Contains("State: CA", output.Stdout);
Assert.Contains("Country: USA", output.Stdout);
Assert.Contains("Capital: False", output.Stdout);
Assert.Contains("Population: 860000", output.Stdout);
}
[Fact]
public void GetDocAsEntityTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunGetData("get-doc-as-entity", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document data for BJ document:", output.Stdout);
Assert.Contains("State:", output.Stdout);
Assert.Contains("Country: China", output.Stdout);
Assert.Contains("Capital: True", output.Stdout);
Assert.Contains("Population: 21500000", output.Stdout);
}
[Fact]
public void GetMultipleDocsTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunGetData("get-multiple-docs", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document data for DC document:", output.Stdout);
Assert.Contains("Document data for TOK document:", output.Stdout);
Assert.Contains("Document data for BJ document:", output.Stdout);
Assert.DoesNotContain("Document data for SF document:", output.Stdout);
Assert.DoesNotContain("Document data for LA document:", output.Stdout);
Assert.Contains("Name: Tokyo", output.Stdout);
Assert.Contains("State:", output.Stdout);
Assert.Contains("Country: Japan", output.Stdout);
Assert.Contains("Capital: True", output.Stdout);
Assert.Contains("Population: 9000000", output.Stdout);
}
[Fact]
public void GetAllDocsTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunGetData("get-all-docs", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document data for BJ document:", output.Stdout);
Assert.Contains("Document data for DC document:", output.Stdout);
Assert.Contains("Document data for LA document:", output.Stdout);
Assert.Contains("Document data for SF document:", output.Stdout);
Assert.Contains("Document data for TOK document:", output.Stdout);
Assert.Contains("Name: Los Angeles", output.Stdout);
Assert.Contains("State: CA", output.Stdout);
Assert.Contains("Country: USA", output.Stdout);
Assert.Contains("Capital: False", output.Stdout);
Assert.Contains("Population: 3900000", output.Stdout);
}
[Fact]
public void GetCollectionsTest()
{
RunGetData("retrieve-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var addSubcollectionOutput = RunGetData("add-subcollection", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added data to the Marina document in the neighborhoods subcollection in the SF document in the cities collection.", addSubcollectionOutput.Stdout);
var getCollectionsOutput = RunGetData("get-collections", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Found subcollection with ID: neighborhoods", getCollectionsOutput.Stdout);
}
// LISTEN DATA TESTS
[Fact(Skip = "https://github.com/GoogleCloudPlatform/dotnet-docs-samples/issues/1162")]
public void ListenDocumentTest()
{
RunDeleteData("delete-collection", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var listenDocumentOutput = RunListenData("listen-document", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Callback received document snapshot.", listenDocumentOutput.Stdout);
Assert.Contains("Document exists? True", listenDocumentOutput.Stdout);
Assert.Contains("Document data for SF document:", listenDocumentOutput.Stdout);
Assert.Contains("Name: San Francisco", listenDocumentOutput.Stdout);
Assert.Contains("State: CA", listenDocumentOutput.Stdout);
Assert.Contains("Country: USA", listenDocumentOutput.Stdout);
Assert.Contains("Capital: False", listenDocumentOutput.Stdout);
Assert.Contains("Population: 860000", listenDocumentOutput.Stdout);
Assert.Contains("Stopping the listener", listenDocumentOutput.Stdout);
}
[Fact(Skip = "https://github.com/GoogleCloudPlatform/dotnet-docs-samples/issues/1162")]
public void ListenMultipleTest()
{
RunDeleteData("delete-collection", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var listenMultipleOutput = RunListenData("listen-multiple", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Creating document", listenMultipleOutput.Stdout);
Assert.Contains("Callback received query snapshot.", listenMultipleOutput.Stdout);
Assert.Contains("Current cities in California:", listenMultipleOutput.Stdout);
Assert.Contains("LA", listenMultipleOutput.Stdout);
Assert.Contains("Stopping the listener", listenMultipleOutput.Stdout);
}
[Fact(Skip = "https://github.com/GoogleCloudPlatform/dotnet-docs-samples/issues/1162")]
public void ListenForChangesTest()
{
RunDeleteData("delete-collection", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var listenForChangesOutput = RunListenData("listen-for-changes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Creating document", listenForChangesOutput.Stdout);
Assert.Contains("New city: MTV", listenForChangesOutput.Stdout);
Assert.Contains("Modifying document", listenForChangesOutput.Stdout);
Assert.Contains("Modified city: MTV", listenForChangesOutput.Stdout);
Assert.Contains("Deleting document", listenForChangesOutput.Stdout);
Assert.Contains("Removed city: MTV", listenForChangesOutput.Stdout);
Assert.Contains("Stopping the listener", listenForChangesOutput.Stdout);
}
// QUERY DATA TESTS
[Fact]
public void QueryCreateExamplesTest()
{
var output = RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Added example cities data to the cities collection.", output.Stdout);
}
[Fact]
public void CreateQueryStateTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("create-query-state", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by query State=CA", output.Stdout);
Assert.Contains("Document SF returned by query State=CA", output.Stdout);
Assert.DoesNotContain("Document DC returned by query State=CA", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query State=CA", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query State=CA", output.Stdout);
}
[Fact]
public void CreateQueryCapitalTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("create-query-capital", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document DC returned by query Capital=true", output.Stdout);
Assert.Contains("Document TOK returned by query Capital=true", output.Stdout);
Assert.Contains("Document BJ returned by query Capital=true", output.Stdout);
Assert.DoesNotContain("Document SF returned by query Capital=true", output.Stdout);
Assert.DoesNotContain("Document LA returned by query Capital=true", output.Stdout);
}
[Fact]
public void SimpleQueriesTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("simple-queries", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by query State=CA", output.Stdout);
Assert.Contains("Document SF returned by query State=CA", output.Stdout);
Assert.DoesNotContain("Document DC returned by query State=CA", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query State=CA", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query State=CA", output.Stdout);
Assert.Contains("Document LA returned by query Population>1000000", output.Stdout);
Assert.Contains("Document TOK returned by query Population>1000000", output.Stdout);
Assert.Contains("Document BJ returned by query Population>1000000", output.Stdout);
Assert.DoesNotContain("Document SF returned by query Population>1000000", output.Stdout);
Assert.DoesNotContain("Document DC returned by query Population>1000000", output.Stdout);
Assert.Contains("Document SF returned by query Name>=San Francisco", output.Stdout);
Assert.Contains("Document TOK returned by query Name>=San Francisco", output.Stdout);
Assert.Contains("Document DC returned by query Name>=San Francisco", output.Stdout);
Assert.DoesNotContain("Document LA returned by query Name>=San Francisco", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query Name>=San Francisco", output.Stdout);
}
[Fact]
public void ArrayContainsQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("array-contains-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by query 'Regions array_contains west_coast'", output.Stdout);
Assert.Contains("Document SF returned by query 'Regions array_contains west_coast'", output.Stdout);
Assert.DoesNotContain("Document DC returned by query 'Regions array_contains west_coast'", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query 'Regions array_contains west_coast'", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query 'Regions array_contains west_coast'", output.Stdout);
}
[Fact]
public void ArrayContainsQueryAnyTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("array-contains-any-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document SF returned by query 'Regions array_contains_any {west_coast, east_coast}'", output.Stdout);
Assert.Contains("Document LA returned by query 'Regions array_contains_any {west_coast, east_coast}'", output.Stdout);
Assert.Contains("Document DC returned by query 'Regions array_contains_any {west_coast, east_coast}'", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query 'Regions array_contains_any {west_coast, east_coast}'", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query 'Regions array_contains west_coast'", output.Stdout);
}
[Fact]
public void InQueryWithoutArrayTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
// Expected: "SF", "LA", "DC", "TOK"
var output = RunQueryData("in-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document SF returned by query 'Country in {USA, Japan}'", output.Stdout);
Assert.Contains("Document LA returned by query 'Country in {USA, Japan}'", output.Stdout);
Assert.Contains("Document DC returned by query 'Country in {USA, Japan}'", output.Stdout);
Assert.Contains("Document TOK returned by query 'Country in {USA, Japan}'", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query 'Country in {USA, Japan}'", output.Stdout);
}
[Fact]
public void InQueryWithArrayTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
// Expected: "DC"
var output = RunQueryData("in-query-array", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document DC returned by query 'Regions in {west_coast}, {east_coast}'", output.Stdout);
Assert.DoesNotContain("Document LA returned by query 'Regions in {west_coast}, {east_coast}'", output.Stdout);
Assert.DoesNotContain("Document SF returned by query 'Regions in {west_coast}, {east_coast}'", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query 'Regions in {west_coast}, {east_coast}'", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query 'Regions in {west_coast}, {east_coast}'", output.Stdout);
}
[Fact]
public void ChainedQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("chained-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document SF returned by query State=CA and Name=San Francisco", output.Stdout);
Assert.DoesNotContain("Document LA returned by query State=CA and Name=San Francisco", output.Stdout);
Assert.DoesNotContain("Document DC returned by query State=CA and Name=San Francisco", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query State=CA and Name=San Francisco", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query State=CA and Name=San Francisco", output.Stdout);
}
[Fact(Skip = "b/137857855")]
public void CompositeIndexChainedQueryTest()
{
var manageIndexesOutput = RunManageIndexes("create-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
if (!manageIndexesOutput.Stdout.Contains("completed"))
{
var numIndexesCreatedOutput = RunManageIndexes("count-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
int numIndexesCreated = numIndexesCreatedOutput.Stdout.Split('\n').Length;
while (numIndexesCreated < 3)
{
numIndexesCreatedOutput = RunManageIndexes("count-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
numIndexesCreated = numIndexesCreatedOutput.Stdout.Split('\n').Length;
}
}
Assert.Contains("Index creation completed!", manageIndexesOutput.Stdout);
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("composite-index-chained-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document SF returned by query State=CA and Population<1000000", output.Stdout);
Assert.DoesNotContain("Document LA returned by query State=CA and Population<1000000", output.Stdout);
Assert.DoesNotContain("Document DC returned by query State=CA and Population<1000000", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query State=CA and Population<1000000", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query State=CA and Population<1000000", output.Stdout);
}
[Fact]
public void RangeQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("range-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by query CA<=State<=IN", output.Stdout);
Assert.Contains("Document SF returned by query CA<=State<=IN", output.Stdout);
Assert.DoesNotContain("Document DC returned by query CA<=State<=IN", output.Stdout);
Assert.DoesNotContain("Document TOK returned by query CA<=State<=IN", output.Stdout);
Assert.DoesNotContain("Document BJ returned by query CA<=State<=IN", output.Stdout);
}
[Fact]
public void InvalidRangeQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunQueryData("invalid-range-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
// ORDER LIMIT DATA TESTS
[Fact]
public void OrderByNameLimitQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunOrderLimitData("order-by-name-limit-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document BJ returned by order by name with limit query", output.Stdout);
Assert.Contains("Document LA returned by order by name with limit query", output.Stdout);
Assert.Contains("Document SF returned by order by name with limit query", output.Stdout);
Assert.DoesNotContain("Document DC returned by order by name with limit query", output.Stdout);
Assert.DoesNotContain("Document TOK returned by order by name with limit query", output.Stdout);
}
[Fact]
public void OrderByNameDescLimitQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunOrderLimitData("order-by-name-desc-limit-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document DC returned by order by name descending with limit query", output.Stdout);
Assert.Contains("Document TOK returned by order by name descending with limit query", output.Stdout);
Assert.Contains("Document SF returned by order by name descending with limit query", output.Stdout);
Assert.DoesNotContain("Document LA returned by order by name descending with limit query", output.Stdout);
Assert.DoesNotContain("Document BJ returned by order by name descending with limit query", output.Stdout);
}
[Fact(Skip = "b/137857855")]
public void OrderByStateAndPopulationQueryTest()
{
var manageIndexesOutput = RunManageIndexes("create-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
if (!manageIndexesOutput.Stdout.Contains("completed"))
{
var numIndexesCreatedOutput = RunManageIndexes("count-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
int numIndexesCreated = numIndexesCreatedOutput.Stdout.Split('\n').Length;
while (numIndexesCreated < 3)
{
numIndexesCreatedOutput = RunManageIndexes("count-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
numIndexesCreated = numIndexesCreatedOutput.Stdout.Split('\n').Length;
}
}
Assert.Contains("Index creation completed!", manageIndexesOutput.Stdout);
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunOrderLimitData("order-by-state-and-population-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by order by state and descending population query", output.Stdout);
Assert.Contains("Document SF returned by order by state and descending population query", output.Stdout);
Assert.Contains("Document BJ returned by order by state and descending population query", output.Stdout);
Assert.Contains("Document DC returned by order by state and descending population query", output.Stdout);
Assert.Contains("Document TOK returned by order by state and descending population query", output.Stdout);
}
[Fact]
public void WhereOrderByLimitQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunOrderLimitData("where-order-by-limit-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by where order by limit query", output.Stdout);
Assert.Contains("Document TOK returned by where order by limit query", output.Stdout);
Assert.DoesNotContain("Document SF returned by where order by limit query", output.Stdout);
Assert.DoesNotContain("Document DC returned by where order by limit query", output.Stdout);
Assert.DoesNotContain("Document BJ returned by where order by limit query", output.Stdout);
}
[Fact]
public void RangeOrderByQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunOrderLimitData("range-order-by-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by range with order by query", output.Stdout);
Assert.Contains("Document TOK returned by range with order by query", output.Stdout);
Assert.Contains("Document BJ returned by range with order by query", output.Stdout);
Assert.DoesNotContain("Document SF returned by range with order by query", output.Stdout);
Assert.DoesNotContain("Document DC returned by range with order by query", output.Stdout);
}
[Fact]
public void InvalidRangeOrderByQueryTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunOrderLimitData("invalid-range-order-by-query", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
// DATA MODEL TESTS
[Fact]
public void DocumentRefTest()
{
RunDataModel("document-ref", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
[Fact]
public void CollectionRefTest()
{
RunDataModel("collection-ref", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
[Fact]
public void DocumentPathRefTest()
{
RunDataModel("document-path-ref", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
[Fact]
public void SubcollectionRefTest()
{
RunDataModel("subcollection-ref", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
// TRANSACTIONS AND BATCHED WRITES TESTS
[Fact]
public void RunSimpleTransactionTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunTransactionsAndBatchedWrites("run-simple-transaction", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Ran a simple transaction to update the population field in the SF document in the cities collection.", output.Stdout);
}
[Fact]
public void ReturnInfoTransactionTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunTransactionsAndBatchedWrites("return-info-transaction", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Population updated successfully.", output.Stdout);
}
[Fact]
public void BatchWriteTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunTransactionsAndBatchedWrites("batch-write", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Batch write successfully completed.", output.Stdout);
}
// PAGINATE DATA TESTS
[Fact]
public void StartAtFieldQueryCursorTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunPaginateData("start-at-field-query-cursor", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document LA returned by start at population 1000000 field query cursor", output.Stdout);
Assert.Contains("Document TOK returned by start at population 1000000 field query cursor", output.Stdout);
Assert.Contains("Document BJ returned by start at population 1000000 field query cursor", output.Stdout);
Assert.DoesNotContain("Document SF returned by start at population 1000000 field query cursor", output.Stdout);
Assert.DoesNotContain("Document DC returned by start at population 1000000 field query cursor", output.Stdout);
}
[Fact]
public void EndAtFieldQueryCursorTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunPaginateData("end-at-field-query-cursor", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document DC returned by end at population 1000000 field query cursor", output.Stdout);
Assert.Contains("Document SF returned by end at population 1000000 field query cursor", output.Stdout);
Assert.DoesNotContain("Document LA returned by end at population 1000000 field query cursor", output.Stdout);
Assert.DoesNotContain("Document TOK returned by end at population 1000000 field query cursor", output.Stdout);
Assert.DoesNotContain("Document BJ returned by end at population 1000000 field query cursor", output.Stdout);
}
[Fact]
public void DocumentSnapshotCursorTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunPaginateData("document-snapshot-cursor", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.DoesNotContain("Document DC returned by query for cities with population greater than or equal to SF.", output.Stdout);
Assert.Contains("Document SF returned by query for cities with population greater than or equal to SF.", output.Stdout);
Assert.Contains("Document LA returned by query for cities with population greater than or equal to SF.", output.Stdout);
Assert.Contains("Document TOK returned by query for cities with population greater than or equal to SF.", output.Stdout);
Assert.Contains("Document BJ returned by query for cities with population greater than or equal to SF.", output.Stdout);
}
[Fact]
public void PaginatedQueryCursorTest()
{
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
var output = RunPaginateData("paginated-query-cursor", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Document TOK returned by paginated query cursor.", output.Stdout);
Assert.Contains("Document BJ returned by paginated query cursor.", output.Stdout);
Assert.DoesNotContain("Document SF returned by paginated query cursor.", output.Stdout);
Assert.DoesNotContain("Document LA returned by paginated query cursor.", output.Stdout);
Assert.DoesNotContain("Document DC returned by paginated query cursor.", output.Stdout);
}
[Fact(Skip = "b/137857855")]
public void MultipleCursorConditionsTest()
{
var manageIndexesOutput = RunManageIndexes("create-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
if (!manageIndexesOutput.Stdout.Contains("completed"))
{
var numIndexesCreatedOutput = RunManageIndexes("count-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
int numIndexesCreated = numIndexesCreatedOutput.Stdout.Split('\n').Length;
while (numIndexesCreated < 3)
{
numIndexesCreatedOutput = RunManageIndexes("count-indexes", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
numIndexesCreated = numIndexesCreatedOutput.Stdout.Split('\n').Length;
}
}
Assert.Contains("Index creation completed!", manageIndexesOutput.Stdout);
RunQueryData("query-create-examples", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
RunPaginateData("multiple-cursor-conditions", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
}
[Fact]
public void RunDistributedCounterTest()
{
var output = RunDistributedCounter("distributed-counter", Environment.GetEnvironmentVariable("FIRESTORE_PROJECT_ID"));
Assert.Contains("Distributed counter created.", output.Stdout);
Assert.Contains("Distributed counter incremented.", output.Stdout);
Assert.Contains("Total count: 1", output.Stdout);
}
}
}
| |
namespace System.Workflow.Activities
{
#region Imports
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Drawing;
using System.Diagnostics;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.Activities.Common;
#endregion
[SRDescription(SR.ListenActivityDescription)]
[ToolboxItem(typeof(ListenToolboxItem))]
[Designer(typeof(ListenDesigner), typeof(IDesigner))]
[ToolboxBitmap(typeof(ListenActivity), "Resources.Listen.png")]
[ActivityValidator(typeof(ListenValidator))]
[SRCategory(SR.Standard)]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class ListenActivity : CompositeActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs>
{
#region Constructors
public ListenActivity()
{
}
public ListenActivity(string name)
: base(name)
{
}
#endregion
#region Protected methods
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
List<ListenEventActivitySubscriber> eventActivitySubscribers = new List<ListenEventActivitySubscriber>();
this.ActivityState = eventActivitySubscribers;
//Subscribe to all EventDriven Children.
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
EventDrivenActivity eventDriven = this.EnabledActivities[i] as EventDrivenActivity;
ListenEventActivitySubscriber eventActivitySubscriber = new ListenEventActivitySubscriber(eventDriven);
eventDriven.EventActivity.Subscribe(executionContext, eventActivitySubscriber);
eventActivitySubscribers.Add(eventActivitySubscriber);
}
return ActivityExecutionStatus.Executing;
}
protected override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (this.ActivityState == null)
return ActivityExecutionStatus.Closed;
try
{
if (this.IsListenTrigerred)
{
//We need to cancel the active running branch
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
EventDrivenActivity eventDriven = this.EnabledActivities[i] as EventDrivenActivity;
if (eventDriven.ExecutionStatus == ActivityExecutionStatus.Executing)
{
executionContext.CancelActivity(eventDriven);
return ActivityExecutionStatus.Canceling;
} //If the branch is faulting let it close.
else if (eventDriven.ExecutionStatus == ActivityExecutionStatus.Faulting)
{
return ActivityExecutionStatus.Canceling;
}
}
}
else
{
//Everything is passive. Lets unsubscribe all and close.
for (int i = 0; i < this.ActivityState.Count; ++i)
{
EventDrivenActivity eventDrivenChild = this.EnabledActivities[i] as EventDrivenActivity;
ListenEventActivitySubscriber eventActivitySubscriber = this.ActivityState[i];
eventDrivenChild.EventActivity.Unsubscribe(executionContext, eventActivitySubscriber);
}
}
}
finally
{
// We null out ActivityState in the finally block to ensure that if
// eventDrivenChild.EventActivity.Unsubscribe above throws then the
// Cancel method does not get called repeatedly.
this.ActivityState = null;
}
return ActivityExecutionStatus.Closed;
}
protected override void OnClosed(IServiceProvider provider)
{
base.RemoveProperty(ListenActivity.IsListenTrigerredProperty);
base.RemoveProperty(ListenActivity.ActivityStateProperty);
}
#region Dynamic Update Methods
[NonSerialized]
private bool activeBranchRemoved = false;
protected override sealed void OnActivityChangeAdd(ActivityExecutionContext executionContext, Activity addedActivity)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (addedActivity == null)
throw new ArgumentNullException("addedActivity");
Debug.Assert(addedActivity is EventDrivenActivity, "Listen only contains EventDriven activities");
ListenActivity listen = executionContext.Activity as ListenActivity;
if (listen.ExecutionStatus == ActivityExecutionStatus.Executing && listen.ActivityState != null && !listen.IsListenTrigerred)
{
EventDrivenActivity eda = addedActivity as EventDrivenActivity;
ListenEventActivitySubscriber eventActivitySubscriber = new ListenEventActivitySubscriber(eda);
eda.EventActivity.Subscribe(executionContext, eventActivitySubscriber);
listen.ActivityState.Insert(listen.EnabledActivities.IndexOf(addedActivity), eventActivitySubscriber);
}
}
protected override sealed void OnActivityChangeRemove(ActivityExecutionContext executionContext, Activity removedActivity)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (removedActivity == null)
throw new ArgumentNullException("removedActivity");
ListenActivity listen = executionContext.Activity as ListenActivity;
if (listen.ExecutionStatus == ActivityExecutionStatus.Executing && listen.ActivityState != null && !listen.IsListenTrigerred)
{
EventDrivenActivity eda = removedActivity as EventDrivenActivity;
for (int i = 0; i < listen.ActivityState.Count; ++i)
{
ListenEventActivitySubscriber listenEventSubscriber = listen.ActivityState[i];
if (listenEventSubscriber.eventDrivenActivity.QualifiedName.Equals(eda.QualifiedName))
{
eda.EventActivity.Unsubscribe(executionContext, listenEventSubscriber);
listen.ActivityState.RemoveAt(i);
return;
}
}
}
else if (this.IsListenTrigerred && removedActivity.ExecutionStatus == ActivityExecutionStatus.Closed)
{
activeBranchRemoved = true;
}
}
protected override void OnWorkflowChangesCompleted(ActivityExecutionContext executionContext)
{
base.OnWorkflowChangesCompleted(executionContext);
if (activeBranchRemoved)
executionContext.CloseActivity();
activeBranchRemoved = false;
}
#endregion
#endregion
#region Private Implementation
#region Private Runtime State Dependency Properties
static DependencyProperty IsListenTrigerredProperty = DependencyProperty.Register("IsListenTrigerred", typeof(bool), typeof(ListenActivity), new PropertyMetadata(false));
static DependencyProperty ActivityStateProperty = DependencyProperty.Register("ActivityState", typeof(List<ListenEventActivitySubscriber>), typeof(ListenActivity));
private bool IsListenTrigerred
{
get
{
return (bool)base.GetValue(IsListenTrigerredProperty);
}
set
{
base.SetValue(IsListenTrigerredProperty, value);
}
}
private List<ListenEventActivitySubscriber> ActivityState
{
get
{
return (List<ListenEventActivitySubscriber>)base.GetValue(ActivityStateProperty);
}
set
{
if (value == null)
base.RemoveProperty(ActivityStateProperty);
else
base.SetValue(ActivityStateProperty, value);
}
}
#endregion
#region IActivityEventListener<ActivityExecutionStatusChangedEventArgs> Members
void IActivityEventListener<ActivityExecutionStatusChangedEventArgs>.OnEvent(object sender, ActivityExecutionStatusChangedEventArgs e)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (e == null)
throw new ArgumentNullException("e");
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this);
context.CloseActivity();
}
#endregion
#region Subscription Datastructures
[Serializable]
private sealed class ListenEventActivitySubscriber : IActivityEventListener<QueueEventArgs>
{
internal EventDrivenActivity eventDrivenActivity;
internal ListenEventActivitySubscriber(EventDrivenActivity eventDriven)
{
this.eventDrivenActivity = eventDriven;
}
void IActivityEventListener<QueueEventArgs>.OnEvent(object sender, QueueEventArgs e)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (e == null)
throw new ArgumentNullException("e");
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
ListenActivity parentActivity = context.Activity as ListenActivity;
if (!parentActivity.IsListenTrigerred && parentActivity.ExecutionStatus != ActivityExecutionStatus.Canceling && parentActivity.ExecutionStatus != ActivityExecutionStatus.Closed)
{
//Check whether it is still live in tree.
if (!parentActivity.EnabledActivities.Contains(eventDrivenActivity))//Activity is dynamically removed.
return;
parentActivity.IsListenTrigerred = true;
for (int i = 0; i < parentActivity.EnabledActivities.Count; ++i)
{
EventDrivenActivity eventDriven = parentActivity.EnabledActivities[i] as EventDrivenActivity;
ListenEventActivitySubscriber eventSubscriber = parentActivity.ActivityState[i];
eventDriven.EventActivity.Unsubscribe(context, eventSubscriber);
}
eventDrivenActivity.RegisterForStatusChange(Activity.ClosedEvent, parentActivity);
context.ExecuteActivity(eventDrivenActivity);
}
}
}
#endregion
#endregion
}
#region Validator
internal sealed class ListenValidator : CompositeActivityValidator
{
public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
{
ValidationErrorCollection validationErrors = new ValidationErrorCollection(base.Validate(manager, obj));
ListenActivity listen = obj as ListenActivity;
if (listen == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(ListenActivity).FullName), "obj");
// Validate number of children
if (listen.EnabledActivities.Count < 2)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ListenLessThanTwoChildren), ErrorNumbers.Error_ListenLessThanTwoChildren));
bool bNotAllEventDriven = false;
foreach (Activity activity in listen.EnabledActivities)
{
if (!(activity is EventDrivenActivity))
bNotAllEventDriven = true;
}
// validate that all child activities are event driven activities.
if (bNotAllEventDriven)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ListenNotAllEventDriven), ErrorNumbers.Error_ListenNotAllEventDriven));
return validationErrors;
}
}
#endregion
}
| |
namespace Nancy.ModelBinding
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nancy.Validation;
public static class ModuleExtensions
{
private static readonly string[] NoBlacklistedProperties = new string[0];
/// <summary>
/// Parses an array of expressions like <code>t => t.Property</code> to a list of strings containing the property names;
/// </summary>
/// <typeparam name="T">Type of the model</typeparam>
/// <param name="expressions">Expressions that tell which property should be ignored</param>
/// <returns>Array of strings containing the names of the properties.</returns>
private static string[] ParseBlacklistedPropertiesExpressionTree<T>(this IEnumerable<Expression<Func<T, object>>> expressions)
{
return expressions.Select(p => p.GetTargetMemberInfo().Name).ToArray();
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <param name="module">Current module</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <returns>Model adapter - cast to a model type to bind it</returns>
public static dynamic Bind(this INancyModule module, params string[] blacklistedProperties)
{
return module.Bind(BindingConfig.Default, blacklistedProperties);
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <returns>Model adapter - cast to a model type to bind it</returns>
public static dynamic Bind(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties)
{
return new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, null, configuration, blacklistedProperties);
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module)
{
return module.Bind();
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module, params string[] blacklistedProperties)
{
return module.Bind(blacklistedProperties);
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
return module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
}
/// <summary>
/// Bind the incoming request to a model and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <returns>Bound model instance</returns>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindAndValidate<TModel>(this INancyModule module, params string[] blacklistedProperties)
{
var model = module.Bind<TModel>(blacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to a model and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
/// <returns>Bound model instance</returns>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindAndValidate<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
var model = module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to a model and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <returns>Bound model instance</returns>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindAndValidate<TModel>(this INancyModule module)
{
var model = module.Bind<TModel>(NoBlacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration)
{
return module.Bind(configuration);
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties)
{
return module.Bind(configuration, blacklistedProperties);
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperty">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, Expression<Func<TModel, object>> blacklistedProperty)
{
return module.Bind(configuration, new [] { blacklistedProperty }.ParseBlacklistedPropertiesExpressionTree());
}
/// <summary>
/// Bind the incoming request to a model
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
/// <returns>Bound model instance</returns>
public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
return module.Bind(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
}
/// <summary>
/// Bind the incoming request to a model and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <returns>Bound model instance</returns>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties)
{
var model = module.Bind<TModel>(configuration, blacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to a model and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
/// <returns>Bound model instance</returns>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
var model = module.Bind<TModel>(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to a model and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <returns>Bound model instance</returns>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration)
{
var model = module.Bind<TModel>(configuration, NoBlacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to an existing instance
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties)
{
return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties);
}
/// <summary>
/// Bind the incoming request to an existing instance
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
}
/// <summary>
/// Bind the incoming request to an existing instance
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
public static TModel BindTo<TModel>(this INancyModule module, TModel instance)
{
return module.BindTo(instance, BindingConfig.NoOverwrite, NoBlacklistedProperties);
}
/// <summary>
/// Bind the incoming request to an existing instance and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties)
{
var model = module.BindTo(instance, blacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to an existing instance and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
var model = module.BindTo(instance, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to an existing instance and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance)
{
var model = module.BindTo(instance, NoBlacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to an existing instance
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties)
{
dynamic adapter =
new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, instance, configuration, blacklistedProperties);
return adapter;
}
/// <summary>
/// Bind the incoming request to an existing instance
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example>
public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
return module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
}
/// <summary>
/// Bind the incoming request to an existing instance
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration)
{
return module.BindTo(instance, configuration, NoBlacklistedProperties);
}
/// <summary>
/// Bind the incoming request to an existing instance and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Property names to blacklist from binding</param>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties)
{
var model = module.BindTo(instance, configuration, blacklistedProperties);
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to an existing instance and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
/// <example>this.BindToAndValidate(person, config, p => p.Name, p => p.Age)</example>
public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)
{
var model = module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());
module.Validate(model);
return model;
}
/// <summary>
/// Bind the incoming request to an existing instance and validate
/// </summary>
/// <typeparam name="TModel">Model type</typeparam>
/// <param name="module">Current module</param>
/// <param name="instance">The class instance to bind properties to</param>
/// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
/// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>
public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration)
{
var model = module.BindTo(instance, configuration, NoBlacklistedProperties);
module.Validate(model);
return model;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
namespace Silphid.Extensions
{
public static class IEnumerableExtensions
{
public static TTarget SelectFirstOrDefault<TSource, TTarget>(this IEnumerable<TSource> source,
Func<TSource, bool> predicate,
Func<TSource, TTarget> selector,
TTarget defaultValue = default(TTarget))
{
foreach (var element in source)
if (predicate(element))
return selector(element);
return defaultValue;
}
public static TTarget SelectLastOrDefault<TSource, TTarget>(this IEnumerable<TSource> source,
Func<TSource, bool> predicate,
Func<TSource, TTarget> selector,
TTarget defaultValue = default(TTarget))
{
var value = default(TSource);
var isFound = false;
foreach (var element in source)
if (predicate(element))
{
value = element;
isFound = true;
}
return isFound
? selector(value)
: defaultValue;
}
public static T FirstOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue)
{
foreach (var element in source)
if (predicate(element))
return element;
return defaultValue;
}
public static T LastOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue)
{
var value = defaultValue;
foreach (var element in source)
if (predicate(element))
value = element;
return value;
}
public static T FirstNotNullOrDefault<T>(this IEnumerable<T> This) =>
This.FirstOrDefault(x => x != null);
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> This) =>
This.Where(x => x != null);
public static void DisposeAll<T>(this IEnumerable<T> This) where T : IDisposable
{
This.ForEach(x => x.Dispose());
}
public static bool AllTrue(this IEnumerable<bool> This) =>
This.All(x => x);
public static bool AllFalse(this IEnumerable<bool> This) =>
This.All(x => !x);
public static bool AnyTrue(this IEnumerable<bool> This) =>
This.Any(x => x);
public static bool AnyFalse(this IEnumerable<bool> This) =>
This.Any(x => !x);
public static IEnumerable<bool> WhereTrue(this IEnumerable<bool> This) =>
This.Where(x => x);
public static IEnumerable<bool> WhereFalse(this IEnumerable<bool> This) =>
This.Where(x => !x);
public static IEnumerable<IEnumerable<T>> Paged<T>(this IEnumerable<T> source, int itemsPerPage)
{
var list = source.ToList();
int index = 0;
while (index < list.Count)
{
int count = Math.Min(itemsPerPage, list.Count - index);
var array = new T[count];
list.CopyTo(index, array, 0, count);
index += count;
yield return array;
}
}
public static void Shuffle<T>(this IList<T> list)
{
var random = new Random();
for (int i = 0; i < list.Count; i++)
{
// Permute with random item
int j = random.Next(list.Count);
var temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
/// <summary>
/// Returns element for which selector function returns the minimum value.
/// </summary>
public static T WithMin<T, U>(this IEnumerable<T> source, Func<T, IComparable<U>> selector)
{
var minElement = default(T);
var minValue = default(IComparable<U>);
foreach (var element in source)
{
var value = selector(element);
if (Equals(minElement, default(T)) || value.CompareTo((U) minValue) < 0)
{
minValue = value;
minElement = element;
}
}
return minElement;
}
public static T WithMax<T, U>(this IEnumerable<T> source, Func<T, IComparable<U>> selector)
{
var maxElement = default(T);
var maxValue = default(IComparable<U>);
foreach (var element in source)
{
var value = selector(element);
if (Equals(maxElement, default(T)) || value.CompareTo((U) maxValue) > 0)
{
maxValue = value;
maxElement = element;
}
}
return maxElement;
}
public static string JoinAsString<T>(this IEnumerable<T> source, string delimiter = null)
{
if (source == null)
return string.Empty;
var builder = new StringBuilder();
bool needsDelimiter = false;
foreach (var t in source.WhereNotNull())
{
if (delimiter != null && needsDelimiter)
builder.Append(delimiter);
builder.Append(t);
needsDelimiter = true;
}
return builder.ToString();
}
public static string JoinAsString<T>(this IEnumerable<T> source, string prefix, string suffix, bool omitLastSuffix = false)
{
if (source == null)
return string.Empty;
var builder = new StringBuilder();
bool isFirst = true;
foreach (var t in source.WhereNotNull())
{
if (!isFirst)
builder.Append(suffix);
builder.Append(prefix);
builder.Append(t);
isFirst = false;
}
if (!omitLastSuffix && !isFirst)
builder.Append(suffix);
return builder.ToString();
}
public static bool OrderedEquals<T>(this IEnumerable<T> source, IEnumerable<T> other)
{
// Compare lengths (list-specific optimization)
if (source is IList<T> && other is IList<T>)
{
int sourceCount = ((IList<T>) source).Count;
int otherCount = ((IList<T>) other).Count;
if (sourceCount != otherCount)
return false;
}
// Compare items one-by-one
using (var sourceEnumerator = source.GetEnumerator())
using (var otherEnumerator = other.GetEnumerator())
{
bool hasSource, hasOther;
while ((hasSource = sourceEnumerator.MoveNext()) & (hasOther = otherEnumerator.MoveNext()))
{
if (!Equals(sourceEnumerator.Current, otherEnumerator.Current))
return false;
}
// Any item left in either collection?
if (hasSource || hasOther)
{
return false;
}
}
return true;
}
#if !UNITY_2018_1_OR_NEWER
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T obj)
{
T[] array = {obj};
return array.Concat(source);
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T obj)
{
T[] array = {obj};
return source.Concat(array);
}
#endif
public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int count)
{
source = source as T[] ?? source as IList<T> ?? source.ToList();
for (int i = 0; i < count; i++)
foreach (var s in source)
yield return s;
}
public static IEnumerable<T> Except<T>(this IEnumerable<T> source, T obj)
{
return source.Where(s => !s.Equals(obj));
}
public static List<T> Shuffled<T>(this IEnumerable<T> source)
{
var list = source.ToList();
list.Shuffle();
return list;
}
public static int FirstIndex<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
int index = 0;
foreach (var item in source)
{
if (predicate(item))
return index;
index++;
}
return -1;
}
public static int FirstIndex<T>(this IReadOnlyList<T> source, int startIndex, Predicate<T> predicate)
{
for (int i = startIndex; i < source.Count; i++)
if (predicate(source[i]))
return i;
return -1;
}
public static int LastIndex<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
var list = source.ToList();
list.Reverse();
int index = list.Count - 1;
foreach (var item in list)
{
if (predicate(item))
{
return index;
}
index--;
}
return -1;
}
public static int? IndexOf<T>(this IEnumerable<T> This, T item)
{
var index = 0;
foreach (var candidate in This)
{
if (candidate.Equals(item))
return index;
index++;
}
return null;
}
public static int? IndexOf<T>(this IEnumerable<T> This, Func<T, bool> predicate)
{
var index = 0;
foreach (var candidate in This)
{
if (predicate(candidate))
return index;
index++;
}
return null;
}
public static T GetAtOrDefault<T>(this IEnumerable<T> This, int? index, T defaultValue = default(T))
{
if (index == null || index < 0)
return defaultValue;
var list = This as IList<T>;
if (list != null)
return index < list.Count
? list[index.Value]
: defaultValue;
var i = 0;
foreach (var item in This)
if (i++ == index)
return item;
return defaultValue;
}
/// <summary>
/// Compares objects based on their value modulated through custom function.
/// </summary>
private class CustomFunctionComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, object> _customFunc;
public CustomFunctionComparer(Func<T, object> customFunc)
{
_customFunc = customFunc;
}
public bool Equals(T x, T y)
{
return Equals(_customFunc.Invoke(x), _customFunc.Invoke(y));
}
public int GetHashCode(T obj)
{
return _customFunc.Invoke(obj)
.GetHashCode();
}
}
/// <summary>
/// Variant of the Distinct() extension method allowing to specify a
/// function to determine distinctive criteria for each item.
/// </summary>
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source, Func<T, object> comparisonValueFunc)
{
return source.Distinct(new CustomFunctionComparer<T>(comparisonValueFunc));
}
/// <summary>
/// Invokes action on each item of source.
/// </summary>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
action(item);
}
/// <summary>
/// Invokes action on each item of source, also passing in the index of item within collection.
/// </summary>
public static void ForEach<T>(this IEnumerable<T> source, Action<int, T> action)
{
int index = 0;
foreach (var item in source)
{
action(index++, item);
}
}
/// <summary>
/// Invokes action on items of source as they are iterated through downstream.
/// </summary>
public static IEnumerable<T> Do<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
yield return item;
}
}
public static T SelectRandom<T>(this IEnumerable<T> source)
{
var random = new Random();
var list = source as IList<T> ?? source.ToList();
var index = random.Next(0, list.Count);
if (index < list.Count)
return list[index];
return default(T);
}
[Pure]
public static IEnumerable<TR> SelectNotNull<T, TR>(this IEnumerable<T> This, Func<T, TR> selector) =>
This.Select(selector)
.WhereNotNull();
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Internal;
namespace System.Management.Automation.Tracing
{
/// <summary>
/// ETW logging API.
/// </summary>
internal static class PSEtwLog
{
#if UNIX
private static readonly PSSysLogProvider provider;
#else
private static readonly PSEtwLogProvider provider;
#endif
/// <summary>
/// Class constructor.
/// </summary>
static PSEtwLog()
{
#if UNIX
provider = new PSSysLogProvider();
#else
provider = new PSEtwLogProvider();
#endif
}
internal static void LogConsoleStartup()
{
Guid activityId = EtwActivity.GetActivityId();
if (activityId == Guid.Empty)
{
EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
}
PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart,
PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);
}
/// <summary>
/// Provider interface function for logging health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="eventId"></param>
/// <param name="exception"></param>
/// <param name="additionalInfo"></param>
internal static void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<string, string> additionalInfo)
{
provider.LogEngineHealthEvent(logContext, eventId, exception, additionalInfo);
}
/// <summary>
/// Provider interface function for logging engine lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="newState"></param>
/// <param name="previousState"></param>
internal static void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState)
{
provider.LogEngineLifecycleEvent(logContext, newState, previousState);
}
/// <summary>
/// Provider interface function for logging command health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="exception"></param>
internal static void LogCommandHealthEvent(LogContext logContext, Exception exception)
{
provider.LogCommandHealthEvent(logContext, exception);
}
/// <summary>
/// Provider interface function for logging command lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="newState"></param>
internal static void LogCommandLifecycleEvent(LogContext logContext, CommandState newState)
{
provider.LogCommandLifecycleEvent(() => logContext, newState);
}
/// <summary>
/// Provider interface function for logging pipeline execution detail.
/// </summary>
/// <param name="logContext"></param>
/// <param name="pipelineExecutionDetail"></param>
internal static void LogPipelineExecutionDetailEvent(LogContext logContext, List<string> pipelineExecutionDetail)
{
provider.LogPipelineExecutionDetailEvent(logContext, pipelineExecutionDetail);
}
/// <summary>
/// Provider interface function for logging provider health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="exception"></param>
internal static void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
{
provider.LogProviderHealthEvent(logContext, providerName, exception);
}
/// <summary>
/// Provider interface function for logging provider lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="newState"></param>
internal static void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
{
provider.LogProviderLifecycleEvent(logContext, providerName, newState);
}
/// <summary>
/// Provider interface function for logging settings event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="variableName"></param>
/// <param name="value"></param>
/// <param name="previousValue"></param>
internal static void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue)
{
provider.LogSettingsEvent(logContext, variableName, value, previousValue);
}
/// <summary>
/// Logs information to the operational channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args);
}
/// <summary>
/// Logs information to the operational channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args);
}
/// <summary>
/// Logs Verbose to the operational channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args);
}
/// <summary>
/// Logs error message to the analytic channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args);
}
/// <summary>
/// Logs warning message to the analytic channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args);
}
/// <summary>
/// Logs remoting fragment data to verbose channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="objectId"></param>
/// <param name="fragmentId"></param>
/// <param name="isStartFragment"></param>
/// <param name="isEndFragment"></param>
/// <param name="fragmentLength"></param>
/// <param name="fragmentData"></param>
internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword,
Int64 objectId,
Int64 fragmentId,
int isStartFragment,
int isEndFragment,
UInt32 fragmentLength,
PSETWBinaryBlob fragmentData)
{
if (provider.IsEnabled(PSLevel.Verbose, keyword))
{
string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length);
payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", string.Empty));
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword,
objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength,
payLoadData);
}
}
/// <summary>
/// Logs verbose message to the analytic channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args);
}
/// <summary>
/// Logs informational message to the analytic channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args);
}
/// <summary>
/// Logs error message to operation channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args);
}
/// <summary>
/// Logs error message to the operational channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="logContext"></param>
/// <param name="payLoad"></param>
internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad);
}
internal static void SetActivityIdForCurrentThread(Guid newActivityId)
{
provider.SetActivityIdForCurrentThread(newActivityId);
}
internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId,
PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task)
{
// set the new activity id
provider.SetActivityIdForCurrentThread(newActivityId);
// Once the activity id is set, write the transfer event
WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task);
}
/// <summary>
/// Writes a transfer event mapping current activity id
/// with a related activity id
/// This function writes a transfer event for both the
/// operational and analytic channels.
/// </summary>
/// <param name="relatedActivityId"></param>
/// <param name="eventForOperationalChannel"></param>
/// <param name="eventForAnalyticChannel"></param>
/// <param name="keyword"></param>
/// <param name="task"></param>
internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel,
PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task)
{
provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task,
PSKeyword.UseAlwaysOperational);
provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task,
PSKeyword.UseAlwaysAnalytic);
}
/// <summary>
/// Writes a transfer event.
/// </summary>
/// <param name="parentActivityId"></param>
internal static void WriteTransferEvent(Guid parentActivityId)
{
provider.WriteTransferEvent(parentActivityId);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
/// ProgressNode is an augmentation of the ProgressRecord type that adds extra fields for the purposes of tracking
/// outstanding activities received by the host, and rendering them in the console.
/// </summary>
internal
class
ProgressNode : ProgressRecord
{
/// <summary>
/// Indicates the various layouts for rendering a particular node. Each style is progressively less terse.
/// </summary>
internal
enum
RenderStyle
{
Invisible = 0,
Minimal = 1,
Compact = 2,
/// <summary>
/// Allocate only one line for displaying the StatusDescription or the CurrentOperation,
/// truncate the rest if the StatusDescription or CurrentOperation doesn't fit in one line.
/// </summary>
Full = 3,
/// <summary>
/// The node will be displayed the same as Full, plus, the whole StatusDescription and CurrentOperation will be displayed (in multiple lines if needed).
/// </summary>
FullPlus = 4,
};
/// <summary>
/// Constructs an instance from a ProgressRecord.
/// </summary>
internal
ProgressNode(Int64 sourceId, ProgressRecord record)
:
base(record.ActivityId, record.Activity, record.StatusDescription)
{
Dbg.Assert(record.RecordType == ProgressRecordType.Processing, "should only create node for Processing records");
this.ParentActivityId = record.ParentActivityId;
this.CurrentOperation = record.CurrentOperation;
this.PercentComplete = Math.Min(record.PercentComplete, 100);
this.SecondsRemaining = record.SecondsRemaining;
this.RecordType = record.RecordType;
this.Style = RenderStyle.FullPlus;
this.SourceId = sourceId;
}
/// <summary>
/// Renders a single progress node as strings of text according to that node's style. The text is appended to the
/// supplied list of strings.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
internal
void
Render(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
Dbg.Assert(strCollection != null, "strCollection should not be null");
Dbg.Assert(indentation >= 0, "indentation is negative");
Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records");
switch (Style)
{
case RenderStyle.FullPlus:
RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: true);
break;
case RenderStyle.Full:
RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: false);
break;
case RenderStyle.Compact:
RenderCompact(strCollection, indentation, maxWidth, rawUI);
break;
case RenderStyle.Minimal:
RenderMinimal(strCollection, indentation, maxWidth, rawUI);
break;
case RenderStyle.Invisible:
// do nothing
break;
default:
Dbg.Assert(false, "unrecognized RenderStyle value");
break;
}
}
/// <summary>
/// Renders a node in the "Full" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
/// <param name="isFullPlus">
/// Indicate if the full StatusDescription and CurrentOperation should be displayed.
/// </param>
private
void
RenderFull(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI, bool isFullPlus)
{
string indent = StringUtil.Padding(indentation);
// First line: the activity
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI, StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth));
indentation += 3;
indent = StringUtil.Padding(indentation);
// Second line: the status description
RenderFullDescription(this.StatusDescription, indent, maxWidth, rawUI, strCollection, isFullPlus);
// Third line: the percentage thermometer. The size of this is proportional to the width we're allowed
// to consume. -2 for the whitespace, -2 again for the brackets around thermo, -5 to not be too big
if (PercentComplete >= 0)
{
int thermoWidth = Math.Max(3, maxWidth - indentation - 2 - 2 - 5);
int mercuryWidth = 0;
mercuryWidth = PercentComplete * thermoWidth / 100;
if (PercentComplete < 100 && mercuryWidth == thermoWidth)
{
// back off a tad unless we're totally complete to prevent the appearance of completion before
// the fact.
--mercuryWidth;
}
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(
" {0}[{1}{2}] ",
indent,
new string('o', mercuryWidth),
StringUtil.Padding(thermoWidth - mercuryWidth)),
maxWidth));
}
// Fourth line: the seconds remaining
if (SecondsRemaining >= 0)
{
TimeSpan span = new TimeSpan(0, 0, this.SecondsRemaining);
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
" "
+ StringUtil.Format(
ProgressNodeStrings.SecondsRemaining,
indent,
span)
+ " ",
maxWidth));
}
// Fifth and Sixth lines: The current operation
if (!string.IsNullOrEmpty(CurrentOperation))
{
strCollection.Add(" ");
RenderFullDescription(this.CurrentOperation, indent, maxWidth, rawUI, strCollection, isFullPlus);
}
}
private static void RenderFullDescription(string description, string indent, int maxWidth, PSHostRawUserInterface rawUi, ArrayList strCollection, bool isFullPlus)
{
string oldDescription = StringUtil.Format(" {0}{1} ", indent, description);
string newDescription;
do
{
newDescription = StringUtil.TruncateToBufferCellWidth(rawUi, oldDescription, maxWidth);
strCollection.Add(newDescription);
if (oldDescription.Length == newDescription.Length)
{
break;
}
else
{
oldDescription = StringUtil.Format(" {0}{1}", indent, oldDescription.Substring(newDescription.Length));
}
} while (isFullPlus);
}
/// <summary>
/// Renders a node in the "Compact" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
private
void
RenderCompact(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
string indent = StringUtil.Padding(indentation);
// First line: the activity
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth));
indentation += 3;
indent = StringUtil.Padding(indentation);
// Second line: the status description with percentage and time remaining, if applicable.
string percent = string.Empty;
if (PercentComplete >= 0)
{
percent = StringUtil.Format("{0}% ", PercentComplete);
}
string secRemain = string.Empty;
if (SecondsRemaining >= 0)
{
TimeSpan span = new TimeSpan(0, 0, SecondsRemaining);
secRemain = span.ToString() + " ";
}
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(
" {0}{1}{2}{3} ",
indent,
percent,
secRemain,
StatusDescription),
maxWidth));
// Third line: The current operation
if (!string.IsNullOrEmpty(CurrentOperation))
{
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(" {0}{1} ", indent, this.CurrentOperation), maxWidth));
}
}
/// <summary>
/// Renders a node in the "Minimal" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
private
void
RenderMinimal(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
string indent = StringUtil.Padding(indentation);
// First line: Everything mushed into one line
string percent = string.Empty;
if (PercentComplete >= 0)
{
percent = StringUtil.Format("{0}% ", PercentComplete);
}
string secRemain = string.Empty;
if (SecondsRemaining >= 0)
{
TimeSpan span = new TimeSpan(0, 0, SecondsRemaining);
secRemain = span.ToString() + " ";
}
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(
" {0}{1} {2}{3}{4} ",
indent,
Activity,
percent,
secRemain,
StatusDescription),
maxWidth));
}
/// <summary>
/// The nodes that have this node as their parent.
/// </summary>
internal
ArrayList
Children;
/// <summary>
/// The "age" of the node. A node's age is incremented by PendingProgress.Update each time a new ProgressRecord is
/// received by the host. A node's age is reset when a corresponding ProgressRecord is received. Thus, the age of
/// a node reflects the number of ProgressRecord that have been received since the node was last updated.
///
/// The age is used by PendingProgress.Render to determine which nodes should be rendered on the display, and how. As the
/// display has finite size, it may be possible to have many more outstanding progress activities than will fit in that
/// space. The rendering of nodes can be progressively "compressed" into a more terse format, or not rendered at all in
/// order to fit as many nodes as possible in the available space. The oldest nodes are compressed or skipped first.
/// </summary>
internal
int
Age;
/// <summary>
/// The style in which this node should be rendered.
/// </summary>
internal
RenderStyle
Style = RenderStyle.FullPlus;
/// <summary>
/// Identifies the source of the progress record.
/// </summary>
internal
Int64
SourceId;
/// <summary>
/// The number of vertical BufferCells that are required to render the node in its current style.
/// </summary>
/// <value></value>
internal int LinesRequiredMethod(PSHostRawUserInterface rawUi, int maxWidth)
{
Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records");
switch (Style)
{
case RenderStyle.FullPlus:
return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: true);
case RenderStyle.Full:
return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: false);
case RenderStyle.Compact:
return LinesRequiredInCompactStyle;
case RenderStyle.Minimal:
return 1;
case RenderStyle.Invisible:
return 0;
default:
Dbg.Assert(false, "Unknown RenderStyle value");
break;
}
return 0;
}
/// <summary>
/// The number of vertical BufferCells that are required to render the node in the Full style.
/// </summary>
/// <value></value>
private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int maxWidth, bool isFullPlus)
{
// Since the fields of this instance could have been changed, we compute this on-the-fly.
// NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to
// word-wrap text fields, then this calculation will need updating.
// Start with 1 for the Activity
int lines = 1;
// Use 5 spaces as the heuristic indent. 5 spaces stand for the indent for the CurrentOperation of the first-level child node
var indent = StringUtil.Padding(5);
var temp = new ArrayList();
if (isFullPlus)
{
temp.Clear();
RenderFullDescription(StatusDescription, indent, maxWidth, rawUi, temp, isFullPlus: true);
lines += temp.Count;
}
else
{
// 1 for the Status
lines++;
}
if (PercentComplete >= 0)
{
++lines;
}
if (SecondsRemaining >= 0)
{
++lines;
}
if (!string.IsNullOrEmpty(CurrentOperation))
{
if (isFullPlus)
{
lines += 1;
temp.Clear();
RenderFullDescription(CurrentOperation, indent, maxWidth, rawUi, temp, isFullPlus: true);
lines += temp.Count;
}
else
{
lines += 2;
}
}
return lines;
}
/// <summary>
/// The number of vertical BufferCells that are required to render the node in the Compact style.
/// </summary>
/// <value></value>
private
int
LinesRequiredInCompactStyle
{
get
{
// Since the fields of this instance could have been changed, we compute this on-the-fly.
// NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to
// word-wrap text fields, then this calculation will need updating.
// Start with 1 for the Activity, and 1 for the Status.
int lines = 2;
if (!string.IsNullOrEmpty(CurrentOperation))
{
++lines;
}
return lines;
}
}
}
} // namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using FT = MS.Internal.Xml.XPath.Function.FunctionType;
namespace MS.Internal.Xml.XPath
{
internal sealed class QueryBuilder
{
// Note: Up->Down, Down->Up:
// For operators order is normal: 1 + 2 --> Operator+(1, 2)
// For paths order is reversed: a/b -> ChildQuery_B(input: ChildQuery_A(input: ContextQuery()))
// Input flags. We pass them Up->Down.
// Using them upper query set states which controls how inner query will be built.
enum Flags
{
None = 0x00,
SmartDesc = 0x01,
PosFilter = 0x02, // Node has this flag set when it has position predicate applied to it
Filter = 0x04, // Subtree we compiling will be filtered. i.e. Flag not set on rightmost filter.
}
// Output props. We return them Down->Up.
// These are properties of Query tree we have built already.
// These properties are closely related to QueryProps exposed by Query node itself.
// They have the following difference:
// QueryProps describe property of node they are (belong like Reverse)
// these Props describe accumulated properties of the tree (like nonFlat)
enum Props
{
None = 0x00,
PosFilter = 0x01, // This filter or inner filter was positional: foo[1] or foo[1][true()]
HasPosition = 0x02, // Expression may ask position() of the context
HasLast = 0x04, // Expression may ask last() of the context
NonFlat = 0x08, // Some nodes may be descendent of others
}
// comment are approximate. This is my best understanding:
private string _query;
private bool _allowVar;
private bool _allowKey;
private bool _allowCurrent;
private bool _needContext;
private BaseAxisQuery _firstInput; // Input of the leftmost predicate. Set by leftmost predicate, used in rightmost one
private void Reset()
{
_parseDepth = 0;
_needContext = false;
}
private Query ProcessAxis(Axis root, Flags flags, out Props props)
{
Query result = null;
if (root.Prefix.Length > 0)
{
_needContext = true;
}
_firstInput = null;
Query qyInput;
{
if (root.Input != null)
{
Flags inputFlags = Flags.None;
if ((flags & Flags.PosFilter) == 0)
{
Axis input = root.Input as Axis;
if (input != null)
{
if (
root.TypeOfAxis == Axis.AxisType.Child &&
input.TypeOfAxis == Axis.AxisType.DescendantOrSelf && input.NodeType == XPathNodeType.All
)
{
Query qyGrandInput;
if (input.Input != null)
{
qyGrandInput = ProcessNode(input.Input, Flags.SmartDesc, out props);
}
else
{
qyGrandInput = new ContextQuery();
props = Props.None;
}
result = new DescendantQuery(qyGrandInput, root.Name, root.Prefix, root.NodeType, false, input.AbbrAxis);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
props |= Props.NonFlat;
return result;
}
}
if (root.TypeOfAxis == Axis.AxisType.Descendant || root.TypeOfAxis == Axis.AxisType.DescendantOrSelf)
{
inputFlags |= Flags.SmartDesc;
}
}
qyInput = ProcessNode(root.Input, inputFlags, out props);
}
else
{
qyInput = new ContextQuery();
props = Props.None;
}
}
switch (root.TypeOfAxis)
{
case Axis.AxisType.Ancestor:
result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, false);
props |= Props.NonFlat;
break;
case Axis.AxisType.AncestorOrSelf:
result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, true);
props |= Props.NonFlat;
break;
case Axis.AxisType.Child:
if ((props & Props.NonFlat) != 0)
{
result = new CacheChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
else
{
result = new ChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
break;
case Axis.AxisType.Parent:
result = new ParentQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Descendant:
if ((flags & Flags.SmartDesc) != 0)
{
result = new DescendantOverDescendantQuery(qyInput, false, root.Name, root.Prefix, root.NodeType, /*abbrAxis:*/false);
}
else
{
result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, false, /*abbrAxis:*/false);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
}
props |= Props.NonFlat;
break;
case Axis.AxisType.DescendantOrSelf:
if ((flags & Flags.SmartDesc) != 0)
{
result = new DescendantOverDescendantQuery(qyInput, true, root.Name, root.Prefix, root.NodeType, root.AbbrAxis);
}
else
{
result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, true, root.AbbrAxis);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
}
props |= Props.NonFlat;
break;
case Axis.AxisType.Preceding:
result = new PrecedingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
props |= Props.NonFlat;
break;
case Axis.AxisType.Following:
result = new FollowingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
props |= Props.NonFlat;
break;
case Axis.AxisType.FollowingSibling:
result = new FollSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
break;
case Axis.AxisType.PrecedingSibling:
result = new PreSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Attribute:
result = new AttributeQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Self:
result = new XPathSelfQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Namespace:
if ((root.NodeType == XPathNodeType.All || root.NodeType == XPathNodeType.Element || root.NodeType == XPathNodeType.Attribute) && root.Prefix.Length == 0)
{
result = new NamespaceQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
else
{
result = new EmptyQuery();
}
break;
default:
throw XPathException.Create(SR.Xp_NotSupported, _query);
}
return result;
}
private static bool CanBeNumber(Query q)
{
return (
q.StaticType == XPathResultType.Any ||
q.StaticType == XPathResultType.Number
);
}
private Query ProcessFilter(Filter root, Flags flags, out Props props)
{
bool first = ((flags & Flags.Filter) == 0);
Props propsCond;
Query cond = ProcessNode(root.Condition, Flags.None, out propsCond);
if (
CanBeNumber(cond) ||
(propsCond & (Props.HasPosition | Props.HasLast)) != 0
)
{
propsCond |= Props.HasPosition;
flags |= Flags.PosFilter;
}
// We don't want DescendantOverDescendant pattern to be recognized here (in case descendent::foo[expr]/descendant::bar)
// So we clean this flag here:
flags &= ~Flags.SmartDesc;
// ToDo: Instead it would be nice to wrap descendent::foo[expr] into special query that will flatten it -- i.e.
// remove all nodes that are descendant of other nodes. This is very easy because for sorted nodesets all children
// follow its parent. One step caching. This can be easily done by rightmost DescendantQuery itself.
// Interesting note! Can we guarantee that DescendantOverDescendant returns flat nodeset? This definitely true if it's input is flat.
Query qyInput = ProcessNode(root.Input, flags | Flags.Filter, out props);
if (root.Input.Type != AstNode.AstType.Filter)
{
// Props.PosFilter is for nested filters only.
// We clean it here to avoid cleaning it in all other ast nodes.
props &= ~Props.PosFilter;
}
if ((propsCond & Props.HasPosition) != 0)
{
// this condition is positional rightmost filter should be aware of this.
props |= Props.PosFilter;
}
/*merging predicates*/
{
FilterQuery qyFilter = qyInput as FilterQuery;
if (qyFilter != null && (propsCond & Props.HasPosition) == 0 && qyFilter.Condition.StaticType != XPathResultType.Any)
{
Query prevCond = qyFilter.Condition;
if (prevCond.StaticType == XPathResultType.Number)
{
prevCond = new LogicalExpr(Operator.Op.EQ, new NodeFunctions(FT.FuncPosition, null), prevCond);
}
cond = new BooleanExpr(Operator.Op.AND, prevCond, cond);
qyInput = qyFilter.qyInput;
}
}
if ((props & Props.PosFilter) != 0 && qyInput is DocumentOrderQuery)
{
qyInput = ((DocumentOrderQuery)qyInput).input;
}
if (_firstInput == null)
{
_firstInput = qyInput as BaseAxisQuery;
}
bool merge = (qyInput.Properties & QueryProps.Merge) != 0;
bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0;
if ((propsCond & Props.HasPosition) != 0)
{
if (reverse)
{
qyInput = new ReversePositionQuery(qyInput);
}
else if ((propsCond & Props.HasLast) != 0)
{
qyInput = new ForwardPositionQuery(qyInput);
}
}
if (first && _firstInput != null)
{
if (merge && (props & Props.PosFilter) != 0)
{
qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/false);
Query parent = _firstInput.qyInput;
if (!(parent is ContextQuery))
{ // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ?
_firstInput.qyInput = new ContextQuery();
_firstInput = null;
return new MergeFilterQuery(parent, qyInput);
}
_firstInput = null;
return qyInput;
}
_firstInput = null;
}
return new FilterQuery(qyInput, cond, /*noPosition:*/(propsCond & Props.HasPosition) == 0);
}
private Query ProcessOperator(Operator root, out Props props)
{
Props props1, props2;
Query op1 = ProcessNode(root.Operand1, Flags.None, out props1);
Query op2 = ProcessNode(root.Operand2, Flags.None, out props2);
props = props1 | props2;
switch (root.OperatorType)
{
case Operator.Op.PLUS:
case Operator.Op.MINUS:
case Operator.Op.MUL:
case Operator.Op.MOD:
case Operator.Op.DIV:
return new NumericExpr(root.OperatorType, op1, op2);
case Operator.Op.LT:
case Operator.Op.GT:
case Operator.Op.LE:
case Operator.Op.GE:
case Operator.Op.EQ:
case Operator.Op.NE:
return new LogicalExpr(root.OperatorType, op1, op2);
case Operator.Op.OR:
case Operator.Op.AND:
return new BooleanExpr(root.OperatorType, op1, op2);
case Operator.Op.UNION:
props |= Props.NonFlat;
return new UnionExpr(op1, op2);
default: return null;
}
}
private Query ProcessVariable(Variable root)
{
_needContext = true;
if (!_allowVar)
{
throw XPathException.Create(SR.Xp_InvalidKeyPattern, _query);
}
return new VariableQuery(root.Localname, root.Prefix);
}
private Query ProcessFunction(Function root, out Props props)
{
props = Props.None;
Query qy = null;
switch (root.TypeOfFunction)
{
case FT.FuncLast:
qy = new NodeFunctions(root.TypeOfFunction, null);
props |= Props.HasLast;
return qy;
case FT.FuncPosition:
qy = new NodeFunctions(root.TypeOfFunction, null);
props |= Props.HasPosition;
return qy;
case FT.FuncCount:
return new NodeFunctions(FT.FuncCount,
ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)
);
case FT.FuncID:
qy = new IDQuery(ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props));
props |= Props.NonFlat;
return qy;
case FT.FuncLocalName:
case FT.FuncNameSpaceUri:
case FT.FuncName:
if (root.ArgumentList != null && root.ArgumentList.Count > 0)
{
return new NodeFunctions(root.TypeOfFunction,
ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)
);
}
else
{
return new NodeFunctions(root.TypeOfFunction, null);
}
case FT.FuncString:
case FT.FuncConcat:
case FT.FuncStartsWith:
case FT.FuncContains:
case FT.FuncSubstringBefore:
case FT.FuncSubstringAfter:
case FT.FuncSubstring:
case FT.FuncStringLength:
case FT.FuncNormalize:
case FT.FuncTranslate:
return new StringFunctions(root.TypeOfFunction, ProcessArguments(root.ArgumentList, out props));
case FT.FuncNumber:
case FT.FuncSum:
case FT.FuncFloor:
case FT.FuncCeiling:
case FT.FuncRound:
if (root.ArgumentList != null && root.ArgumentList.Count > 0)
{
return new NumberFunctions(root.TypeOfFunction,
ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props)
);
}
else
{
return new NumberFunctions(Function.FunctionType.FuncNumber, null);
}
case FT.FuncTrue:
case FT.FuncFalse:
return new BooleanFunctions(root.TypeOfFunction, null);
case FT.FuncNot:
case FT.FuncLang:
case FT.FuncBoolean:
return new BooleanFunctions(root.TypeOfFunction,
ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props)
);
case FT.FuncUserDefined:
_needContext = true;
if (!_allowCurrent && root.Name == "current" && root.Prefix.Length == 0)
{
throw XPathException.Create(SR.Xp_CurrentNotAllowed);
}
if (!_allowKey && root.Name == "key" && root.Prefix.Length == 0)
{
throw XPathException.Create(SR.Xp_InvalidKeyPattern, _query);
}
qy = new FunctionQuery(root.Prefix, root.Name, ProcessArguments(root.ArgumentList, out props));
props |= Props.NonFlat;
return qy;
default:
throw XPathException.Create(SR.Xp_NotSupported, _query);
}
}
List<Query> ProcessArguments(List<AstNode> args, out Props props)
{
int numArgs = args != null ? args.Count : 0;
List<Query> argList = new List<Query>(numArgs);
props = Props.None;
for (int count = 0; count < numArgs; count++)
{
Props argProps;
argList.Add(ProcessNode((AstNode)args[count], Flags.None, out argProps));
props |= argProps;
}
return argList;
}
private int _parseDepth = 0;
private const int MaxParseDepth = 1024;
private Query ProcessNode(AstNode root, Flags flags, out Props props)
{
if (++_parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
Debug.Assert(root != null, "root != null");
Query result = null;
props = Props.None;
switch (root.Type)
{
case AstNode.AstType.Axis:
result = ProcessAxis((Axis)root, flags, out props);
break;
case AstNode.AstType.Operator:
result = ProcessOperator((Operator)root, out props);
break;
case AstNode.AstType.Filter:
result = ProcessFilter((Filter)root, flags, out props);
break;
case AstNode.AstType.ConstantOperand:
result = new OperandQuery(((Operand)root).OperandValue);
break;
case AstNode.AstType.Variable:
result = ProcessVariable((Variable)root);
break;
case AstNode.AstType.Function:
result = ProcessFunction((Function)root, out props);
break;
case AstNode.AstType.Group:
result = new GroupQuery(ProcessNode(((Group)root).GroupNode, Flags.None, out props));
break;
case AstNode.AstType.Root:
result = new AbsoluteQuery();
break;
default:
Debug.Fail("Unknown QueryType encountered!!");
break;
}
--_parseDepth;
return result;
}
private Query Build(AstNode root, string query)
{
Reset();
Props props;
_query = query;
Query result = ProcessNode(root, Flags.None, out props);
return result;
}
internal Query Build(string query, bool allowVar, bool allowKey)
{
_allowVar = allowVar;
_allowKey = allowKey;
_allowCurrent = true;
return Build(XPathParser.ParseXPathExpression(query), query);
}
internal Query Build(string query, out bool needContext)
{
Query result = Build(query, true, true);
needContext = _needContext;
return result;
}
internal Query BuildPatternQuery(string query, bool allowVar, bool allowKey)
{
_allowVar = allowVar;
_allowKey = allowKey;
_allowCurrent = false;
return Build(XPathParser.ParseXPathPattern(query), query);
}
internal Query BuildPatternQuery(string query, out bool needContext)
{
Query result = BuildPatternQuery(query, true, true);
needContext = _needContext;
return result;
}
}
}
| |
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 LinkRelationsMore.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.
// See the LICENSE file in the project root for more information.
//
using System;
class r8NaNadd
{
//user-defined class that overloads operator +
public class numHolder
{
double d_num;
public numHolder(double d_num)
{
this.d_num = Convert.ToSingle(d_num);
}
public static double operator +(numHolder a, double b)
{
return a.d_num + b;
}
public static double operator +(numHolder a, numHolder b)
{
return a.d_num + b.d_num;
}
}
static double d_s_test1_op1 = Double.NegativeInfinity;
static double d_s_test1_op2 = Double.PositiveInfinity;
static double d_s_test2_op1 = Double.PositiveInfinity;
static double d_s_test2_op2 = Double.NaN;
static double d_s_test3_op1 = Double.NaN;
static double d_s_test3_op2 = Double.NaN;
public static double d_test1_f(String s)
{
if (s == "test1_op1")
return Double.NegativeInfinity;
else
return Double.PositiveInfinity;
}
public static double d_test2_f(String s)
{
if (s == "test2_op1")
return Double.PositiveInfinity;
else
return Double.NaN;
}
public static double d_test3_f(String s)
{
if (s == "test3_op1")
return Double.NaN;
else
return Double.NaN;
}
class CL
{
public double d_cl_test1_op1 = Double.NegativeInfinity;
public double d_cl_test1_op2 = Double.PositiveInfinity;
public double d_cl_test2_op1 = Double.PositiveInfinity;
public double d_cl_test2_op2 = Double.NaN;
public double d_cl_test3_op1 = Double.NaN;
public double d_cl_test3_op2 = Double.NaN;
}
struct VT
{
public double d_vt_test1_op1;
public double d_vt_test1_op2;
public double d_vt_test2_op1;
public double d_vt_test2_op2;
public double d_vt_test3_op1;
public double d_vt_test3_op2;
}
public static int Main()
{
bool passed = true;
//initialize class
CL cl1 = new CL();
//initialize struct
VT vt1;
vt1.d_vt_test1_op1 = Double.NegativeInfinity;
vt1.d_vt_test1_op2 = Double.PositiveInfinity;
vt1.d_vt_test2_op1 = Double.PositiveInfinity;
vt1.d_vt_test2_op2 = Double.NaN;
vt1.d_vt_test3_op1 = Double.NaN;
vt1.d_vt_test3_op2 = Double.NaN;
double[] d_arr1d_test1_op1 = { 0, Double.NegativeInfinity };
double[,] d_arr2d_test1_op1 = { { 0, Double.NegativeInfinity }, { 1, 1 } };
double[, ,] d_arr3d_test1_op1 = { { { 0, Double.NegativeInfinity }, { 1, 1 } } };
double[] d_arr1d_test1_op2 = { Double.PositiveInfinity, 0, 1 };
double[,] d_arr2d_test1_op2 = { { 0, Double.PositiveInfinity }, { 1, 1 } };
double[, ,] d_arr3d_test1_op2 = { { { 0, Double.PositiveInfinity }, { 1, 1 } } };
double[] d_arr1d_test2_op1 = { 0, Double.PositiveInfinity };
double[,] d_arr2d_test2_op1 = { { 0, Double.PositiveInfinity }, { 1, 1 } };
double[, ,] d_arr3d_test2_op1 = { { { 0, Double.PositiveInfinity }, { 1, 1 } } };
double[] d_arr1d_test2_op2 = { Double.NaN, 0, 1 };
double[,] d_arr2d_test2_op2 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test2_op2 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test3_op1 = { 0, Double.NaN };
double[,] d_arr2d_test3_op1 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test3_op1 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test3_op2 = { Double.NaN, 0, 1 };
double[,] d_arr2d_test3_op2 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test3_op2 = { { { 0, Double.NaN }, { 1, 1 } } };
int[,] index = { { 0, 0 }, { 1, 1 } };
{
double d_l_test1_op1 = Double.NegativeInfinity;
double d_l_test1_op2 = Double.PositiveInfinity;
if (!Double.IsNaN(d_l_test1_op1 + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 64 failed");
passed = false;
}
}
{
double d_l_test2_op1 = Double.PositiveInfinity;
double d_l_test2_op2 = Double.NaN;
if (!Double.IsNaN(d_l_test2_op1 + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 64 failed");
passed = false;
}
}
{
double d_l_test3_op1 = Double.NaN;
double d_l_test3_op2 = Double.NaN;
if (!Double.IsNaN(d_l_test3_op1 + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 64 failed");
passed = false;
}
}
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using NetCoreForce.Client.Models;
namespace NetCoreForce.Client
{
public class AuthenticationClient : IDisposable
{
private string DefaultApiVersion { get { return "v50.0"; } }
public string ApiVersion { get; set; }
/// <summary>
/// The access token response from a successful authentication.
/// </summary>
/// <returns><see cref="AccessTokenResponse" /></returns>
public AccessTokenResponse AccessInfo { get; private set; }
private const string UserAgent = "netcoreforce-client";
private const string TokenRequestEndpointUrl = "https://login.salesforce.com/services/oauth2/token";
private readonly HttpClient _httpClient;
/// <summary>
/// Initialize the AuthenticationClient with the libary's default Salesforce API version
/// <para>See the DefaultApiVersion property</para>
/// </summary>
public AuthenticationClient() : this(null) { }
/// <summary>
/// Initialize the AuthenticationClient with the specified Salesforce API version
/// </summary>
/// <param name="apiVersion">Target Salesforce API version</param>
public AuthenticationClient(string apiVersion)
{
if (!string.IsNullOrEmpty(apiVersion))
{
ApiVersion = apiVersion;
}
else
{
ApiVersion = DefaultApiVersion;
}
_httpClient = new HttpClient();
}
/// <summary>
/// Authenticate using the "Username and Password" auth flow, synchronously
/// <para>Uses a default Token request endpoint URL: https://login.salesforce.com/services/oauth2/token</para>
/// </summary>
/// <param name="clientId">Client ID, a.k.a. Consumer Key</param>
/// <param name="clientSecret">Client Secret, a.k.a. Consumer Secret</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <exception cref="ForceAuthException">Thrown if the authentication fails</exception>
public void UsernamePassword(string clientId, string clientSecret, string username, string password)
{
UsernamePassword(clientId, clientSecret, username, password, TokenRequestEndpointUrl);
}
/// <summary>
/// Authenticate using the "Username and Password" auth flow, synchronously
/// <para>Uses a default Token request endpoint URL: https://login.salesforce.com/services/oauth2/token</para>
/// </summary>
/// <param name="clientId">Client ID, a.k.a. Consumer Key</param>
/// <param name="clientSecret">Client Secret, a.k.a. Consumer Secret</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="tokenRequestEndpointUrl">Token request endpoint URL, e.g. https://login.salesforce.com/services/oauth2/token</param>
/// <exception cref="ForceAuthException">Thrown if the authentication fails</exception>
public void UsernamePassword(string clientId, string clientSecret, string username, string password, string tokenRequestEndpointUrl)
{
try
{
var task = UsernamePasswordAsync(clientId, clientSecret, username, password, tokenRequestEndpointUrl);
task.Wait();
}
catch (AggregateException ex)
{
// Will typically be a single ForceAuthException exception - unwrap and throw
if (ex.InnerException != null && ex.InnerExceptions != null && ex.InnerExceptions.Count == 1)
{
throw ex.InnerException;
}
//otherwise throw the original AggregateException as-is
throw;
}
}
/// <summary>
/// Authenticate using the "Username and Password" auth flow
/// <para>Uses a default Token request endpoint URL: https://login.salesforce.com/services/oauth2/token</para>
/// </summary>
/// <param name="clientId">Client ID, a.k.a. Consumer Key</param>
/// <param name="clientSecret">Client Secret, a.k.a. Consumer Secret</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <exception cref="ForceAuthException">Thrown if the authentication fails</exception>
public Task UsernamePasswordAsync(string clientId, string clientSecret, string username, string password)
{
return UsernamePasswordAsync(clientId, clientSecret, username, password, TokenRequestEndpointUrl);
}
/// <summary>
/// Authenticate using the "Username and Password" auth flow
/// </summary>
/// <param name="clientId">Client ID, a.k.a. Consumer Key</param>
/// <param name="clientSecret">Client Secret, a.k.a. Consumer Secret</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="tokenRequestEndpointUrl">Token request endpoint URL, e.g. https://login.salesforce.com/services/oauth2/token</param>
/// <exception cref="ForceAuthException">Thrown if the authentication fails</exception>
public async Task UsernamePasswordAsync(string clientId, string clientSecret, string username, string password, string tokenRequestEndpointUrl)
{
#if DEBUG
Stopwatch sw = new Stopwatch();
sw.Start();
#endif
if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId", "Client ID is null or empty");
if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret", "Client Secret is null or empty");
if (string.IsNullOrEmpty(username)) throw new ArgumentNullException("username", "Username is null or empty");
if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password", "Password is null or empty");
if (string.IsNullOrEmpty(tokenRequestEndpointUrl)) throw new ArgumentNullException("tokenRequestEndpointUrl", "Token Request Endpoint is null or empty");
if (!Uri.IsWellFormedUriString(tokenRequestEndpointUrl, UriKind.Absolute)) throw new FormatException("Invalid tokenRequestEndpointUrl");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(tokenRequestEndpointUrl),
Content = content
};
request.Headers.UserAgent.ParseAdd(string.Concat(UserAgent, "/", ApiVersion));
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
if (responseMessage.IsSuccessStatusCode)
{
this.AccessInfo = JsonConvert.DeserializeObject<AccessTokenResponse>(response);
}
else if (responseMessage.StatusCode == HttpStatusCode.NotFound)
{
// Unable to reach the auth/token url
throw new ForceAuthException(Error.Unknown.ToString(), "Error reaching Login URL", responseMessage.StatusCode);
}
else
{
var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
throw new ForceAuthException(errorResponse.Error, errorResponse.ErrorDescription, responseMessage.StatusCode);
}
#if DEBUG
sw.Stop();
Debug.WriteLine(string.Format("Login completed in {0}ms", sw.ElapsedMilliseconds.ToString()));
#endif
return;
}
/// <summary>
/// Web Server OAuth Authentication Flow
/// <para>https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_web_server_oauth_flow.htm</para>
/// </summary>
/// <param name="clientId">The Consumer Key from the connected app definition.</param>
/// <param name="clientSecret">The Consumer Secret from the connected app definition. Required unless the Require Secret for Web Server Flow setting is not enabled in the connected app definition.</param>
/// <param name="redirectUri">The Callback URL from the connected app definition.</param>
/// <param name="code">Authorization code the consumer must use to obtain the access and refresh tokens.</param>
/// <param name="tokenRequestEndpointUrl">Salesforce token request endpoint</param>
/// <returns><see cref="AccessTokenResponse" /></returns>
public async Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code, string tokenRequestEndpointUrl = TokenRequestEndpointUrl)
{
if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId");
if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret");
if (string.IsNullOrEmpty(redirectUri)) throw new ArgumentNullException("redirectUri");
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) throw new FormatException("redirectUri");
if (string.IsNullOrEmpty(code)) throw new ArgumentNullException("code");
if (string.IsNullOrEmpty(tokenRequestEndpointUrl)) throw new ArgumentNullException("tokenRequestEndpointUrl");
if (!Uri.IsWellFormedUriString(tokenRequestEndpointUrl, UriKind.Absolute)) throw new FormatException("tokenRequestEndpointUrl");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("code", code)
});
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(tokenRequestEndpointUrl),
Content = content
};
request.Headers.UserAgent.ParseAdd(string.Concat(UserAgent, "/", ApiVersion));
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
if (responseMessage.IsSuccessStatusCode)
{
this.AccessInfo = JsonConvert.DeserializeObject<AccessTokenResponse>(response);
}
else
{
try
{
var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
throw new ForceAuthException(errorResponse.Error, errorResponse.ErrorDescription, responseMessage.StatusCode);
}
catch (Exception ex)
{
throw new ForceAuthException("Unknown", ex.Message, responseMessage.StatusCode);
}
}
}
/// <summary>
/// Obtain a new access token using a refresh token
/// </summary>
/// <param name="refreshToken">The refresh token the client application already received.</param>
/// <param name="clientId">The Consumer Key from the connected app definition.</param>
/// <param name="clientSecret">The Consumer Secret from the connected app definition. Required unless the Require Secret for Web Server Flow setting is not enabled in the connected app definition.</param>
/// <param name="tokenRequestEndpointUrl"></param>
/// <returns></returns>
public async Task TokenRefreshAsync(string refreshToken, string clientId, string clientSecret = "", string tokenRequestEndpointUrl = TokenRequestEndpointUrl)
{
var uri = UriFormatter.RefreshTokenUrl(
tokenRequestEndpointUrl,
refreshToken,
clientId,
clientSecret);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
request.Headers.UserAgent.ParseAdd(string.Concat(UserAgent, "/", ApiVersion));
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
if (responseMessage.IsSuccessStatusCode)
{
this.AccessInfo = JsonConvert.DeserializeObject<AccessTokenResponse>(response);
this.AccessInfo.RefreshToken = refreshToken; //not included in reponse
}
else
{
var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
throw new ForceAuthException(errorResponse.Error, errorResponse.ErrorDescription, responseMessage.StatusCode);
}
}
public void Dispose()
{
_httpClient.Dispose();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForIndexersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new UseExpressionBodyForIndexersDiagnosticAnalyzer(), new UseExpressionBodyForIndexersCodeFixProvider());
private static readonly Dictionary<OptionKey, object> UseExpressionBody =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CodeStyleOptions.TrueWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement },
};
private static readonly Dictionary<OptionKey, object> UseBlockBody =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CodeStyleOptions.FalseWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement }
};
private static readonly Dictionary<OptionKey, object> UseBlockBodyExceptAccessor =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CodeStyleOptions.FalseWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.TrueWithNoneEnforcement }
};
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i]
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int this[int i]
{
get
{
[|return|] Bar();
}
set
{
}
}
}", new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingOnSetter1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int this[int i]
{
set
{
[|Bar|]();
}
}
}", new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i]
{
get
{
[|throw|] new NotImplementedException();
}
}
}",
@"class C
{
int this[int i] => throw new NotImplementedException();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i]
{
get
{
[|throw|] new NotImplementedException(); // comment
}
}
}",
@"class C
{
int this[int i] => throw new NotImplementedException(); // comment
}", ignoreTrivia: false, options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i] [|=>|] Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBodyIfAccessorWantExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i] [|=>|] Bar();
}",
@"class C
{
int this[int i]
{
get => Bar();
}
}", options: UseBlockBodyExceptAccessor);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i] [|=>|] throw new NotImplementedException();
}",
@"class C
{
int this[int i]
{
get
{
throw new NotImplementedException();
}
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i] [|=>|] throw new NotImplementedException(); // comment
}",
@"class C
{
int this[int i]
{
get
{
throw new NotImplementedException(); // comment
}
}
}", ignoreTrivia: false, options: UseBlockBody);
}
}
}
| |
/*
* Analyst.cs: proxy that makes packet inspection and modifcation interactive
* See the README for usage instructions.
*
* Copyright (c) 2006 Austin Jennings
* Modified by "qode" and "mcortez" on December 21st, 2006 to work with the new
* pregen
* 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.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Reflection;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.Packets;
using GridProxy;
public class Analyst : ProxyPlugin
{
private ProxyFrame frame;
private Proxy proxy;
private Hashtable loggedPackets = new Hashtable();
private string logGrep = null;
private Dictionary<PacketType, Dictionary<BlockField, object>> modifiedPackets = new Dictionary<PacketType, Dictionary<BlockField, object>>();
private Assembly openmvAssembly;
private StreamWriter output;
//private PacketDecoder DecodePacket = new PacketDecoder();
public Analyst(ProxyFrame frame)
{
this.frame = frame;
this.proxy = frame.proxy;
}
~Analyst()
{
if (output != null)
output.Close();
}
public override void Init()
{
openmvAssembly = Assembly.Load("OpenMetaverse");
if (openmvAssembly == null) throw new Exception("Assembly load exception");
// build the table of /command delegates
InitializeCommandDelegates();
// handle command line arguments
foreach (string arg in frame.Args)
if (arg == "--log-all")
LogAll();
else if (arg.Contains("--log-whitelist="))
LogWhitelist(arg.Substring(arg.IndexOf('=') + 1));
else if (arg.Contains("--no-log-blacklist="))
NoLogBlacklist(arg.Substring(arg.IndexOf('=') + 1));
else if (arg.Contains("--output="))
SetOutput(arg.Substring(arg.IndexOf('=') + 1));
Console.WriteLine("Analyst loaded");
}
// InitializeCommandDelegates: configure Analyst's commands
private void InitializeCommandDelegates()
{
frame.AddCommand("/log", new ProxyFrame.CommandDelegate(CmdLog));
frame.AddCommand("/-log", new ProxyFrame.CommandDelegate(CmdNoLog));
frame.AddCommand("/grep", new ProxyFrame.CommandDelegate(CmdGrep));
frame.AddCommand("/drop", new ProxyFrame.CommandDelegate(CmdDrop));
frame.AddCommand("/-drop", new ProxyFrame.CommandDelegate(CmdNoDrop));
frame.AddCommand("/set", new ProxyFrame.CommandDelegate(CmdSet));
frame.AddCommand("/-set", new ProxyFrame.CommandDelegate(CmdNoSet));
frame.AddCommand("/inject", new ProxyFrame.CommandDelegate(CmdInject));
frame.AddCommand("/in", new ProxyFrame.CommandDelegate(CmdInject));
}
private static PacketType packetTypeFromName(string name)
{
Type packetTypeType = typeof(PacketType);
System.Reflection.FieldInfo f = packetTypeType.GetField(name);
if (f == null) throw new ArgumentException("Bad packet type");
return (PacketType)Enum.ToObject(packetTypeType, (int)f.GetValue(packetTypeType));
}
// CmdLog: handle a /log command
private void CmdLog(string[] words)
{
if (words.Length != 2)
SayToUser("Usage: /log <packet name>");
else if (words[1] == "*")
{
LogAll();
SayToUser("logging all packets");
}
else
{
PacketType pType;
try
{
pType = packetTypeFromName(words[1]);
}
catch (ArgumentException)
{
SayToUser("Bad packet name: " + words[1]);
return;
}
loggedPackets[pType] = null;
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
SayToUser("logging " + words[1]);
}
}
// CmdNoLog: handle a /-log command
private void CmdNoLog(string[] words)
{
if (words.Length != 2)
SayToUser("Usage: /-log <packet name>");
else if (words[1] == "*")
{
NoLogAll();
SayToUser("stopped logging all packets");
}
else
{
PacketType pType = packetTypeFromName(words[1]);
loggedPackets.Remove(pType);
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
SayToUser("stopped logging " + words[1]);
}
}
// CmdGrep: handle a /grep command
private void CmdGrep(string[] words)
{
if (words.Length == 1)
{
logGrep = null;
SayToUser("stopped filtering logs");
}
else
{
string[] regexArray = new string[words.Length - 1];
Array.Copy(words, 1, regexArray, 0, words.Length - 1);
logGrep = String.Join(" ", regexArray);
SayToUser("filtering log with " + logGrep);
}
}
private void CmdDrop(string[] words)
{
throw new NotImplementedException();
}
private void CmdNoDrop(string[] words)
{
throw new NotImplementedException();
}
// CmdSet: handle a /set command
private void CmdSet(string[] words)
{
if (words.Length < 5)
SayToUser("Usage: /set <packet name> <block> <field> <value>");
else
{
PacketType pType;
try
{
pType = packetTypeFromName(words[1]);
}
catch (ArgumentException)
{
SayToUser("Bad packet name: " + words[1]);
return;
}
string[] valueArray = new string[words.Length - 4];
Array.Copy(words, 4, valueArray, 0, words.Length - 4);
string valueString = String.Join(" ", valueArray);
object value;
try
{
value = MagicCast(words[1], words[2], words[3], valueString);
}
catch (Exception e)
{
SayToUser(e.Message);
return;
}
Dictionary<BlockField, object> fields;
if (modifiedPackets.ContainsKey(pType))
fields = (Dictionary<BlockField, object>)modifiedPackets[pType];
else
fields = new Dictionary<BlockField, object>();
fields[new BlockField(words[2], words[3])] = value;
modifiedPackets[pType] = fields;
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(ModifyIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(ModifyOut));
SayToUser("setting " + words[1] + "." + words[2] + "." + words[3] + " = " + valueString);
}
}
// CmdNoSet: handle a /-set command
private void CmdNoSet(string[] words)
{
if (words.Length == 2 && words[1] == "*")
{
foreach (PacketType pType in modifiedPackets.Keys)
{
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(ModifyIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(ModifyOut));
}
modifiedPackets = new Dictionary<PacketType, Dictionary<BlockField, object>>();
SayToUser("stopped setting all fields");
}
else if (words.Length == 4)
{
PacketType pType;
try
{
pType = packetTypeFromName(words[1]);
}
catch (ArgumentException)
{
SayToUser("Bad packet name: " + words[1]);
return;
}
if (modifiedPackets.ContainsKey(pType))
{
Dictionary<BlockField, object> fields = modifiedPackets[pType];
fields.Remove(new BlockField(words[2], words[3]));
if (fields.Count == 0)
{
modifiedPackets.Remove(pType);
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(ModifyIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(ModifyOut));
}
}
SayToUser("stopped setting " + words[1] + "." + words[2] + "." + words[3]);
}
else
SayToUser("Usage: /-set <packet name> <block> <field>");
}
// CmdInject: handle an /inject command
private void CmdInject(string[] words)
{
if (words.Length < 2)
SayToUser("Usage: /inject <packet file> [value]");
else
{
string[] valueArray = new string[words.Length - 2];
Array.Copy(words, 2, valueArray, 0, words.Length - 2);
string value = String.Join(" ", valueArray);
FileStream fs = null;
StreamReader sr = null;
Direction direction = Direction.Incoming;
string name = null;
string block = null;
object blockObj = null;
Type packetClass = null;
Packet packet = null;
try
{
fs = File.OpenRead(words[1] + ".packet");
sr = new StreamReader(fs);
string line;
while ((line = sr.ReadLine()) != null)
{
Match match;
if (name == null)
{
match = (new Regex(@"^\s*(in|out)\s+(\w+)\s*$")).Match(line);
if (!match.Success)
{
SayToUser("expecting direction and packet name, got: " + line);
return;
}
string lineDir = match.Groups[1].Captures[0].ToString();
string lineName = match.Groups[2].Captures[0].ToString();
if (lineDir == "in")
direction = Direction.Incoming;
else if (lineDir == "out")
direction = Direction.Outgoing;
else
{
SayToUser("expecting 'in' or 'out', got: " + line);
return;
}
name = lineName;
packetClass = openmvAssembly.GetType("OpenMetaverse.Packets." + name + "Packet");
if (packetClass == null) throw new Exception("Couldn't get class " + name + "Packet");
ConstructorInfo ctr = packetClass.GetConstructor(new Type[] { });
if (ctr == null) throw new Exception("Couldn't get suitable constructor for " + name + "Packet");
packet = (Packet)ctr.Invoke(new object[] { });
//Console.WriteLine("Created new " + name + "Packet");
}
else
{
match = (new Regex(@"^\s*\[(\w+)\]\s*$")).Match(line);
if (match.Success)
{
block = match.Groups[1].Captures[0].ToString();
FieldInfo blockField = packetClass.GetField(block);
if (blockField == null) throw new Exception("Couldn't get " + name + "Packet." + block);
Type blockClass = blockField.FieldType;
if (blockClass.IsArray)
{
blockClass = blockClass.GetElementType();
ConstructorInfo ctr = blockClass.GetConstructor(new Type[] { });
if (ctr == null) throw new Exception("Couldn't get suitable constructor for " + blockClass.Name);
blockObj = ctr.Invoke(new object[] { });
object[] arr = (object[])blockField.GetValue(packet);
object[] narr = (object[])Array.CreateInstance(blockClass, arr.Length + 1);
Array.Copy(arr, narr, arr.Length);
narr[arr.Length] = blockObj;
blockField.SetValue(packet, narr);
//Console.WriteLine("Added block "+block);
}
else
{
blockObj = blockField.GetValue(packet);
}
if (blockObj == null) throw new Exception("Got " + name + "Packet." + block + " == null");
//Console.WriteLine("Got block " + name + "Packet." + block);
continue;
}
if (block == null)
{
SayToUser("expecting block name, got: " + line);
return;
}
match = (new Regex(@"^\s*(\w+)\s*=\s*(.*)$")).Match(line);
if (match.Success)
{
string lineField = match.Groups[1].Captures[0].ToString();
string lineValue = match.Groups[2].Captures[0].ToString();
object fval;
//FIXME: use of MagicCast inefficient
if (lineValue == "$Value")
fval = MagicCast(name, block, lineField, value);
else if (lineValue == "$UUID")
fval = UUID.Random();
else if (lineValue == "$AgentID")
fval = frame.AgentID;
else if (lineValue == "$SessionID")
fval = frame.SessionID;
else
fval = MagicCast(name, block, lineField, lineValue);
MagicSetField(blockObj, lineField, fval);
continue;
}
SayToUser("expecting block name or field, got: " + line);
return;
}
}
if (name == null)
{
SayToUser("expecting direction and packet name, got EOF");
return;
}
packet.Header.Reliable = true;
//if (protocolManager.Command(name).Encoded)
// packet.Header.Zerocoded = true;
proxy.InjectPacket(packet, direction);
SayToUser("injected " + words[1]);
}
catch (Exception e)
{
SayToUser("failed to inject " + words[1] + ": " + e.Message);
Console.WriteLine("failed to inject " + words[1] + ": " + e.Message + "\n" + e.StackTrace);
}
finally
{
if (fs != null)
fs.Close();
if (sr != null)
sr.Close();
}
}
}
// SayToUser: send a message to the user as in-world chat
private void SayToUser(string message)
{
ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket();
packet.ChatData.FromName = Utils.StringToBytes("Analyst");
packet.ChatData.SourceID = UUID.Random();
packet.ChatData.OwnerID = frame.AgentID;
packet.ChatData.SourceType = (byte)2;
packet.ChatData.ChatType = (byte)1;
packet.ChatData.Audible = (byte)1;
packet.ChatData.Position = new Vector3(0, 0, 0);
packet.ChatData.Message = Utils.StringToBytes(message);
proxy.InjectPacket(packet, Direction.Incoming);
}
// BlockField: product type for a block name and field name
private struct BlockField
{
public string block;
public string field;
public BlockField(string block, string field)
{
this.block = block;
this.field = field;
}
}
private static void MagicSetField(object obj, string field, object val)
{
Type cls = obj.GetType();
FieldInfo fieldInf = cls.GetField(field);
if (fieldInf == null)
{
PropertyInfo prop = cls.GetProperty(field);
if (prop == null) throw new Exception("Couldn't find field " + cls.Name + "." + field);
prop.SetValue(obj, val, null);
//throw new Exception("FIXME: can't set properties");
}
else
{
fieldInf.SetValue(obj, val);
}
}
// MagicCast: given a packet/block/field name and a string, convert the string to a value of the appropriate type
private object MagicCast(string name, string block, string field, string value)
{
Type packetClass = openmvAssembly.GetType("OpenMetaverse.Packets." + name + "Packet");
if (packetClass == null) throw new Exception("Couldn't get class " + name + "Packet");
FieldInfo blockField = packetClass.GetField(block);
if (blockField == null) throw new Exception("Couldn't get " + name + "Packet." + block);
Type blockClass = blockField.FieldType;
if (blockClass.IsArray) blockClass = blockClass.GetElementType();
// Console.WriteLine("DEBUG: " + blockClass.Name);
FieldInfo fieldField = blockClass.GetField(field); PropertyInfo fieldProp = null;
Type fieldClass = null;
if (fieldField == null)
{
fieldProp = blockClass.GetProperty(field);
if (fieldProp == null) throw new Exception("Couldn't get " + name + "Packet." + block + "." + field);
fieldClass = fieldProp.PropertyType;
}
else
{
fieldClass = fieldField.FieldType;
}
try
{
if (fieldClass == typeof(byte))
{
return Convert.ToByte(value);
}
else if (fieldClass == typeof(ushort))
{
return Convert.ToUInt16(value);
}
else if (fieldClass == typeof(uint))
{
return Convert.ToUInt32(value);
}
else if (fieldClass == typeof(ulong))
{
return Convert.ToUInt64(value);
}
else if (fieldClass == typeof(sbyte))
{
return Convert.ToSByte(value);
}
else if (fieldClass == typeof(short))
{
return Convert.ToInt16(value);
}
else if (fieldClass == typeof(int))
{
return Convert.ToInt32(value);
}
else if (fieldClass == typeof(long))
{
return Convert.ToInt64(value);
}
else if (fieldClass == typeof(float))
{
return Convert.ToSingle(value);
}
else if (fieldClass == typeof(double))
{
return Convert.ToDouble(value);
}
else if (fieldClass == typeof(UUID))
{
return new UUID(value);
}
else if (fieldClass == typeof(bool))
{
if (value.ToLower() == "true")
return true;
else if (value.ToLower() == "false")
return false;
else
throw new Exception();
}
else if (fieldClass == typeof(byte[]))
{
return Utils.StringToBytes(value);
}
else if (fieldClass == typeof(Vector3))
{
Vector3 result;
if (Vector3.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClass == typeof(Vector3d))
{
Vector3d result;
if (Vector3d.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClass == typeof(Vector4))
{
Vector4 result;
if (Vector4.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClass == typeof(Quaternion))
{
Quaternion result;
if (Quaternion.TryParse(value, out result))
return result;
else
throw new Exception();
}
else
{
throw new Exception("unsupported field type " + fieldClass);
}
}
catch
{
throw new Exception("unable to interpret " + value + " as " + fieldClass);
}
}
// ModifyIn: modify an incoming packet
private Packet ModifyIn(Packet packet, IPEndPoint endPoint)
{
return Modify(packet, endPoint, Direction.Incoming);
}
// ModifyOut: modify an outgoing packet
private Packet ModifyOut(Packet packet, IPEndPoint endPoint)
{
return Modify(packet, endPoint, Direction.Outgoing);
}
// Modify: modify a packet
private Packet Modify(Packet packet, IPEndPoint endPoint, Direction direction)
{
if (modifiedPackets.ContainsKey(packet.Type))
{
try
{
Dictionary<BlockField, object> changes = modifiedPackets[packet.Type];
Type packetClass = packet.GetType();
foreach (KeyValuePair<BlockField, object> change in changes)
{
BlockField bf = change.Key;
FieldInfo blockField = packetClass.GetField(bf.block);
if (blockField.FieldType.IsArray) // We're modifying a variable block.
{
// Modify each block in the variable block identically.
// This is really simple, can probably be improved.
object[] blockArray = (object[])blockField.GetValue(packet);
foreach (object blockElement in blockArray)
{
MagicSetField(blockElement, bf.field, change.Value);
}
}
else
{
//Type blockClass = blockField.FieldType;
object blockObject = blockField.GetValue(packet);
MagicSetField(blockObject, bf.field, change.Value);
}
}
}
catch (Exception e)
{
Console.WriteLine("failed to modify " + packet.Type + ": " + e.Message);
Console.WriteLine(e.StackTrace);
}
}
return packet;
}
// LogPacketIn: log an incoming packet
private Packet LogPacketIn(Packet packet, IPEndPoint endPoint)
{
LogPacket(packet, endPoint, Direction.Incoming);
return packet;
}
// LogPacketOut: log an outgoing packet
private Packet LogPacketOut(Packet packet, IPEndPoint endPoint)
{
LogPacket(packet, endPoint, Direction.Outgoing);
return packet;
}
// LogAll: register logging delegates for all packets
private void LogAll()
{
Type packetTypeType = typeof(PacketType);
System.Reflection.MemberInfo[] packetTypes = packetTypeType.GetMembers();
for (int i = 0; i < packetTypes.Length; i++)
{
if (packetTypes[i].MemberType == System.Reflection.MemberTypes.Field && packetTypes[i].DeclaringType == packetTypeType)
{
string name = packetTypes[i].Name;
PacketType pType;
try
{
pType = packetTypeFromName(name);
}
catch (Exception)
{
continue;
}
loggedPackets[pType] = null;
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
}
}
}
private void LogWhitelist(string whitelistFile)
{
try
{
string[] lines = File.ReadAllLines(whitelistFile);
int count = 0;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
if (line.Length == 0)
continue;
PacketType pType;
try
{
pType = packetTypeFromName(line);
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
++count;
}
catch (ArgumentException)
{
Console.WriteLine("Bad packet name: " + line);
}
}
Console.WriteLine(String.Format("Logging {0} packet types loaded from whitelist", count));
}
catch (Exception)
{
Console.WriteLine("Failed to load packet whitelist from " + whitelistFile);
}
}
private void NoLogBlacklist(string blacklistFile)
{
try
{
string[] lines = File.ReadAllLines(blacklistFile);
int count = 0;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
if (line.Length == 0)
continue;
PacketType pType;
try
{
pType = packetTypeFromName(line);
string[] noLogStr = new string[] {"/-log", line};
CmdNoLog(noLogStr);
++count;
}
catch (ArgumentException)
{
Console.WriteLine("Bad packet name: " + line);
}
}
Console.WriteLine(String.Format("Not logging {0} packet types loaded from blacklist", count));
}
catch (Exception)
{
Console.WriteLine("Failed to load packet blacklist from " + blacklistFile);
}
}
private void SetOutput(string outputFile)
{
try
{
output = new StreamWriter(outputFile, false);
Console.WriteLine("Logging packets to " + outputFile);
}
catch (Exception)
{
Console.WriteLine(String.Format("Failed to open {0} for logging", outputFile));
}
}
// NoLogAll: unregister logging delegates for all packets
private void NoLogAll()
{
Type packetTypeType = typeof(PacketType);
System.Reflection.MemberInfo[] packetTypes = packetTypeType.GetMembers();
for (int i = 0; i < packetTypes.Length; i++)
{
if (packetTypes[i].MemberType == System.Reflection.MemberTypes.Field && packetTypes[i].DeclaringType == packetTypeType)
{
string name = packetTypes[i].Name;
PacketType pType;
try
{
pType = packetTypeFromName(name);
}
catch (Exception)
{
continue;
}
loggedPackets.Remove(pType);
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
}
}
}
// LogPacket: dump a packet to the console
private void LogPacket(Packet packet, IPEndPoint endPoint, Direction direction)
{
//string packetText = DecodePacket.PacketToString(packet);
string packetText = PacketDecoder.PacketToString(packet);
if (logGrep == null || (logGrep != null && Regex.IsMatch(packetText, logGrep)))
{
string line = String.Format("{0}\n{1} {2,21} {3,5} {4}{5}{6}"
, packet.Type
, direction == Direction.Incoming ? "<--" : "-->"
, endPoint
, packet.Header.Sequence
, InterpretOptions(packet.Header)
, Environment.NewLine
, packetText
);
Console.WriteLine(line);
if (output != null)
output.WriteLine(line);
}
}
// InterpretOptions: produce a string representing a packet's header options
private static string InterpretOptions(Header header)
{
return "["
+ (header.AppendedAcks ? "Ack" : " ")
+ " "
+ (header.Resent ? "Res" : " ")
+ " "
+ (header.Reliable ? "Rel" : " ")
+ " "
+ (header.Zerocoded ? "Zer" : " ")
+ "]"
;
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using QuantConnect.ToolBox.RandomDataGenerator;
namespace QuantConnect.Tests.ToolBox.RandomDataGenerator
{
[TestFixture]
public class TickGeneratorTests
{
private Dictionary<SecurityType, List<TickType>> _tickTypesPerSecurityType =
SubscriptionManager.DefaultDataTypes();
private Symbol _symbol = Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
private Security _security;
private ITickGenerator _tickGenerator;
[SetUp]
public void Setup()
{
var start = new DateTime(2020, 1, 1);
var end = new DateTime(2020, 1, 2);
// initialize using a seed for deterministic tests
_symbol = Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_security = new Security(
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(typeof(TradeBar),
_symbol,
Resolution.Minute,
TimeZones.NewYork,
TimeZones.NewYork,
true, true, false),
new Cash(Currencies.USD, 0, 0),
SymbolProperties.GetDefault(Currencies.USD),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache()
);
_security.SetMarketPrice(new Tick(start, _security.Symbol, 100, 100));
_security.SetMarketPrice(new OpenInterest(start, _security.Symbol, 10000));
_tickGenerator = new TickGenerator(
new RandomDataGeneratorSettings()
{
Start = start,
End = end
},
_tickTypesPerSecurityType[_symbol.SecurityType].ToArray(),
_security,
new RandomValueGenerator());
}
[Test]
public void NextTick_CreatesTradeTick_WithPriceAndQuantity()
{
var dateTime = new DateTime(2000, 01, 01);
var tick = _tickGenerator.NextTick(dateTime, TickType.Trade, 1m);
Assert.AreEqual(_symbol, tick.Symbol);
Assert.AreEqual(dateTime, tick.Time);
Assert.AreEqual(TickType.Trade, tick.TickType);
Assert.LessOrEqual(99m, tick.Value);
Assert.GreaterOrEqual(101m, tick.Value);
Assert.Greater(tick.Quantity, 0);
Assert.LessOrEqual(tick.Quantity, 1500);
}
[Test]
public void NextTick_CreatesQuoteTick_WithCommonValues()
{
var dateTime = new DateTime(2000, 01, 01);
var tick = _tickGenerator.NextTick(dateTime, TickType.Quote, 1m);
Assert.AreEqual(_symbol, tick.Symbol);
Assert.AreEqual(dateTime, tick.Time);
Assert.AreEqual(TickType.Quote, tick.TickType);
Assert.GreaterOrEqual(tick.Value, 99m);
Assert.LessOrEqual(tick.Value, 101m);
}
[Test]
public void NextTick_CreatesQuoteTick_WithBidData()
{
var dateTime = new DateTime(2000, 01, 01);
var tick = _tickGenerator.NextTick(dateTime, TickType.Quote, 1m);
Assert.Greater(tick.BidSize, 0);
Assert.LessOrEqual(tick.BidSize, 1500);
Assert.GreaterOrEqual(tick.BidPrice, 98.9m);
Assert.LessOrEqual(tick.BidPrice, 100.9m);
Assert.GreaterOrEqual(tick.Value, tick.BidPrice);
}
[Test]
public void NextTick_CreatesQuoteTick_WithAskData()
{
var dateTime = new DateTime(2000, 01, 01);
var tick = _tickGenerator.NextTick(dateTime, TickType.Quote, 1m);
Assert.GreaterOrEqual(tick.AskSize, 0);
Assert.LessOrEqual(tick.AskSize, 1500);
Assert.GreaterOrEqual(tick.AskPrice, 99.1m);
Assert.LessOrEqual(tick.AskPrice, 101.1m);
Assert.LessOrEqual(tick.Value, tick.AskPrice);
}
[Test]
public void NextTick_CreatesOpenInterestTick()
{
var dateTime = new DateTime(2000, 01, 01);
var tick = _tickGenerator.NextTick(dateTime, TickType.OpenInterest, 10m);
Assert.AreEqual(dateTime, tick.Time);
Assert.AreEqual(TickType.OpenInterest, tick.TickType);
Assert.AreEqual(_symbol, tick.Symbol);
Assert.GreaterOrEqual(tick.Quantity, 9000);
Assert.LessOrEqual(tick.Quantity, 11000);
Assert.AreEqual(tick.Value, tick.Quantity);
}
[Test]
[TestCase(Resolution.Tick, DataDensity.Dense)]
[TestCase(Resolution.Second, DataDensity.Dense)]
[TestCase(Resolution.Minute, DataDensity.Dense)]
[TestCase(Resolution.Hour, DataDensity.Dense)]
[TestCase(Resolution.Daily, DataDensity.Dense)]
[TestCase(Resolution.Tick, DataDensity.Sparse)]
[TestCase(Resolution.Second, DataDensity.Sparse)]
[TestCase(Resolution.Minute, DataDensity.Sparse)]
[TestCase(Resolution.Hour, DataDensity.Sparse)]
[TestCase(Resolution.Daily, DataDensity.Sparse)]
[TestCase(Resolution.Tick, DataDensity.VerySparse)]
[TestCase(Resolution.Second, DataDensity.VerySparse)]
[TestCase(Resolution.Minute, DataDensity.VerySparse)]
[TestCase(Resolution.Hour, DataDensity.VerySparse)]
[TestCase(Resolution.Daily, DataDensity.VerySparse)]
public void NextTickTime_CreatesTimes(Resolution resolution, DataDensity density)
{
var count = 100;
var deltaSum = TimeSpan.Zero;
var previous = new DateTime(2019, 01, 14, 9, 30, 0);
var increment = resolution.ToTimeSpan();
if (increment == TimeSpan.Zero)
{
increment = TimeSpan.FromMilliseconds(500);
}
var marketHours = MarketHoursDatabase.FromDataFolder()
.GetExchangeHours(_symbol.ID.Market, _symbol, _symbol.SecurityType);
for (int i = 0; i < count; i++)
{
var next = _tickGenerator.NextTickTime(previous, resolution, density);
var barStart = next.Subtract(increment);
Assert.Less(previous, next);
Assert.IsTrue(marketHours.IsOpen(barStart, next, false));
var delta = next - previous;
deltaSum += delta;
previous = next;
}
var avgDelta = TimeSpan.FromTicks(deltaSum.Ticks / count);
switch (density)
{
case DataDensity.Dense:
// more frequent than once an increment
Assert.Less(avgDelta, increment);
break;
case DataDensity.Sparse:
// less frequent that once an increment
Assert.Greater(avgDelta, increment);
break;
case DataDensity.VerySparse:
// less frequent than one every 10 increments
Assert.Greater(avgDelta, TimeSpan.FromTicks(increment.Ticks * 10));
break;
default:
throw new ArgumentOutOfRangeException(nameof(density), density, null);
}
}
[Test]
public void HistoryIsNotEmpty()
{
var history = _tickGenerator.GenerateTicks().ToList();
Assert.IsNotEmpty(history);
Assert.That(history.Select(s => s.Symbol), Is.All.EqualTo(_symbol));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Threading;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a block that contains a sequence of expressions where variables can be defined.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))]
public class BlockExpression : Expression
{
/// <summary>
/// Gets the expressions in this block.
/// </summary>
public ReadOnlyCollection<Expression> Expressions
{
get { return GetOrMakeExpressions(); }
}
/// <summary>
/// Gets the variables defined in this block.
/// </summary>
public ReadOnlyCollection<ParameterExpression> Variables
{
get
{
return GetOrMakeVariables();
}
}
/// <summary>
/// Gets the last expression in this block.
/// </summary>
public Expression Result
{
get
{
Debug.Assert(ExpressionCount > 0);
return GetExpression(ExpressionCount - 1);
}
}
internal BlockExpression()
{
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitBlock(this);
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Block; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type
{
get { return GetExpression(ExpressionCount - 1).Type; }
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="variables">The <see cref="Variables" /> property of the result.</param>
/// <param name="expressions">The <see cref="Expressions" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
if (variables == Variables && expressions == Expressions)
{
return this;
}
return Expression.Block(Type, variables, expressions);
}
internal virtual Expression GetExpression(int index)
{
throw ContractUtils.Unreachable;
}
internal virtual int ExpressionCount
{
get
{
throw ContractUtils.Unreachable;
}
}
internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
throw ContractUtils.Unreachable;
}
internal virtual ParameterExpression GetVariable(int index)
{
throw ContractUtils.Unreachable;
}
internal virtual int VariableCount
{
get
{
return 0;
}
}
internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables()
{
return EmptyReadOnlyCollection<ParameterExpression>.Instance;
}
/// <summary>
/// Makes a copy of this node replacing the parameters/args with the provided values. The
/// shape of the parameters/args needs to match the shape of the current block - in other
/// words there should be the same # of parameters and args.
///
/// parameters can be null in which case the existing parameters are used.
///
/// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
/// subclass of BlockExpression which is being used.
/// </summary>
internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
///
/// This is similar to the ReturnReadOnly which only takes a single argument. This version
/// supports nodes which hold onto 5 Expressions and puts all of the arguments into the
/// ReadOnlyCollection.
///
/// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll
/// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything
/// which would force the readonly collection to be created.
///
/// This is used by BlockExpression5 and MethodCallExpression5.
/// </summary>
internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection)
{
Expression tObj = collection as Expression;
if (tObj != null)
{
// otherwise make sure only one readonly collection ever gets exposed
Interlocked.CompareExchange(
ref collection,
new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)),
tObj
);
}
// and return what is not guaranteed to be a readonly collection
return (ReadOnlyCollection<Expression>)collection;
}
}
#region Specialized Subclasses
internal sealed class Block2 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd argument.
internal Block2(Expression arg0, Expression arg1)
{
_arg0 = arg0;
_arg1 = arg1;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 2;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == 2);
Debug.Assert(variables == null || variables.Count == 0);
return new Block2(args[0], args[1]);
}
}
internal sealed class Block3 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments.
internal Block3(Expression arg0, Expression arg1, Expression arg2)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 3;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == 3);
Debug.Assert(variables == null || variables.Count == 0);
return new Block3(args[0], args[1], args[2]);
}
}
internal sealed class Block4 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments.
internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 4;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == 4);
Debug.Assert(variables == null || variables.Count == 0);
return new Block4(args[0], args[1], args[2], args[3]);
}
}
internal sealed class Block5 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args.
internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
_arg4 = arg4;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
case 4: return _arg4;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 5;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == 5);
Debug.Assert(variables == null || variables.Count == 0);
return new Block5(args[0], args[1], args[2], args[3], args[4]);
}
}
internal class BlockN : BlockExpression
{
private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it.
internal BlockN(IList<Expression> expressions)
{
Debug.Assert(expressions.Count != 0);
_expressions = expressions;
}
internal override Expression GetExpression(int index)
{
Debug.Assert(index >= 0 && index < _expressions.Count);
return _expressions[index];
}
internal override int ExpressionCount
{
get
{
return _expressions.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnly(ref _expressions);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(variables == null || variables.Count == 0);
return new BlockN(args);
}
}
internal class ScopeExpression : BlockExpression
{
private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection
internal ScopeExpression(IList<ParameterExpression> variables)
{
_variables = variables;
}
internal override int VariableCount
{
get
{
return _variables.Count;
}
}
internal override ParameterExpression GetVariable(int index)
{
return _variables[index];
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables()
{
return ReturnReadOnly(ref _variables);
}
protected IList<ParameterExpression> VariablesList
{
get
{
return _variables;
}
}
// Used for rewrite of the nodes to either reuse existing set of variables if not rewritten.
internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables)
{
if (variables != null && variables != VariablesList)
{
// Need to validate the new variables (uniqueness, not byref)
ValidateVariables(variables, "variables");
return variables;
}
else
{
return VariablesList;
}
}
}
internal sealed class Scope1 : ScopeExpression
{
private object _body;
internal Scope1(IList<ParameterExpression> variables, Expression body)
: base(variables)
{
_body = body;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_body);
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 1;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _body);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == 1);
Debug.Assert(variables == null || variables.Count == VariableCount);
return new Scope1(ReuseOrValidateVariables(variables), args[0]);
}
}
internal class ScopeN : ScopeExpression
{
private IList<Expression> _body;
internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body)
: base(variables)
{
_body = body;
}
internal override Expression GetExpression(int index)
{
return _body[index];
}
internal override int ExpressionCount
{
get
{
return _body.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnly(ref _body);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == ExpressionCount);
Debug.Assert(variables == null || variables.Count == VariableCount);
return new ScopeN(ReuseOrValidateVariables(variables), args);
}
}
internal class ScopeWithType : ScopeN
{
private readonly Type _type;
internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type)
: base(variables, expressions)
{
_type = type;
}
public sealed override Type Type
{
get { return _type; }
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args.Length == ExpressionCount);
Debug.Assert(variables == null || variables.Count == VariableCount);
return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type);
}
}
#endregion
#region Block List Classes
/// <summary>
/// Provides a wrapper around an IArgumentProvider which exposes the argument providers
/// members out as an IList of Expression. This is used to avoid allocating an array
/// which needs to be stored inside of a ReadOnlyCollection. Instead this type has
/// the same amount of overhead as an array without duplicating the storage of the
/// elements. This ensures that internally we can avoid creating and copying arrays
/// while users of the Expression trees also don't pay a size penalty for this internal
/// optimization. See IArgumentProvider for more general information on the Expression
/// tree optimizations being used here.
/// </summary>
internal class BlockExpressionList : IList<Expression>
{
private readonly BlockExpression _block;
private readonly Expression _arg0;
internal BlockExpressionList(BlockExpression provider, Expression arg0)
{
_block = provider;
_arg0 = arg0;
}
#region IList<Expression> Members
public int IndexOf(Expression item)
{
if (_arg0 == item)
{
return 0;
}
for (int i = 1; i < _block.ExpressionCount; i++)
{
if (_block.GetExpression(i) == item)
{
return i;
}
}
return -1;
}
public void Insert(int index, Expression item)
{
throw ContractUtils.Unreachable;
}
public void RemoveAt(int index)
{
throw ContractUtils.Unreachable;
}
public Expression this[int index]
{
get
{
if (index == 0)
{
return _arg0;
}
return _block.GetExpression(index);
}
set
{
throw ContractUtils.Unreachable;
}
}
#endregion
#region ICollection<Expression> Members
public void Add(Expression item)
{
throw ContractUtils.Unreachable;
}
public void Clear()
{
throw ContractUtils.Unreachable;
}
public bool Contains(Expression item)
{
return IndexOf(item) != -1;
}
public void CopyTo(Expression[] array, int arrayIndex)
{
array[arrayIndex++] = _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
array[arrayIndex++] = _block.GetExpression(i);
}
}
public int Count
{
get { return _block.ExpressionCount; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(Expression item)
{
throw ContractUtils.Unreachable;
}
#endregion
#region IEnumerable<Expression> Members
public IEnumerator<Expression> GetEnumerator()
{
yield return _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
yield return _block.GetExpression(i);
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
yield return _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
yield return _block.GetExpression(i);
}
}
#endregion
}
#endregion
public partial class Expression
{
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
return new Block2(arg0, arg1);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
RequiresCanRead(arg2, "arg2");
return new Block3(arg0, arg1, arg2);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <param name="arg3">The fourth expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
RequiresCanRead(arg2, "arg2");
RequiresCanRead(arg3, "arg3");
return new Block4(arg0, arg1, arg2, arg3);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <param name="arg3">The fourth expression in the block.</param>
/// <param name="arg4">The fifth expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
RequiresCanRead(arg2, "arg2");
RequiresCanRead(arg3, "arg3");
RequiresCanRead(arg4, "arg4");
return new Block5(arg0, arg1, arg2, arg3, arg4);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
/// </summary>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(params Expression[] expressions)
{
ContractUtils.RequiresNotNull(expressions, "expressions");
switch (expressions.Length)
{
case 2: return Block(expressions[0], expressions[1]);
case 3: return Block(expressions[0], expressions[1], expressions[2]);
case 4: return Block(expressions[0], expressions[1], expressions[2], expressions[3]);
case 5: return Block(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]);
default:
ContractUtils.RequiresNotEmpty(expressions, "expressions");
RequiresCanRead(expressions, "expressions");
return new BlockN(expressions.Copy());
}
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
/// </summary>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<Expression> expressions)
{
return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, params Expression[] expressions)
{
ContractUtils.RequiresNotNull(expressions, "expressions");
return Block(type, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<Expression> expressions)
{
return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions)
{
return Block(variables, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions)
{
return Block(type, variables, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
ContractUtils.RequiresNotNull(expressions, "expressions");
var expressionList = expressions.ToReadOnly();
ContractUtils.RequiresNotEmpty(expressionList, "expressions");
RequiresCanRead(expressionList, "expressions");
return Block(expressionList.Last().Type, variables, expressionList);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
ContractUtils.RequiresNotNull(type, "type");
ContractUtils.RequiresNotNull(expressions, "expressions");
var expressionList = expressions.ToReadOnly();
var variableList = variables.ToReadOnly();
ContractUtils.RequiresNotEmpty(expressionList, "expressions");
RequiresCanRead(expressionList, "expressions");
ValidateVariables(variableList, "variables");
Expression last = expressionList.Last();
if (type != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(type, last.Type))
{
throw Error.ArgumentTypesMustMatch();
}
}
if (!TypeUtils.AreEquivalent(type, last.Type))
{
return new ScopeWithType(variableList, expressionList, type);
}
else
{
if (expressionList.Count == 1)
{
return new Scope1(variableList, expressionList[0]);
}
else
{
return new ScopeN(variableList, expressionList);
}
}
}
// Checks that all variables are non-null, not byref, and unique.
internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName)
{
if (varList.Count == 0)
{
return;
}
int count = varList.Count;
var set = new Set<ParameterExpression>(count);
for (int i = 0; i < count; i++)
{
ParameterExpression v = varList[i];
if (v == null)
{
throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count));
}
if (v.IsByRef)
{
throw Error.VariableMustNotBeByRef(v, v.Type);
}
if (set.Contains(v))
{
throw Error.DuplicateVariable(v);
}
set.Add(v);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace BestHTTP.Authentication
{
using BestHTTP.Extensions;
using System.Text;
/// <summary>
/// Internal class that stores all information that received from a server in a WWW-Authenticate and need to construct a valid Authorization header. Based on rfc 2617 (http://tools.ietf.org/html/rfc2617).
/// Used only internally by the plugin.
/// </summary>
internal sealed class Digest
{
#region Public Properties
/// <summary>
/// The Uri that this Digest is bound to.
/// </summary>
public Uri Uri { get; private set; }
public AuthenticationTypes Type { get; private set; }
/// <summary>
/// A string to be displayed to users so they know which username and password to use.
/// This string should contain at least the name of the host performing the authentication and might additionally indicate the collection of users who might have access.
/// </summary>
public string Realm { get; private set; }
/// <summary>
/// A flag, indicating that the previous request from the client was rejected because the nonce value was stale.
/// If stale is TRUE (case-insensitive), the client may wish to simply retry the request with a new encrypted response, without the user for a new username and password.
/// The server should only set stale to TRUE if it receives a request for which the nonce is invalid but with a valid digest for that nonce
/// (indicating that the client knows the correct username/password).
/// If stale is FALSE, or anything other than TRUE, or the stale directive is not present, the username and/or password are invalid, and new values must be obtained.
/// </summary>
public bool Stale { get; private set; }
#endregion
#region Private Properties
/// <summary>
/// A server-specified data string which should be uniquely generated each time a 401 response is made.
/// Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
/// </summary>
private string Nonce { get; set; }
/// <summary>
/// A string of data, specified by the server, which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space.
/// It is recommended that this string be base64 or data.
/// </summary>
private string Opaque { get; set; }
/// <summary>
/// A string indicating a pair of algorithms used to produce the digest and a checksum. If this is not present it is assumed to be "MD5".
/// If the algorithm is not understood, the challenge should be ignored (and a different one used, if there is more than one).
/// </summary>
private string Algorithm { get; set; }
/// <summary>
/// List of URIs, as specified in RFC XURI, that define the protection space.
/// If a URI is an abs_path, it is relative to the canonical root URL (see section 1.2 above) of the server being accessed.
/// An absoluteURI in this list may refer to a different server than the one being accessed.
/// The client can use this list to determine the set of URIs for which the same authentication information may be sent:
/// any URI that has a URI in this list as a prefix (after both have been made absolute) may be assumed to be in the same protection space.
/// If this directive is omitted or its value is empty, the client should assume that the protection space consists of all URIs on the responding server.
/// </summary>
public List<string> ProtectedUris { get; private set; }
/// <summary>
/// If present, it is a quoted string of one or more tokens indicating the "quality of protection" values supported by the server.
/// The value "auth" indicates authentication. The value "auth-int" indicates authentication with integrity protection.
/// </summary>
private string QualityOfProtections { get; set; }
/// <summary>
/// his MUST be specified if a qop directive is sent (see above), and MUST NOT be specified if the server did not send a qop directive in the WWW-Authenticate header field.
/// The nc-value is the hexadecimal count of the number of requests (including the current request) that the client has sent with the nonce value in this request.
/// </summary>
private int NonceCount { get; set; }
/// <summary>
/// Used to store the last HA1 that can be used in the next header generation when Algorithm is set to "md5-sess".
/// </summary>
private string HA1Sess { get; set; }
#endregion
internal Digest(Uri uri)
{
this.Uri = uri;
this.Algorithm = "md5";
}
/// <summary>
/// Parses a WWW-Authenticate header's value to retrive all information.
/// </summary>
public void ParseChallange(string header)
{
// Reset some values to its defaults.
this.Type = AuthenticationTypes.Unknown;
this.Stale = false;
this.Opaque = null;
this.HA1Sess = null;
this.NonceCount = 0;
this.QualityOfProtections = null;
if (this.ProtectedUris != null)
this.ProtectedUris.Clear();
// Parse the header
WWWAuthenticateHeaderParser qpl = new WWWAuthenticateHeaderParser(header);
// Then process
foreach (var qp in qpl.Values)
switch (qp.Key)
{
case "basic": this.Type = AuthenticationTypes.Basic; break;
case "digest": this.Type = AuthenticationTypes.Digest; break;
case "realm": this.Realm = qp.Value; break;
case "domain":
{
if (string.IsNullOrEmpty(qp.Value) || qp.Value.Length == 0)
break;
if (this.ProtectedUris == null)
this.ProtectedUris = new List<string>();
int idx = 0;
string val = qp.Value.Read(ref idx, ' ');
do
{
this.ProtectedUris.Add(val);
val = qp.Value.Read(ref idx, ' ');
} while (idx < qp.Value.Length);
break;
}
case "nonce": this.Nonce = qp.Value; break;
case "qop": this.QualityOfProtections = qp.Value; break;
case "stale": this.Stale = bool.Parse(qp.Value); break;
case "opaque": this.Opaque = qp.Value; break;
case "algorithm": this.Algorithm = qp.Value; break;
}
}
/// <summary>
/// Generates a string that can be set to an Authorization header.
/// </summary>
public string GenerateResponseHeader(HTTPRequest request, Credentials credentials)
{
try
{
switch (Type)
{
case AuthenticationTypes.Basic:
return string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", credentials.UserName, credentials.Password))));
case AuthenticationTypes.Digest:
{
NonceCount++;
string HA1 = string.Empty;
// The cnonce-value is an opaque quoted string value provided by the client and used by both client and server to avoid chosen plaintext attacks, to provide mutual
// authentication, and to provide some message integrity protection.
string cnonce = new System.Random(request.GetHashCode()).Next(int.MinValue, int.MaxValue).ToString("X8");
string ncvalue = NonceCount.ToString("X8");
switch (Algorithm.TrimAndLower())
{
case "md5":
HA1 = string.Format("{0}:{1}:{2}", credentials.UserName, Realm, credentials.Password).CalculateMD5Hash();
break;
case "md5-sess":
if (string.IsNullOrEmpty(this.HA1Sess))
this.HA1Sess = string.Format("{0}:{1}:{2}:{3}:{4}", credentials.UserName, Realm, credentials.Password, Nonce, ncvalue).CalculateMD5Hash();
HA1 = this.HA1Sess;
break;
default: //throw new NotSupportedException("Not supported hash algorithm found in Web Authentication: " + Algorithm);
return string.Empty;
}
// A string of 32 hex digits, which proves that the user knows a password. Set according to the qop value.
string response = string.Empty;
// The server sent QoP-value can be a list of supported methodes(if sent at all - in this case it's null).
// The rfc is not specify that this is a space or comma separeted list. So it can be "auth, auth-int" or "auth auth-int".
// We will first check the longer value("auth-int") then the short one ("auth"). If one matches we will reset the qop to the exact value.
string qop = this.QualityOfProtections != null ? this.QualityOfProtections.TrimAndLower() : null;
if (qop == null)
{
string HA2 = string.Concat(request.MethodType.ToString().ToUpper(), ":", request.CurrentUri.PathAndQuery).CalculateMD5Hash();
response = string.Format("{0}:{1}:{2}", HA1, Nonce, HA2).CalculateMD5Hash();
}
else if (qop.Contains("auth-int"))
{
qop = "auth-int";
byte[] entityBody = request.GetEntityBody();
if (entityBody == null)
entityBody = string.Empty.GetASCIIBytes();
string HA2 = string.Format("{0}:{1}:{2}", request.MethodType.ToString().ToUpper(), request.CurrentUri.PathAndQuery, entityBody.CalculateMD5Hash()).CalculateMD5Hash();
response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash();
}
else if (qop.Contains("auth"))
{
qop = "auth";
string HA2 = string.Concat(request.MethodType.ToString().ToUpper(), ":", request.CurrentUri.PathAndQuery).CalculateMD5Hash();
response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash();
}
else //throw new NotSupportedException("Unrecognized Quality of Protection value found: " + this.QualityOfProtections);
return string.Empty;
string result = string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", cnonce=\"{4}\", response=\"{5}\"",
credentials.UserName, Realm, Nonce, request.Uri.PathAndQuery, cnonce, response);
if (qop != null)
result += String.Concat(", qop=\"", qop, "\", nc=", ncvalue);
if (!string.IsNullOrEmpty(Opaque))
result = String.Concat(result, ", opaque=\"", Opaque, "\"");
return result;
}// end of case "digest":
default:
break;
}
}
catch
{
}
return string.Empty;
}
public bool IsUriProtected(Uri uri)
{
// http://tools.ietf.org/html/rfc2617#section-3.2.1
// An absoluteURI in this list may refer to
// a different server than the one being accessed. The client can use
// this list to determine the set of URIs for which the same
// authentication information may be sent: any URI that has a URI in
// this list as a prefix (after both have been made absolute) may be
// assumed to be in the same protection space. If this directive is
// omitted or its value is empty, the client should assume that the
// protection space consists of all URIs on the responding server.
if (string.CompareOrdinal(uri.Host, this.Uri.Host) != 0)
return false;
string uriStr = uri.ToString();
if (ProtectedUris != null && ProtectedUris.Count > 0)
for (int i = 0; i < ProtectedUris.Count; ++i)
if (uriStr.Contains(ProtectedUris[i]))
return true;
return true;
}
}
}
| |
// 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.Azure.AcceptanceTestsAzureParameterGrouping
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ParameterGroupingOperations operations.
/// </summary>
internal partial class ParameterGroupingOperations : IServiceOperations<AutoRestParameterGroupingTestService>, IParameterGroupingOperations
{
/// <summary>
/// Initializes a new instance of the ParameterGroupingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterGroupingTestService
/// </summary>
public AutoRestParameterGroupingTestService Client { get; private set; }
/// <summary>
/// Post a bunch of required parameters grouped
/// </summary>
/// <param name='parameterGroupingPostRequiredParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParameters parameterGroupingPostRequiredParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameterGroupingPostRequiredParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
}
if (parameterGroupingPostRequiredParameters != null)
{
parameterGroupingPostRequiredParameters.Validate();
}
int body = default(int);
if (parameterGroupingPostRequiredParameters != null)
{
body = parameterGroupingPostRequiredParameters.Body;
}
string customHeader = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostRequiredParameters != null)
{
query = parameterGroupingPostRequiredParameters.Query;
}
string path = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
path = parameterGroupingPostRequiredParameters.Path;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("path", path);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();
_url = _url.Replace("{path}", Uri.EscapeDataString(path));
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(query, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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 AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post a bunch of optional parameters grouped
/// </summary>
/// <param name='parameterGroupingPostOptionalParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostOptionalWithHttpMessagesAsync(ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = default(ParameterGroupingPostOptionalParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string customHeader = default(string);
if (parameterGroupingPostOptionalParameters != null)
{
customHeader = parameterGroupingPostOptionalParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostOptionalParameters != null)
{
query = parameterGroupingPostOptionalParameters.Query;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostOptional", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postOptional").ToString();
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(query, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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 AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters from multiple different parameter groups
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='parameterGroupingPostMultiParamGroupsSecondParamGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMultiParamGroupsWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = default(ParameterGroupingPostMultiParamGroupsSecondParamGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
string headerTwo = default(string);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.HeaderTwo;
}
int? queryTwo = default(int?);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.QueryTwo;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("headerTwo", headerTwo);
tracingParameters.Add("queryTwo", queryTwo);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMultiParamGroups", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postMultipleParameterGroups").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(queryOne, this.Client.SerializationSettings).Trim('"'))));
}
if (queryTwo != null)
{
_queryParameters.Add(string.Format("query-two={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(queryTwo, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (headerTwo != null)
{
if (_httpRequest.Headers.Contains("header-two"))
{
_httpRequest.Headers.Remove("header-two");
}
_httpRequest.Headers.TryAddWithoutValidation("header-two", headerTwo);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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 AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters with a shared parameter group object
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostSharedParameterGroupObjectWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSharedParameterGroupObject", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/sharedParameterGroupObject").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(queryOne, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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 AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Analysis;
using Lucene.Net.Util;
using NUnit.Framework;
namespace Lucene.Net.Analysis
{
public class ChainedFilterTest : Lucene.Net.TestCase
{
public static int MAX = 500;
private RAMDirectory directory;
private IndexSearcher searcher;
private Query query;
// private DateFilter dateFilter; DateFilter was deprecated and removed
private TermRangeFilter dateFilter;
private QueryWrapperFilter bobFilter;
private QueryWrapperFilter sueFilter;
[SetUp]
public void SetUp()
{
directory = new RAMDirectory();
IndexWriter writer =
new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED);
DateTime cal = new DateTime(1041397200000L * TimeSpan.TicksPerMillisecond); // 2003 January 01
for (int i = 0; i < MAX; i++)
{
Document doc = new Document();
doc.Add(new Field("key", "" + (i + 1), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("owner", (i < MAX / 2) ? "bob" : "sue", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("date", (cal.Ticks / TimeSpan.TicksPerMillisecond).ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.AddDocument(doc);
cal.AddMilliseconds(1);
}
writer.Close();
searcher = new IndexSearcher(directory, true);
// query for everything to make life easier
BooleanQuery bq = new BooleanQuery();
bq.Add(new TermQuery(new Term("owner", "bob")), BooleanClause.Occur.SHOULD);
bq.Add(new TermQuery(new Term("owner", "sue")), BooleanClause.Occur.SHOULD);
query = bq;
// date filter matches everything too
//Date pastTheEnd = parseDate("2099 Jan 1");
// dateFilter = DateFilter.Before("date", pastTheEnd);
// just treat dates as strings and select the whole range for now...
dateFilter = new TermRangeFilter("date", "", "ZZZZ", true, true);
bobFilter = new QueryWrapperFilter(
new TermQuery(new Term("owner", "bob")));
sueFilter = new QueryWrapperFilter(
new TermQuery(new Term("owner", "sue")));
}
private ChainedFilter GetChainedFilter(Filter[] chain, ChainedFilter.Logic[] logic)
{
if (logic == null)
{
return new ChainedFilter(chain);
}
else
{
return new ChainedFilter(chain, logic);
}
}
private ChainedFilter GetChainedFilter(Filter[] chain, ChainedFilter.Logic logic)
{
return new ChainedFilter(chain, logic);
}
[Test]
public void TestSingleFilter()
{
ChainedFilter chain = GetChainedFilter(new Filter[] { dateFilter }, null);
int numHits = searcher.Search(query, chain, 1000).TotalHits;
Assert.AreEqual(MAX, numHits);
chain = new ChainedFilter(new Filter[] { bobFilter });
numHits = searcher.Search(query, chain, 1000).TotalHits;
Assert.AreEqual(MAX / 2, numHits);
chain = GetChainedFilter(new Filter[] { bobFilter }, new ChainedFilter.Logic[] { ChainedFilter.Logic.AND });
TopDocs hits = searcher.Search(query, chain, 1000);
numHits = hits.TotalHits;
Assert.AreEqual(MAX / 2, numHits);
Assert.AreEqual("bob", searcher.Doc(hits.ScoreDocs[0].doc).Get("owner"));
chain = GetChainedFilter(new Filter[] { bobFilter }, new ChainedFilter.Logic[] { ChainedFilter.Logic.ANDNOT });
hits = searcher.Search(query, chain, 1000);
numHits = hits.TotalHits;
Assert.AreEqual(MAX / 2, numHits);
Assert.AreEqual("sue", searcher.Doc(hits.ScoreDocs[0].doc).Get("owner"));
}
[Test]
public void TestOR()
{
ChainedFilter chain = GetChainedFilter(
new Filter[] { sueFilter, bobFilter }, null);
int numHits = searcher.Search(query, chain, 1000).TotalHits;
Assert.AreEqual(MAX, numHits, "OR matches all");
}
[Test]
public void TestAND()
{
ChainedFilter chain = GetChainedFilter(
new Filter[] { dateFilter, bobFilter }, ChainedFilter.Logic.AND);
TopDocs hits = searcher.Search(query, chain, 1000);
Assert.AreEqual(MAX / 2, hits.TotalHits, "AND matches just bob");
Assert.AreEqual("bob", searcher.Doc(hits.ScoreDocs[0].doc).Get("owner"));
}
[Test]
public void TestXOR()
{
ChainedFilter chain = GetChainedFilter(
new Filter[] { dateFilter, bobFilter }, ChainedFilter.Logic.XOR);
TopDocs hits = searcher.Search(query, chain, 1000);
Assert.AreEqual(MAX / 2, hits.TotalHits, "XOR matches sue");
Assert.AreEqual("sue", searcher.Doc(hits.ScoreDocs[0].doc).Get("owner"));
}
[Test]
public void TestANDNOT()
{
ChainedFilter chain = GetChainedFilter(
new Filter[] { dateFilter, sueFilter },
new ChainedFilter.Logic[] { ChainedFilter.Logic.AND, ChainedFilter.Logic.ANDNOT });
TopDocs hits = searcher.Search(query, chain, 1000);
Assert.AreEqual(MAX / 2, hits.TotalHits, "ANDNOT matches just bob");
Assert.AreEqual("bob", searcher.Doc(hits.ScoreDocs[0].doc).Get("owner"));
chain = GetChainedFilter(
new Filter[] { bobFilter, bobFilter },
new ChainedFilter.Logic[] { ChainedFilter.Logic.ANDNOT, ChainedFilter.Logic.ANDNOT });
hits = searcher.Search(query, chain, 1000);
Assert.AreEqual(MAX / 2, hits.TotalHits, "ANDNOT bob ANDNOT bob matches all sues");
Assert.AreEqual("sue", searcher.Doc(hits.ScoreDocs[0].doc).Get("owner"));
}
/*
private Date parseDate(String s) throws ParseException {
return new SimpleDateFormat("yyyy MMM dd", Locale.US).parse(s);
}
*/
[Test]
public void TestWithCachingFilter()
{
Directory dir = new RAMDirectory();
Analyzer analyzer = new WhitespaceAnalyzer();
IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
writer.Close();
Searcher searcher = new IndexSearcher(dir, true);
Query query = new TermQuery(new Term("none", "none"));
QueryWrapperFilter queryFilter = new QueryWrapperFilter(query);
CachingWrapperFilter cachingFilter = new CachingWrapperFilter(queryFilter);
searcher.Search(query, cachingFilter, 1);
CachingWrapperFilter cachingFilter2 = new CachingWrapperFilter(queryFilter);
Filter[] chain = new Filter[2];
chain[0] = cachingFilter;
chain[1] = cachingFilter2;
ChainedFilter cf = new ChainedFilter(chain);
// throws java.lang.ClassCastException: org.apache.lucene.util.OpenBitSet cannot be cast to java.util.BitSet
searcher.Search(new MatchAllDocsQuery(), cf, 1);
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Text;
using Encog.Engine.Network.Activation;
using Encog.MathUtil.Randomize;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Neural.Flat;
using Encog.Neural.Networks.Layers;
using Encog.Neural.Networks.Structure;
using Encog.Util;
using Encog.Util.CSV;
using Encog.Util.Simple;
namespace Encog.Neural.Networks
{
/// <summary>
/// This class implements a neural network. This class works in conjunction the
/// Layer classes. Layers are added to the BasicNetwork to specify the structure
/// of the neural network.
/// The first layer added is the input layer, the final layer added is the output
/// layer. Any layers added between these two layers are the hidden layers.
/// The network structure is stored in the structure member. It is important to
/// call:
/// network.getStructure().finalizeStructure();
/// Once the neural network has been completely constructed.
/// </summary>
///
[Serializable]
public class BasicNetwork : BasicML, IContainsFlat, IMLContext,
IMLRegression, IMLEncodable, IMLResettable, IMLClassification, IMLError
{
/// <summary>
/// Tag used for the connection limit.
/// </summary>
///
public const String TagLimit = "CONNECTION_LIMIT";
/// <summary>
/// The default connection limit.
/// </summary>
///
public const double DefaultConnectionLimit = 0.0000000001d;
/// <summary>
/// The property for connection limit.
/// </summary>
///
public const String TagConnectionLimit = "connectionLimit";
/// <summary>
/// The property for begin training.
/// </summary>
///
public const String TagBeginTraining = "beginTraining";
/// <summary>
/// The property for context target offset.
/// </summary>
///
public const String TagContextTargetOffset = "contextTargetOffset";
/// <summary>
/// The property for context target size.
/// </summary>
///
public const String TagContextTargetSize = "contextTargetSize";
/// <summary>
/// The property for end training.
/// </summary>
///
public const String TagEndTraining = "endTraining";
/// <summary>
/// The property for has context.
/// </summary>
///
public const String TagHasContext = "hasContext";
/// <summary>
/// The property for layer counts.
/// </summary>
///
public const String TagLayerCounts = "layerCounts";
/// <summary>
/// The property for layer feed counts.
/// </summary>
///
public const String TagLayerFeedCounts = "layerFeedCounts";
/// <summary>
/// The property for layer index.
/// </summary>
///
public const String TagLayerIndex = "layerIndex";
/// <summary>
/// The property for weight index.
/// </summary>
///
public const String TagWeightIndex = "weightIndex";
/// <summary>
/// The property for bias activation.
/// </summary>
///
public const String TagBiasActivation = "biasActivation";
/// <summary>
/// The property for layer context count.
/// </summary>
///
public const String TagLayerContextCount = "layerContextCount";
/// <summary>
/// Holds the structure of the network. This keeps the network from having to
/// constantly lookup layers and synapses.
/// </summary>
///
private readonly NeuralStructure _structure;
/// <summary>
/// Construct an empty neural network.
/// </summary>
///
public BasicNetwork()
{
_structure = new NeuralStructure(this);
}
/// <value>The layer count.</value>
public int LayerCount
{
get
{
_structure.RequireFlat();
return _structure.Flat.LayerCounts.Length;
}
}
/// <value>Get the structure of the neural network. The structure allows you
/// to quickly obtain synapses and layers without traversing the
/// network.</value>
public NeuralStructure Structure
{
get { return _structure; }
}
/// <summary>
/// Sets the bias activation for every layer that supports bias. Make sure
/// that the network structure has been finalized before calling this method.
/// </summary>
public double BiasActivation
{
set
{
// first, see what mode we are on. If the network has not been
// finalized, set the layers
if (_structure.Flat == null)
{
foreach (ILayer layer in _structure.Layers)
{
if (layer.HasBias())
{
layer.BiasActivation = value;
}
}
}
else
{
for (int i = 0; i < LayerCount; i++)
{
if (IsLayerBiased(i))
{
SetLayerBiasActivation(i, value);
}
}
}
}
}
#region ContainsFlat Members
/// <inheritdoc/>
public FlatNetwork Flat
{
get { return Structure.Flat; }
}
#endregion
#region MLClassification Members
/// <inheritdoc/>
public int Classify(IMLData input)
{
return Winner(input);
}
#endregion
#region MLContext Members
/// <summary>
/// Clear any data from any context layers.
/// </summary>
///
public void ClearContext()
{
if (_structure.Flat != null)
{
_structure.Flat.ClearContext();
}
}
#endregion
#region MLEncodable Members
/// <inheritdoc/>
public void DecodeFromArray(double[] encoded)
{
_structure.RequireFlat();
double[] weights = _structure.Flat.Weights;
if (weights.Length != encoded.Length)
{
throw new NeuralNetworkError(
"Size mismatch, encoded array should be of length "
+ weights.Length);
}
EngineArray.ArrayCopy(encoded, weights);
}
/// <inheritdoc/>
public int EncodedArrayLength()
{
_structure.RequireFlat();
return _structure.Flat.EncodeLength;
}
/// <inheritdoc/>
public void EncodeToArray(double[] encoded)
{
_structure.RequireFlat();
double[] weights = _structure.Flat.Weights;
if (weights.Length != encoded.Length)
{
throw new NeuralNetworkError(
"Size mismatch, encoded array should be of length "
+ weights.Length);
}
EngineArray.ArrayCopy(weights, encoded);
}
#endregion
#region MLError Members
/// <summary>
/// Calculate the error for this neural network.
/// </summary>
///
/// <param name="data">The training set.</param>
/// <returns>The error percentage.</returns>
public double CalculateError(IMLDataSet data)
{
return EncogUtility.CalculateRegressionError(this, data);
}
#endregion
#region MLRegression Members
/// <summary>
/// Compute the output for a given input to the neural network.
/// </summary>
///
/// <param name="input">The input to the neural network.</param>
/// <returns>The output from the neural network.</returns>
public IMLData Compute(IMLData input)
{
try
{
var output = new double[_structure.Flat.OutputCount];
_structure.Flat.Compute(input, output);
return new BasicMLData(output, false);
}
catch (IndexOutOfRangeException ex)
{
throw new NeuralNetworkError(
"Index exception: there was likely a mismatch between layer sizes, or the size of the input presented to the network.",
ex);
}
}
/// <inheritdoc/>
public virtual int InputCount
{
get
{
_structure.RequireFlat();
return Structure.Flat.InputCount;
}
}
/// <inheritdoc/>
public virtual int OutputCount
{
get
{
_structure.RequireFlat();
return Structure.Flat.OutputCount;
}
}
#endregion
#region MLResettable Members
/// <summary>
/// Reset the weight matrix and the bias values. This will use a
/// Nguyen-Widrow randomizer with a range between -1 and 1. If the network
/// does not have an input, output or hidden layers, then Nguyen-Widrow
/// cannot be used and a simple range randomize between -1 and 1 will be
/// used.
/// </summary>
///
public void Reset()
{
if (LayerCount < 3)
{
(new RangeRandomizer(-1, 1)).Randomize(this);
}
else
{
(new NguyenWidrowRandomizer()).Randomize(this);
}
}
/// <summary>
/// Reset the weight matrix and the bias values. This will use a
/// Nguyen-Widrow randomizer with a range between -1 and 1. If the network
/// does not have an input, output or hidden layers, then Nguyen-Widrow
/// cannot be used and a simple range randomize between -1 and 1 will be
/// used.
/// Use the specified seed.
/// </summary>
///
public void Reset(int seed)
{
Reset();
}
#endregion
/// <summary>
/// Add a layer to the neural network. If there are no layers added this
/// layer will become the input layer. This function automatically updates
/// both the input and output layer references.
/// </summary>
///
/// <param name="layer">The layer to be added to the network.</param>
public void AddLayer(ILayer layer)
{
layer.Network = this;
_structure.Layers.Add(layer);
}
/// <summary>
/// Add to a weight.
/// </summary>
///
/// <param name="fromLayer">The from layer.</param>
/// <param name="fromNeuron">The from neuron.</param>
/// <param name="toNeuron">The to neuron.</param>
/// <param name="v">The value to add.</param>
public void AddWeight(int fromLayer, int fromNeuron,
int toNeuron, double v)
{
double old = GetWeight(fromLayer, fromNeuron, toNeuron);
SetWeight(fromLayer, fromNeuron, toNeuron, old + v);
}
/// <summary>
/// Calculate the total number of neurons in the network across all layers.
/// </summary>
///
/// <returns>The neuron count.</returns>
public int CalculateNeuronCount()
{
int result = 0;
foreach (ILayer layer in _structure.Layers)
{
result += layer.NeuronCount;
}
return result;
}
/// <summary>
/// Return a clone of this neural network. Including structure, weights and
/// bias values. This is a deep copy.
/// </summary>
///
/// <returns>A cloned copy of the neural network.</returns>
public Object Clone()
{
var result = (BasicNetwork) ObjectCloner.DeepCopy(this);
return result;
}
/// <summary>
/// Compute the output for this network.
/// </summary>
///
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
public void Compute(double[] input, double[] output)
{
var input2 = new BasicMLData(input);
IMLData output2 = Compute(input2);
output2.CopyTo(output, 0, output2.Count);
}
/// <returns>The weights as a comma separated list.</returns>
public String DumpWeights()
{
var result = new StringBuilder();
NumberList.ToList(CSVFormat.EgFormat, result, _structure.Flat.Weights);
return result.ToString();
}
/// <summary>
/// Enable, or disable, a connection.
/// </summary>
///
/// <param name="fromLayer">The layer that contains the from neuron.</param>
/// <param name="fromNeuron">The source neuron.</param>
/// <param name="toNeuron">The target connection.</param>
/// <param name="enable">True to enable, false to disable.</param>
public void EnableConnection(int fromLayer,
int fromNeuron, int toNeuron, bool enable)
{
double v = GetWeight(fromLayer, fromNeuron, toNeuron);
if (enable)
{
if (!_structure.ConnectionLimited)
{
return;
}
if (Math.Abs(v) < _structure.ConnectionLimit)
{
SetWeight(fromLayer, fromNeuron, toNeuron,
RangeRandomizer.Randomize(-1, 1));
}
}
else
{
if (!_structure.ConnectionLimited)
{
SetProperty(TagLimit,
DefaultConnectionLimit);
_structure.UpdateProperties();
}
SetWeight(fromLayer, fromNeuron, toNeuron, 0);
}
}
/// <summary>
/// Compare the two neural networks. For them to be equal they must be of the
/// same structure, and have the same matrix values.
/// </summary>
///
/// <param name="other">The other neural network.</param>
/// <returns>True if the two networks are equal.</returns>
public bool Equals(BasicNetwork other)
{
return Equals(other, EncogFramework.DefaultPrecision);
}
/// <summary>
/// Determine if this neural network is equal to another. Equal neural
/// networks have the same weight matrix and bias values, within a specified
/// precision.
/// </summary>
///
/// <param name="other">The other neural network.</param>
/// <param name="precision">The number of decimal places to compare to.</param>
/// <returns>True if the two neural networks are equal.</returns>
public bool Equals(BasicNetwork other, int precision)
{
return NetworkCODEC.Equals(this, other, precision);
}
/// <summary>
/// Get the activation function for the specified layer.
/// </summary>
///
/// <param name="layer">The layer.</param>
/// <returns>The activation function.</returns>
public IActivationFunction GetActivation(int layer)
{
_structure.RequireFlat();
int layerNumber = LayerCount - layer - 1;
return _structure.Flat.ActivationFunctions[layerNumber];
}
/// <summary>
/// Get the bias activation for the specified layer.
/// </summary>
///
/// <param name="l">The layer.</param>
/// <returns>The bias activation.</returns>
public double GetLayerBiasActivation(int l)
{
if (!IsLayerBiased(l))
{
throw new NeuralNetworkError(
"Error, the specified layer does not have a bias: " + l);
}
_structure.RequireFlat();
int layerNumber = LayerCount - l - 1;
int layerOutputIndex = _structure.Flat.LayerIndex[layerNumber];
int count = _structure.Flat.LayerCounts[layerNumber];
return _structure.Flat.LayerOutput[layerOutputIndex
+ count - 1];
}
/// <summary>
/// Get the neuron count.
/// </summary>
///
/// <param name="l">The layer.</param>
/// <returns>The neuron count.</returns>
public int GetLayerNeuronCount(int l)
{
_structure.RequireFlat();
int layerNumber = LayerCount - l - 1;
return _structure.Flat.LayerFeedCounts[layerNumber];
}
/// <summary>
/// Get the layer output for the specified neuron.
/// </summary>
///
/// <param name="layer">The layer.</param>
/// <param name="neuronNumber">The neuron number.</param>
/// <returns>The output from the last call to compute.</returns>
public double GetLayerOutput(int layer, int neuronNumber)
{
_structure.RequireFlat();
int layerNumber = LayerCount - layer - 1;
int index = _structure.Flat.LayerIndex[layerNumber]
+ neuronNumber;
double[] output = _structure.Flat.LayerOutput;
if (index >= output.Length)
{
throw new NeuralNetworkError("The layer index: " + index
+ " specifies an output index larger than the network has.");
}
return output[index];
}
/// <summary>
/// Get the total (including bias and context) neuron cont for a layer.
/// </summary>
///
/// <param name="l">The layer.</param>
/// <returns>The count.</returns>
public int GetLayerTotalNeuronCount(int l)
{
_structure.RequireFlat();
int layerNumber = LayerCount - l - 1;
return _structure.Flat.LayerCounts[layerNumber];
}
/// <summary>
/// Get the weight between the two layers.
/// </summary>
///
/// <param name="fromLayer">The from layer.</param>
/// <param name="fromNeuron">The from neuron.</param>
/// <param name="toNeuron">The to neuron.</param>
/// <returns>The weight value.</returns>
public double GetWeight(int fromLayer, int fromNeuron,
int toNeuron)
{
_structure.RequireFlat();
ValidateNeuron(fromLayer, fromNeuron);
ValidateNeuron(fromLayer + 1, toNeuron);
int fromLayerNumber = LayerCount - fromLayer - 1;
int toLayerNumber = fromLayerNumber - 1;
if (toLayerNumber < 0)
{
throw new NeuralNetworkError(
"The specified layer is not connected to another layer: "
+ fromLayer);
}
int weightBaseIndex = _structure.Flat.WeightIndex[toLayerNumber];
int count = _structure.Flat.LayerCounts[fromLayerNumber];
int weightIndex = weightBaseIndex + fromNeuron
+ (toNeuron*count);
return _structure.Flat.Weights[weightIndex];
}
/// <summary>
/// Generate a hash code.
/// </summary>
///
/// <returns>THe hash code.</returns>
public override sealed int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Determine if the specified connection is enabled.
/// </summary>
///
/// <param name="layer">The layer to check.</param>
/// <param name="fromNeuron">The source neuron.</param>
/// <param name="toNeuron">THe target neuron.</param>
/// <returns>True, if the connection is enabled, false otherwise.</returns>
public bool IsConnected(int layer, int fromNeuron,
int toNeuron)
{
/*
* if (!this.structure.isConnectionLimited()) { return true; } final
* double value = synapse.getMatrix().get(fromNeuron, toNeuron);
*
* return (Math.abs(value) > this.structure.getConnectionLimit());
*/
return false;
}
/// <summary>
/// Determine if the specified layer is biased.
/// </summary>
///
/// <param name="l">The layer number.</param>
/// <returns>True, if the layer is biased.</returns>
public bool IsLayerBiased(int l)
{
_structure.RequireFlat();
int layerNumber = LayerCount - l - 1;
return _structure.Flat.LayerCounts[layerNumber] != _structure.Flat.LayerFeedCounts[layerNumber];
}
/// <summary>
/// Set the bias activation for the specified layer.
/// </summary>
///
/// <param name="l">The layer to use.</param>
/// <param name="value_ren">The bias activation.</param>
public void SetLayerBiasActivation(int l, double v)
{
if (!IsLayerBiased(l))
{
throw new NeuralNetworkError(
"Error, the specified layer does not have a bias: " + l);
}
_structure.RequireFlat();
int layerNumber = LayerCount - l - 1;
int layerOutputIndex = _structure.Flat.LayerIndex[layerNumber];
int count = _structure.Flat.LayerCounts[layerNumber];
_structure.Flat.LayerOutput[layerOutputIndex + count - 1] = v;
}
/// <summary>
/// Set the weight between the two specified neurons.
/// </summary>
///
/// <param name="fromLayer">The from layer.</param>
/// <param name="fromNeuron">The from neuron.</param>
/// <param name="toNeuron">The to neuron.</param>
/// <param name="v">The to value.</param>
public void SetWeight(int fromLayer, int fromNeuron,
int toNeuron, double v)
{
_structure.RequireFlat();
int fromLayerNumber = LayerCount - fromLayer - 1;
int toLayerNumber = fromLayerNumber - 1;
if (toLayerNumber < 0)
{
throw new NeuralNetworkError(
"The specified layer is not connected to another layer: "
+ fromLayer);
}
int weightBaseIndex = _structure.Flat.WeightIndex[toLayerNumber];
int count = _structure.Flat.LayerCounts[fromLayerNumber];
int weightIndex = weightBaseIndex + fromNeuron
+ (toNeuron*count);
_structure.Flat.Weights[weightIndex] = v;
}
/// <summary>
///
/// </summary>
///
public override sealed String ToString()
{
var builder = new StringBuilder();
builder.Append("[BasicNetwork: Layers=");
int layers = _structure.Flat==null ? _structure.Layers.Count : _structure.Flat.LayerCounts.Length;
builder.Append(layers);
builder.Append("]");
return builder.ToString();
}
/// <summary>
///
/// </summary>
///
public override sealed void UpdateProperties()
{
_structure.UpdateProperties();
}
/// <summary>
/// Validate the the specified targetLayer and neuron are valid.
/// </summary>
///
/// <param name="targetLayer">The target layer.</param>
/// <param name="neuron">The target neuron.</param>
public void ValidateNeuron(int targetLayer, int neuron)
{
if ((targetLayer < 0) || (targetLayer >= LayerCount))
{
throw new NeuralNetworkError("Invalid layer count: " + targetLayer);
}
if ((neuron < 0) || (neuron >= GetLayerTotalNeuronCount(targetLayer)))
{
throw new NeuralNetworkError("Invalid neuron number: " + neuron);
}
}
/// <summary>
/// Determine the winner for the specified input. This is the number of the
/// winning neuron.
/// </summary>
///
/// <param name="input">The input patter to present to the neural network.</param>
/// <returns>The winning neuron.</returns>
public int Winner(IMLData input)
{
IMLData output = Compute(input);
return EngineArray.MaxIndex(output);
}
}
}
| |
/// OSVR-Unity Connection
///
/// http://sensics.com/osvr
///
/// <copyright>
/// Copyright 2014 Sensics, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </copyright>
/// <summary>
/// Author: Bob Berkebile
/// Email: bob@bullyentertainment.com || bobb@pixelplacement.com
/// </summary>
using UnityEngine;
using System.Collections;
namespace OSVR
{
namespace Unity
{
public enum ViewMode { stereo, mono };
[RequireComponent(typeof(Camera))]
[RequireComponent(typeof(DisplayInterface))]
public class VRHead : MonoBehaviour
{
#region Public Variables
public ViewMode viewMode;
[Range(0, 1)]
public float stereoAmount;
public float maxStereo = .03f;
public Camera Camera { get { return _camera; } set { _camera = value; } }
#endregion
#region Private Variables
private VREye _leftEye;
private VREye _rightEye;
private float _previousStereoAmount;
private ViewMode _previousViewMode;
private Camera _camera;
private DeviceDescriptor _deviceDescriptor;
private OsvrDistortion _distortionEffect;
private bool _initDisplayInterface = false;
#endregion
#region Init
void Start()
{
Init();
CatalogEyes();
_distortionEffect = GetComponent<OsvrDistortion>();
if (_distortionEffect != null)
{
_distortionEffect.enabled = (viewMode == ViewMode.mono);
}
//update VRHead with info from the display interface if it has been initialized
//it might not be initialized if it is still loading/parsing a display json file
//in that case, we will try to initialize asap in the update function
if (GetComponent<DisplayInterface>().Initialized)
{
UpdateDisplayInterface();
}
}
#endregion
#region Loop
void Update()
{
if(!_initDisplayInterface && GetComponent<DisplayInterface>().Initialized)
{
UpdateDisplayInterface();
}
UpdateStereoAmount();
UpdateViewMode();
}
#endregion
#region Public Methods
#endregion
#region Private Methods
private void UpdateDisplayInterface()
{
GetDeviceDescription();
MatchEyes(); //copy camera properties to each eye
//rotate each eye based on overlap percent, must do this after match eyes
if (_deviceDescriptor != null)
{
SetEyeRotation(_deviceDescriptor.OverlapPercent, _deviceDescriptor.MonocularHorizontal);
SetEyeRoll(_deviceDescriptor.LeftRoll, _deviceDescriptor.RightRoll);
}
_initDisplayInterface = true;
}
void UpdateViewMode()
{
if (Time.realtimeSinceStartup < 100 || _previousViewMode != viewMode)
{
switch (viewMode)
{
case ViewMode.mono:
Camera.enabled = true;
_leftEye.Camera.enabled = false;
_rightEye.Camera.enabled = false;
break;
case ViewMode.stereo:
Camera.enabled = false;
_leftEye.Camera.enabled = true;
_rightEye.Camera.enabled = true;
break;
}
}
_previousViewMode = viewMode;
}
void UpdateStereoAmount()
{
if (stereoAmount != _previousStereoAmount)
{
stereoAmount = Mathf.Clamp(stereoAmount, 0, 1);
_rightEye.cachedTransform.localPosition = Vector3.right * (maxStereo * stereoAmount);
_leftEye.cachedTransform.localPosition = Vector3.left * (maxStereo * stereoAmount);
_previousStereoAmount = stereoAmount;
}
}
//this function finds and initializes each eye
void CatalogEyes()
{
foreach (VREye currentEye in GetComponentsInChildren<VREye>())
{
//catalog:
switch (currentEye.eye)
{
case Eye.left:
_leftEye = currentEye;
break;
case Eye.right:
_rightEye = currentEye;
break;
}
}
}
//this function matches the camera on each eye to the camera on the head
void MatchEyes()
{
foreach (VREye currentEye in GetComponentsInChildren<VREye>())
{
//match:
currentEye.MatchCamera(Camera);
}
}
void Init()
{
if (Camera == null)
{
if ((Camera = GetComponent<Camera>()) == null)
{
Camera = gameObject.AddComponent<Camera>();
}
}
//VR should never timeout the screen:
Screen.sleepTimeout = SleepTimeout.NeverSleep;
//60 FPS whenever possible:
Application.targetFrameRate = 60;
_initDisplayInterface = false;
}
/// <summary>
/// GetDeviceDescription: Get a Description of the HMD and apply appropriate settings
///
/// </summary>
private void GetDeviceDescription()
{
_deviceDescriptor = GetComponent<DisplayInterface>().GetDeviceDescription();
if (_deviceDescriptor != null)
{
Debug.Log(_deviceDescriptor.ToString());
switch (_deviceDescriptor.DisplayMode)
{
case "full_screen":
viewMode = ViewMode.mono;
break;
case "horz_side_by_side":
case "vert_side_by_side":
default:
viewMode = ViewMode.stereo;
break;
}
stereoAmount = Mathf.Clamp(_deviceDescriptor.OverlapPercent, 0, 100);
SetResolution(_deviceDescriptor.Width, _deviceDescriptor.Height); //set resolution before FOV
Camera.fieldOfView = Mathf.Clamp(_deviceDescriptor.MonocularVertical, 0, 180); //unity camera FOV is vertical
SetDistortion(_deviceDescriptor.K1Red, _deviceDescriptor.K1Green, _deviceDescriptor.K1Blue,
_deviceDescriptor.CenterProjX, _deviceDescriptor.CenterProjY); //set distortion shader
//if the view needs to be rotated 180 degrees, create a parent game object that is flipped 180 degrees on the z axis.
if (_deviceDescriptor.Rotate180 > 0)
{
GameObject vrHeadParent = new GameObject();
vrHeadParent.name = this.transform.name + "_parent";
vrHeadParent.transform.position = this.transform.position;
vrHeadParent.transform.rotation = this.transform.rotation;
if (this.transform.parent != null)
{
vrHeadParent.transform.parent = this.transform.parent;
}
this.transform.parent = vrHeadParent.transform;
vrHeadParent.transform.Rotate(0, 0, 180, Space.Self);
}
}
}
private void SetDistortion(float k1Red, float k1Green, float k1Blue, float centerProjX, float centerProjY)
{
if(_distortionEffect != null)
{
_distortionEffect.k1Red = k1Red;
_distortionEffect.k1Green = k1Green;
_distortionEffect.k1Blue = k1Blue;
_distortionEffect.fullCenter = new Vector2(centerProjX, centerProjY);
}
}
//Set the Screen Resolution
private void SetResolution(int width, int height)
{
//set the resolution
Screen.SetResolution(width, height, true);
#if UNITY_EDITOR
UnityEditor.PlayerSettings.defaultScreenWidth = width;
UnityEditor.PlayerSettings.defaultScreenHeight = height;
UnityEditor.PlayerSettings.defaultIsFullScreen = true;
#endif
}
//rotate each eye based on overlap percent and horizontal FOV
//Formula: ((OverlapPercent/100) * hFOV)/2
private void SetEyeRotation(float overlapPercent, float horizontalFov)
{
float overlap = overlapPercent* .01f * horizontalFov * 0.5f;
//with a 90 degree FOV with 100% overlap, the eyes should not be rotated
//compare rotationY with half of FOV
float halfFOV = horizontalFov * 0.5f;
float rotateYAmount = Mathf.Abs(overlap - halfFOV);
foreach (VREye currentEye in GetComponentsInChildren<VREye>())
{
switch (currentEye.eye)
{
case Eye.left:
_leftEye.SetEyeRotationY(-rotateYAmount);
break;
case Eye.right:
_rightEye.SetEyeRotationY(rotateYAmount);
break;
}
}
}
//rotate each eye on the z axis by the specified amount, in degrees
private void SetEyeRoll(float leftRoll, float rightRoll)
{
foreach (VREye currentEye in GetComponentsInChildren<VREye>())
{
switch (currentEye.eye)
{
case Eye.left:
_leftEye.SetEyeRoll(leftRoll);
break;
case Eye.right:
_rightEye.SetEyeRoll(rightRoll);
break;
}
}
}
#endregion
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorPublisher.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Threading;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Reactive.Streams;
namespace Akka.Streams.Actors
{
#region Internal messages
public sealed class Subscribe<T> : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
public readonly ISubscriber<T> Subscriber;
public Subscribe(ISubscriber<T> subscriber)
{
Subscriber = subscriber;
}
}
[Serializable]
public enum LifecycleState
{
PreSubscriber,
Active,
Canceled,
Completed,
CompleteThenStop,
ErrorEmitted
}
#endregion
public interface IActorPublisherMessage: IDeadLetterSuppression { }
/// <summary>
/// This message is delivered to the <see cref="ActorPublisher{T}"/> actor when the stream
/// subscriber requests more elements.
/// </summary>
[Serializable]
public sealed class Request : IActorPublisherMessage
{
public readonly long Count;
public Request(long count)
{
Count = count;
}
}
/// <summary>
/// This message is delivered to the <see cref="ActorPublisher{T}"/> actor when the stream
/// subscriber cancels the subscription.
/// </summary>
[Serializable]
public sealed class Cancel : IActorPublisherMessage
{
public static readonly Cancel Instance = new Cancel();
private Cancel() { }
}
/// <summary>
/// This message is delivered to the <see cref="ActorPublisher{T}"/> actor in order to signal
/// the exceeding of an subscription timeout. Once the actor receives this message, this
/// publisher will already be in cancelled state, thus the actor should clean-up and stop itself.
/// </summary>
[Serializable]
public sealed class SubscriptionTimeoutExceeded : IActorPublisherMessage
{
public static readonly SubscriptionTimeoutExceeded Instance = new SubscriptionTimeoutExceeded();
private SubscriptionTimeoutExceeded() { }
}
/// <summary>
/// <para>
/// Extend this actor to make it a stream publisher that keeps track of the subscription life cycle and
/// requested elements.
/// </para>
/// <para>
/// Create a <see cref="IPublisher{T}"/> backed by this actor with <see cref="ActorPublisher.Create{T}"/>.
/// </para>
/// <para>
/// It can be attached to a <see cref="ISubscriber{T}"/> or be used as an input source for a
/// <see cref="IFlow{T,TMat}"/>. You can only attach one subscriber to this publisher.
/// </para>
/// <para>
/// The life cycle state of the subscription is tracked with the following boolean members:
/// <see cref="IsActive"/>, <see cref="IsCompleted"/>, <see cref="IsErrorEmitted"/>,
/// and <see cref="IsCanceled"/>.
/// </para>
/// <para>
/// You send elements to the stream by calling <see cref="OnNext"/>. You are allowed to send as many
/// elements as have been requested by the stream subscriber. This amount can be inquired with
/// <see cref="TotalDemand"/>. It is only allowed to use <see cref="OnNext"/> when <see cref="IsActive"/>
/// <see cref="TotalDemand"/> > 0, otherwise <see cref="OnNext"/> will throw
/// <see cref="IllegalStateException"/>.
/// </para>
/// <para>
/// When the stream subscriber requests more elements the <see cref="Request"/> message
/// is delivered to this actor, and you can act on that event. The <see cref="TotalDemand"/>
/// is updated automatically.
/// </para>
/// <para>
/// When the stream subscriber cancels the subscription the <see cref="Cancel"/> message
/// is delivered to this actor. After that subsequent calls to <see cref="OnNext"/> will be ignored.
/// </para>
/// <para>
/// You can complete the stream by calling <see cref="OnComplete"/>. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// You can terminate the stream with failure by calling <see cref="OnError"/>. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// If you suspect that this <see cref="ActorPublisher{T}"/> may never get subscribed to,
/// you can override the <see cref="SubscriptionTimeout"/> method to provide a timeout after which
/// this Publisher should be considered canceled. The actor will be notified when
/// the timeout triggers via an <see cref="SubscriptionTimeoutExceeded"/> message and MUST then
/// perform cleanup and stop itself.
/// </para>
/// <para>
/// If the actor is stopped the stream will be completed, unless it was not already terminated with
/// failure, completed or canceled.
/// </para>
/// </summary>
public abstract class ActorPublisher<T> : ActorBase
{
private readonly ActorPublisherState _state = ActorPublisherState.Instance.Apply(Context.System);
private long _demand;
private LifecycleState _lifecycleState = LifecycleState.PreSubscriber;
private ISubscriber<T> _subscriber;
private ICancelable _scheduledSubscriptionTimeout = NoopSubscriptionTimeout.Instance;
// case and stop fields are used only when combined with LifecycleState.ErrorEmitted
private OnErrorBlock _onError;
protected ActorPublisher()
{
SubscriptionTimeout = Timeout.InfiniteTimeSpan;
}
/// <summary>
/// Subscription timeout after which this actor will become Canceled and reject any incoming "late" subscriber.
///
/// The actor will receive an <see cref="SubscriptionTimeoutExceeded"/> message upon which it
/// MUST react by performing all necessary cleanup and stopping itself.
///
/// Use this feature in order to avoid leaking actors when you suspect that this Publisher may never get subscribed to by some Subscriber.
/// </summary>
/// <summary>
/// <para>
/// Subscription timeout after which this actor will become Canceled and reject any incoming "late" subscriber.
/// </para>
/// <para>
/// The actor will receive an <see cref="SubscriptionTimeoutExceeded"/> message upon which it
/// MUST react by performing all necessary cleanup and stopping itself.
/// </para>
/// <para>
/// Use this feature in order to avoid leaking actors when you suspect that this Publisher
/// may never get subscribed to by some Subscriber.
/// </para>
/// </summary>
public TimeSpan SubscriptionTimeout { get; protected set; }
/// <summary>
/// The state when the publisher is active, i.e. before the subscriber is attached
/// and when an subscriber is attached. It is allowed to
/// call <see cref="OnComplete"/> and <see cref="OnError"/> in this state. It is
/// allowed to call <see cref="OnNext"/> in this state when <see cref="TotalDemand"/>
/// is greater than zero.
/// </summary>
public bool IsActive
=> _lifecycleState == LifecycleState.Active || _lifecycleState == LifecycleState.PreSubscriber;
/// <summary>
/// Total number of requested elements from the stream subscriber.
/// This actor automatically keeps tracks of this amount based on
/// incoming request messages and outgoing <see cref="OnNext"/>.
/// </summary>
public long TotalDemand => _demand;
/// <summary>
/// The terminal state after calling <see cref="OnComplete"/>. It is not allowed to
/// <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in this state.
/// </summary>
public bool IsCompleted => _lifecycleState == LifecycleState.Completed;
/// <summary>
/// The terminal state after calling <see cref="OnError"/>. It is not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in this state.
/// </summary>
public bool IsErrorEmitted => _lifecycleState == LifecycleState.ErrorEmitted;
/// <summary>
/// The state after the stream subscriber has canceled the subscription.
/// It is allowed to call <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in
/// this state, but the calls will not perform anything.
/// </summary>
public bool IsCanceled => _lifecycleState == LifecycleState.Canceled;
/// <summary>
/// Send an element to the stream subscriber. You are allowed to send as many elements
/// as have been requested by the stream subscriber. This amount can be inquired with
/// <see cref="TotalDemand"/>. It is only allowed to use <see cref="OnNext"/> when
/// <see cref="IsActive"/> and <see cref="TotalDemand"/> > 0,
/// otherwise <see cref="OnNext"/> will throw <see cref="IllegalStateException"/>.
/// </summary>
public void OnNext(T element)
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
case LifecycleState.CompleteThenStop:
if (_demand > 0)
{
_demand--;
ReactiveStreamsCompliance.TryOnNext(_subscriber, element);
}
else
{
throw new IllegalStateException(
"OnNext is not allowed when the stream has not requested elements, total demand was 0");
}
break;
case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnNext must not be called after OnError");
case LifecycleState.Completed: throw new IllegalStateException("OnNext must not be called after OnComplete");
case LifecycleState.Canceled: break;
}
}
/// <summary>
/// Complete the stream. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </summary>
public void OnComplete()
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
case LifecycleState.CompleteThenStop:
_lifecycleState = LifecycleState.Completed;
_onError = null;
if (_subscriber != null)
{
// otherwise onComplete will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
finally
{
_subscriber = null;
}
}
break;
case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnComplete must not be called after OnError");
case LifecycleState.Completed: throw new IllegalStateException("OnComplete must only be called once");
case LifecycleState.Canceled: break;
}
}
/// <summary>
/// <para>
/// Complete the stream. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// After signalling completion the Actor will then stop itself as it has completed the protocol.
/// When <see cref="OnComplete"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe
/// to this <see cref="ActorPublisher{T}"/> the completion signal (and therefore stopping of the Actor as well)
/// will be delayed until such <see cref="ISubscriber{T}"/> arrives.
/// </para>
/// </summary>
public void OnCompleteThenStop()
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
_lifecycleState = LifecycleState.CompleteThenStop;
_onError = null;
if (_subscriber != null)
{
// otherwise onComplete will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
finally
{
Context.Stop(Self);
}
}
break;
default: OnComplete(); break;
}
}
/// <summary>
/// Terminate the stream with failure. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </summary>
public void OnError(Exception cause)
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
case LifecycleState.CompleteThenStop:
_lifecycleState = LifecycleState.ErrorEmitted;
_onError = new OnErrorBlock(cause, false);
if (_subscriber != null)
{
// otherwise onError will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnError(_subscriber, cause);
}
finally
{
_subscriber = null;
}
}
break;
case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnError must only be called once");
case LifecycleState.Completed: throw new IllegalStateException("OnError must not be called after OnComplete");
case LifecycleState.Canceled: break;
}
}
/// <summary>
/// <para>
/// Terminate the stream with failure. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// After signalling the Error the Actor will then stop itself as it has completed the protocol.
/// When <see cref="OnError"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe
/// to this <see cref="ActorPublisher{T}"/> the error signal (and therefore stopping of the Actor as well)
/// will be delayed until such <see cref="ISubscriber{T}"/> arrives.
/// </para>
/// </summary>
public void OnErrorThenStop(Exception cause)
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
_lifecycleState = LifecycleState.ErrorEmitted;
_onError = new OnErrorBlock(cause, stop: true);
if (_subscriber != null)
{
// otherwise onError will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnError(_subscriber, cause);
}
finally
{
Context.Stop(Self);
}
}
break;
default: OnError(cause); break;
}
}
#region Internal API
protected override bool AroundReceive(Receive receive, object message)
{
if (message is Request)
{
var req = (Request) message;
if (req.Count < 1)
{
if (_lifecycleState == LifecycleState.Active)
OnError(new ArgumentException("Number of requested elements must be positive. Rule 3.9"));
else
base.AroundReceive(receive, message);
}
else
{
_demand += req.Count;
if (_demand < 0) _demand = long.MaxValue; // long overflow: effectively unbounded
base.AroundReceive(receive, message);
}
}
else if (message is Subscribe<T>)
{
var sub = (Subscribe<T>) message;
var subscriber = sub.Subscriber;
switch (_lifecycleState)
{
case LifecycleState.PreSubscriber:
_scheduledSubscriptionTimeout.Cancel();
_subscriber = subscriber;
_lifecycleState = LifecycleState.Active;
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, new ActorPublisherSubscription(Self));
break;
case LifecycleState.ErrorEmitted:
if (_onError.Stop) Context.Stop(Self);
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnError(subscriber, _onError.Cause);
break;
case LifecycleState.Completed:
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnComplete(subscriber);
break;
case LifecycleState.CompleteThenStop:
Context.Stop(Self);
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnComplete(subscriber);
break;
case LifecycleState.Active:
case LifecycleState.Canceled:
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnError(subscriber, _subscriber == subscriber
? new IllegalStateException("Cannot subscribe the same subscriber multiple times")
: new IllegalStateException("Only supports one subscriber"));
break;
}
}
else if (message is Cancel)
{
CancelSelf();
base.AroundReceive(receive, message);
}
else if (message is SubscriptionTimeoutExceeded)
{
if (!_scheduledSubscriptionTimeout.IsCancellationRequested)
{
CancelSelf();
base.AroundReceive(receive, message);
}
}
else return base.AroundReceive(receive, message);
return true;
}
private void CancelSelf()
{
_lifecycleState = LifecycleState.Canceled;
_subscriber = null;
_onError = null;
_demand = 0L;
}
public override void AroundPreStart()
{
base.AroundPreStart();
if (SubscriptionTimeout != Timeout.InfiniteTimeSpan)
{
_scheduledSubscriptionTimeout = new Cancelable(Context.System.Scheduler);
Context.System.Scheduler.ScheduleTellOnce(SubscriptionTimeout, Self, SubscriptionTimeoutExceeded.Instance, Self, _scheduledSubscriptionTimeout);
}
}
public override void AroundPreRestart(Exception cause, object message)
{
// some state must survive restart
_state.Set(Self, new ActorPublisherState.State(UntypedSubscriber.FromTyped(_subscriber), _demand, _lifecycleState));
base.AroundPreRestart(cause, message);
}
public override void AroundPostRestart(Exception cause, object message)
{
var s = _state.Remove(Self);
if (s != null)
{
_subscriber = UntypedSubscriber.ToTyped<T>(s.Subscriber);
_demand = s.Demand;
_lifecycleState = s.LifecycleState;
}
base.AroundPostRestart(cause, message);
}
public override void AroundPostStop()
{
_state.Remove(Self);
try
{
if (_lifecycleState == LifecycleState.Active)
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
finally
{
base.AroundPostStop();
}
}
#endregion
}
public static class ActorPublisher
{
public static IPublisher<T> Create<T>(IActorRef @ref) => new ActorPublisherImpl<T>(@ref);
}
public sealed class ActorPublisherImpl<T> : IPublisher<T>
{
private readonly IActorRef _ref;
public ActorPublisherImpl(IActorRef @ref)
{
if(@ref == null) throw new ArgumentNullException(nameof(@ref), "ActorPublisherImpl requires IActorRef to be defined");
_ref = @ref;
}
public void Subscribe(ISubscriber<T> subscriber)
{
if (subscriber == null) throw new ArgumentNullException(nameof(subscriber), "Subscriber must not be null");
_ref.Tell(new Subscribe<T>(subscriber));
}
}
public sealed class ActorPublisherSubscription : ISubscription
{
private readonly IActorRef _ref;
public ActorPublisherSubscription(IActorRef @ref)
{
if (@ref == null) throw new ArgumentNullException(nameof(@ref), "ActorPublisherSubscription requires IActorRef to be defined");
_ref = @ref;
}
public void Request(long n) => _ref.Tell(new Request(n));
public void Cancel() => _ref.Tell(Actors.Cancel.Instance);
}
public sealed class OnErrorBlock
{
public readonly Exception Cause;
public readonly bool Stop;
public OnErrorBlock(Exception cause, bool stop)
{
Cause = cause;
Stop = stop;
}
}
internal class ActorPublisherState : ExtensionIdProvider<ActorPublisherState>, IExtension
{
public sealed class State
{
public readonly IUntypedSubscriber Subscriber;
public readonly long Demand;
public readonly LifecycleState LifecycleState;
public State(IUntypedSubscriber subscriber, long demand, LifecycleState lifecycleState)
{
Subscriber = subscriber;
Demand = demand;
LifecycleState = lifecycleState;
}
}
private readonly ConcurrentDictionary<IActorRef, State> _state = new ConcurrentDictionary<IActorRef, State>();
public static readonly ActorPublisherState Instance = new ActorPublisherState();
private ActorPublisherState() { }
public State Get(IActorRef actorRef)
{
State state;
return _state.TryGetValue(actorRef, out state) ? state : null;
}
public void Set(IActorRef actorRef, State s) => _state.AddOrUpdate(actorRef, s, (@ref, oldState) => s);
public State Remove(IActorRef actorRef)
{
State s;
return _state.TryRemove(actorRef, out s) ? s : null;
}
public override ActorPublisherState CreateExtension(ExtendedActorSystem system) => new ActorPublisherState();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// An <see cref="AttributeSource"/> contains a list of different <see cref="Attribute"/>s,
/// and methods to add and get them. There can only be a single instance
/// of an attribute in the same <see cref="AttributeSource"/> instance. This is ensured
/// by passing in the actual type of the <see cref="IAttribute"/> to
/// the <see cref="AddAttribute{T}"/>, which then checks if an instance of
/// that type is already present. If yes, it returns the instance, otherwise
/// it creates a new instance and returns it.
/// </summary>
public class AttributeSource
{
/// <summary>
/// An <see cref="AttributeFactory"/> creates instances of <see cref="Attribute"/>s.
/// </summary>
public abstract class AttributeFactory // LUCENENET TODO: API - de-nest
{
/// <summary>
/// returns an <see cref="Attribute"/> for the supplied <see cref="IAttribute"/> interface.
/// </summary>
public abstract Attribute CreateAttributeInstance<T>() where T : IAttribute;
/// <summary>
/// This is the default factory that creates <see cref="Attribute"/>s using the
/// <see cref="Type"/> of the supplied <see cref="IAttribute"/> interface by removing the <code>I</code> from the prefix.
/// </summary>
public static readonly AttributeFactory DEFAULT_ATTRIBUTE_FACTORY = new DefaultAttributeFactory();
private sealed class DefaultAttributeFactory : AttributeFactory
{
// LUCENENET: Using ConditionalWeakTable instead of WeakIdentityMap. A Type IS an
// identity for a class, so there is no need for an identity wrapper for it.
private static readonly ConditionalWeakTable<Type, WeakReference<Type>> attClassImplMap =
new ConditionalWeakTable<Type, WeakReference<Type>>();
internal DefaultAttributeFactory()
{
}
public override Attribute CreateAttributeInstance<S>()
{
try
{
return (Attribute)Activator.CreateInstance(GetClassForInterface<S>());
}
catch (Exception e)
{
throw new ArgumentException("Could not instantiate implementing class for " + typeof(S).FullName, e);
}
}
internal static Type GetClassForInterface<T>() where T : IAttribute
{
var attClass = typeof(T);
Type clazz;
#if !FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
// LUCENENET: If the weakreference is dead, we need to explicitly remove and re-add its key.
// We synchronize on attClassImplMap only to make the operation atomic. This does not actually
// utilize the same lock as attClassImplMap does internally, but since this is the only place
// it is used, it is fine here.
// In .NET Standard 2.1, we can use AddOrUpdate, so don't need the lock.
lock (attClassImplMap)
#endif
{
var @ref = attClassImplMap.GetValue(attClass, (key) =>
{
return CreateAttributeWeakReference(key, out clazz);
});
if (!@ref.TryGetTarget(out clazz))
{
#if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
// There is a small chance that multiple threads will get through here, but it doesn't matter
attClassImplMap.AddOrUpdate(attClass, CreateAttributeWeakReference(attClass, out clazz));
#else
attClassImplMap.Remove(attClass);
attClassImplMap.Add(attClass, CreateAttributeWeakReference(attClass, out clazz));
#endif
}
}
return clazz;
}
// LUCENENET specific - factored this out so we can reuse
private static WeakReference<Type> CreateAttributeWeakReference(Type attClass, out Type clazz)
{
try
{
string name = attClass.FullName.Replace(attClass.Name, attClass.Name.Substring(1)) + ", " + attClass.GetTypeInfo().Assembly.FullName;
return new WeakReference<Type>(clazz = Type.GetType(name, true));
}
catch (Exception e)
{
throw new ArgumentException("Could not find implementing class for " + attClass.Name, e);
}
}
}
}
/// <summary>
/// This class holds the state of an <see cref="AttributeSource"/>. </summary>
/// <seealso cref="CaptureState()"/>
/// <seealso cref="RestoreState(State)"/>
public sealed class State
#if FEATURE_CLONEABLE
: System.ICloneable
#endif
{
internal Attribute attribute;
internal State next;
public object Clone()
{
State clone = new State();
clone.attribute = (Attribute)attribute.Clone();
if (next != null)
{
clone.next = (State)next.Clone();
}
return clone;
}
}
// These two maps must always be in sync!!!
// So they are private, final and read-only from the outside (read-only iterators)
private readonly IDictionary<Type, Util.Attribute> attributes;
private readonly IDictionary<Type, Util.Attribute> attributeImpls;
private readonly State[] currentState;
private readonly AttributeFactory factory;
/// <summary>
/// An <see cref="AttributeSource"/> using the default attribute factory <see cref="AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY"/>.
/// </summary>
public AttributeSource()
: this(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY)
{
}
/// <summary>
/// An <see cref="AttributeSource"/> that uses the same attributes as the supplied one.
/// </summary>
public AttributeSource(AttributeSource input)
{
if (input == null)
{
throw new ArgumentException("input AttributeSource must not be null");
}
this.attributes = input.attributes;
this.attributeImpls = input.attributeImpls;
this.currentState = input.currentState;
this.factory = input.factory;
}
/// <summary>
/// An <see cref="AttributeSource"/> using the supplied <see cref="AttributeFactory"/> for creating new <see cref="IAttribute"/> instances.
/// </summary>
public AttributeSource(AttributeFactory factory)
{
this.attributes = new JCG.LinkedDictionary<Type, Util.Attribute>();
this.attributeImpls = new JCG.LinkedDictionary<Type, Util.Attribute>();
this.currentState = new State[1];
this.factory = factory;
}
/// <summary>
/// Returns the used <see cref="AttributeFactory"/>.
/// </summary>
public AttributeFactory GetAttributeFactory()
{
return this.factory;
}
/// <summary>
/// Returns a new iterator that iterates the attribute classes
/// in the same order they were added in.
/// </summary>
public IEnumerator<Type> GetAttributeClassesEnumerator()
{
return attributes.Keys.GetEnumerator();
}
/// <summary>
/// Returns a new iterator that iterates all unique <see cref="IAttribute"/> implementations.
/// This iterator may contain less entries than <see cref="GetAttributeClassesEnumerator()"/>,
/// if one instance implements more than one <see cref="IAttribute"/> interface.
/// </summary>
public IEnumerator<Attribute> GetAttributeImplsEnumerator()
{
State initState = GetCurrentState();
if (initState != null)
{
return new IteratorAnonymousInnerClassHelper(this, initState);
}
else
{
return (new JCG.HashSet<Attribute>()).GetEnumerator();
}
}
private class IteratorAnonymousInnerClassHelper : IEnumerator<Attribute>
{
private readonly AttributeSource outerInstance;
private AttributeSource.State initState;
private Attribute current;
public IteratorAnonymousInnerClassHelper(AttributeSource outerInstance, AttributeSource.State initState)
{
this.outerInstance = outerInstance;
this.initState = initState;
state = initState;
}
private State state;
public virtual void Remove()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
public bool MoveNext()
{
if (state == null)
{
return false;
}
Attribute att = state.attribute;
state = state.next;
current = att;
return true;
}
public void Reset()
{
throw new NotSupportedException();
}
public Attribute Current
{
get { return current; }
set { current = value; }
}
object IEnumerator.Current
{
get { return Current; }
}
}
/// <summary>
/// A cache that stores all interfaces for known implementation classes for performance (slow reflection) </summary>
// LUCENENET: Using ConditionalWeakTable instead of WeakIdentityMap. A Type IS an
// identity for a class, so there is no need for an identity wrapper for it.
private static readonly ConditionalWeakTable<Type, LinkedList<WeakReference<Type>>> knownImplClasses =
new ConditionalWeakTable<Type, LinkedList<WeakReference<Type>>>();
internal static LinkedList<WeakReference<Type>> GetAttributeInterfaces(Type clazz)
{
return knownImplClasses.GetValue(clazz, (key) =>
{
LinkedList<WeakReference<Type>> foundInterfaces = new LinkedList<WeakReference<Type>>();
// find all interfaces that this attribute instance implements
// and that extend the Attribute interface
Type actClazz = clazz;
do
{
foreach (Type curInterface in actClazz.GetInterfaces())
{
if (curInterface != typeof(IAttribute) && typeof(IAttribute).IsAssignableFrom(curInterface))
{
foundInterfaces.AddLast(new WeakReference<Type>(curInterface));
}
}
actClazz = actClazz.GetTypeInfo().BaseType;
} while (actClazz != null);
return foundInterfaces;
});
}
/// <summary>
/// <b>Expert:</b> Adds a custom <see cref="Attribute"/> instance with one or more <see cref="IAttribute"/> interfaces.
/// <para><font color="red"><b>Please note:</b> It is not guaranteed, that <paramref name="att"/> is added to
/// the <see cref="AttributeSource"/>, because the provided attributes may already exist.
/// You should always retrieve the wanted attributes using <see cref="GetAttribute{T}"/> after adding
/// with this method and cast to your <see cref="Type"/>.
/// The recommended way to use custom implementations is using an <see cref="AttributeFactory"/>.
/// </font></para>
/// </summary>
public void AddAttributeImpl(Attribute att)
{
Type clazz = att.GetType();
if (attributeImpls.ContainsKey(clazz))
{
return;
}
LinkedList<WeakReference<Type>> foundInterfaces = GetAttributeInterfaces(clazz);
// add all interfaces of this Attribute to the maps
foreach (var curInterfaceRef in foundInterfaces)
{
curInterfaceRef.TryGetTarget(out Type curInterface);
Debug.Assert(curInterface != null, "We have a strong reference on the class holding the interfaces, so they should never get evicted");
// Attribute is a superclass of this interface
if (!attributes.ContainsKey(curInterface))
{
// invalidate state to force recomputation in captureState()
this.currentState[0] = null;
attributes.Add(curInterface, att);
if (!attributeImpls.ContainsKey(clazz))
{
attributeImpls.Add(clazz, att);
}
}
}
}
/// <summary>
/// The caller must pass in an interface type that extends <see cref="IAttribute"/>.
/// This method first checks if an instance of the corresponding class is
/// already in this <see cref="AttributeSource"/> and returns it. Otherwise a
/// new instance is created, added to this <see cref="AttributeSource"/> and returned.
/// </summary>
public T AddAttribute<T>()
where T : IAttribute
{
var attClass = typeof(T);
if (!attributes.ContainsKey(attClass))
{
if (!(attClass.GetTypeInfo().IsInterface && typeof(IAttribute).IsAssignableFrom(attClass)))
{
throw new ArgumentException("AddAttribute() only accepts an interface that extends IAttribute, but " + attClass.FullName + " does not fulfil this contract.");
}
AddAttributeImpl(this.factory.CreateAttributeInstance<T>());
}
T returnAttr;
try
{
returnAttr = (T)(IAttribute)attributes[attClass];
}
#pragma warning disable 168
catch (KeyNotFoundException knf)
#pragma warning restore 168
{
return default(T);
}
return returnAttr;
}
/// <summary>
/// Returns <c>true</c>, if this <see cref="AttributeSource"/> has any attributes </summary>
public bool HasAttributes
{
get { return this.attributes.Count > 0; }
}
/// <summary>
/// The caller must pass in an interface type that extends <see cref="IAttribute"/>.
/// Returns <c>true</c>, if this <see cref="AttributeSource"/> contains the corrsponding <see cref="Attribute"/>.
/// </summary>
public bool HasAttribute<T>() where T : IAttribute
{
var attClass = typeof(T);
return this.attributes.ContainsKey(attClass);
}
/// <summary>
/// The caller must pass in an interface type that extends <see cref="IAttribute"/>.
/// Returns the instance of the corresponding <see cref="Attribute"/> contained in this <see cref="AttributeSource"/>
/// </summary>
/// <exception cref="ArgumentException"> if this <see cref="AttributeSource"/> does not contain the
/// <see cref="Attribute"/>. It is recommended to always use <see cref="AddAttribute{T}()"/> even in consumers
/// of <see cref="Analysis.TokenStream"/>s, because you cannot know if a specific <see cref="Analysis.TokenStream"/> really uses
/// a specific <see cref="Attribute"/>. <see cref="AddAttribute{T}()"/> will automatically make the attribute
/// available. If you want to only use the attribute, if it is available (to optimize
/// consuming), use <see cref="HasAttribute{T}()"/>. </exception>
public virtual T GetAttribute<T>() where T : IAttribute
{
var attClass = typeof(T);
if (!attributes.ContainsKey(attClass))
{
throw new ArgumentException("this AttributeSource does not have the attribute '" + attClass.Name + "'.");
}
return (T)(IAttribute)this.attributes[attClass];
}
private State GetCurrentState()
{
State s = currentState[0];
if (s != null || !HasAttributes)
{
return s;
}
var c = s = currentState[0] = new State();
using (var it = attributeImpls.Values.GetEnumerator())
{
it.MoveNext();
c.attribute = it.Current;
while (it.MoveNext())
{
c.next = new State();
c = c.next;
c.attribute = it.Current;
}
return s;
}
}
/// <summary>
/// Resets all <see cref="Attribute"/>s in this <see cref="AttributeSource"/> by calling
/// <see cref="Attribute.Clear()"/> on each <see cref="IAttribute"/> implementation.
/// </summary>
public void ClearAttributes()
{
for (State state = GetCurrentState(); state != null; state = state.next)
{
state.attribute.Clear();
}
}
/// <summary>
/// Captures the state of all <see cref="Attribute"/>s. The return value can be passed to
/// <see cref="RestoreState(State)"/> to restore the state of this or another <see cref="AttributeSource"/>.
/// </summary>
public virtual State CaptureState()
{
State state = this.GetCurrentState();
return (state == null) ? null : (State)state.Clone();
}
/// <summary>
/// Restores this state by copying the values of all attribute implementations
/// that this state contains into the attributes implementations of the targetStream.
/// The targetStream must contain a corresponding instance for each argument
/// contained in this state (e.g. it is not possible to restore the state of
/// an <see cref="AttributeSource"/> containing a <see cref="Analysis.TokenAttributes.ICharTermAttribute"/> into a <see cref="AttributeSource"/> using
/// a <see cref="Analysis.Token"/> instance as implementation).
/// <para/>
/// Note that this method does not affect attributes of the targetStream
/// that are not contained in this state. In other words, if for example
/// the targetStream contains an <see cref="Analysis.TokenAttributes.IOffsetAttribute"/>, but this state doesn't, then
/// the value of the <see cref="Analysis.TokenAttributes.IOffsetAttribute"/> remains unchanged. It might be desirable to
/// reset its value to the default, in which case the caller should first
/// call <see cref="AttributeSource.ClearAttributes()"/> (<c>TokenStream.ClearAttributes()</c> on the targetStream.
/// </summary>
public void RestoreState(State state)
{
if (state == null)
{
return;
}
do
{
if (!attributeImpls.ContainsKey(state.attribute.GetType()))
{
throw new ArgumentException("State contains Attribute of type " + state.attribute.GetType().Name + " that is not in in this AttributeSource");
}
state.attribute.CopyTo(attributeImpls[state.attribute.GetType()]);
state = state.next;
} while (state != null);
}
public override int GetHashCode()
{
int code = 0;
for (State state = GetCurrentState(); state != null; state = state.next)
{
code = code * 31 + state.attribute.GetHashCode();
}
return code;
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (obj is AttributeSource other)
{
if (HasAttributes)
{
if (!other.HasAttributes)
{
return false;
}
if (this.attributeImpls.Count != other.attributeImpls.Count)
{
return false;
}
// it is only equal if all attribute impls are the same in the same order
State thisState = this.GetCurrentState();
State otherState = other.GetCurrentState();
while (thisState != null && otherState != null)
{
if (otherState.attribute.GetType() != thisState.attribute.GetType() || !otherState.attribute.Equals(thisState.attribute))
{
return false;
}
thisState = thisState.next;
otherState = otherState.next;
}
return true;
}
else
{
return !other.HasAttributes;
}
}
else
{
return false;
}
}
/// <summary>
/// This method returns the current attribute values as a string in the following format
/// by calling the <see cref="ReflectWith(IAttributeReflector)"/> method:
///
/// <list type="bullet">
/// <item><term>if <paramref name="prependAttClass"/>=true:</term> <description> <c>"AttributeClass.Key=value,AttributeClass.Key=value"</c> </description></item>
/// <item><term>if <paramref name="prependAttClass"/>=false:</term> <description> <c>"key=value,key=value"</c> </description></item>
/// </list>
/// </summary>
/// <seealso cref="ReflectWith(IAttributeReflector)"/>
public string ReflectAsString(bool prependAttClass)
{
StringBuilder buffer = new StringBuilder();
ReflectWith(new AttributeReflectorAnonymousInnerClassHelper(this, prependAttClass, buffer));
return buffer.ToString();
}
private class AttributeReflectorAnonymousInnerClassHelper : IAttributeReflector
{
private readonly AttributeSource outerInstance;
private bool prependAttClass;
private StringBuilder buffer;
public AttributeReflectorAnonymousInnerClassHelper(AttributeSource outerInstance, bool prependAttClass, StringBuilder buffer)
{
this.outerInstance = outerInstance;
this.prependAttClass = prependAttClass;
this.buffer = buffer;
}
public void Reflect<T>(string key, object value)
where T : IAttribute
{
Reflect(typeof(T), key, value);
}
public void Reflect(Type attClass, string key, object value)
{
if (buffer.Length > 0)
{
buffer.Append(',');
}
if (prependAttClass)
{
buffer.Append(attClass.Name).Append('#');
}
buffer.Append(key).Append('=').Append(object.ReferenceEquals(value, null) ? "null" : value);
}
}
/// <summary>
/// This method is for introspection of attributes, it should simply
/// add the key/values this <see cref="AttributeSource"/> holds to the given <see cref="IAttributeReflector"/>.
///
/// <para>This method iterates over all <see cref="IAttribute"/> implementations and calls the
/// corresponding <see cref="Attribute.ReflectWith(IAttributeReflector)"/> method.</para>
/// </summary>
/// <seealso cref="Attribute.ReflectWith(IAttributeReflector)"/>
public void ReflectWith(IAttributeReflector reflector)
{
for (State state = GetCurrentState(); state != null; state = state.next)
{
state.attribute.ReflectWith(reflector);
}
}
/// <summary>
/// Performs a clone of all <see cref="Attribute"/> instances returned in a new
/// <see cref="AttributeSource"/> instance. This method can be used to e.g. create another <see cref="Analysis.TokenStream"/>
/// with exactly the same attributes (using <see cref="AttributeSource(AttributeSource)"/>).
/// You can also use it as a (non-performant) replacement for <see cref="CaptureState()"/>, if you need to look
/// into / modify the captured state.
/// </summary>
public AttributeSource CloneAttributes()
{
AttributeSource clone = new AttributeSource(this.factory);
if (HasAttributes)
{
// first clone the impls
for (State state = GetCurrentState(); state != null; state = state.next)
{
//clone.AttributeImpls[state.attribute.GetType()] = state.attribute.Clone();
var impl = (Attribute)state.attribute.Clone();
if (!clone.attributeImpls.ContainsKey(impl.GetType()))
{
clone.attributeImpls.Add(impl.GetType(), impl);
}
}
// now the interfaces
foreach (var entry in this.attributes)
{
clone.attributes.Add(entry.Key, clone.attributeImpls[entry.Value.GetType()]);
}
}
return clone;
}
/// <summary>
/// Copies the contents of this <see cref="AttributeSource"/> to the given target <see cref="AttributeSource"/>.
/// The given instance has to provide all <see cref="IAttribute"/>s this instance contains.
/// The actual attribute implementations must be identical in both <see cref="AttributeSource"/> instances;
/// ideally both <see cref="AttributeSource"/> instances should use the same <see cref="AttributeFactory"/>.
/// You can use this method as a replacement for <see cref="RestoreState(State)"/>, if you use
/// <see cref="CloneAttributes()"/> instead of <see cref="CaptureState()"/>.
/// </summary>
public void CopyTo(AttributeSource target)
{
for (State state = GetCurrentState(); state != null; state = state.next)
{
Attribute targetImpl = target.attributeImpls[state.attribute.GetType()];
if (targetImpl == null)
{
throw new ArgumentException("this AttributeSource contains Attribute of type " + state.attribute.GetType().Name + " that is not in the target");
}
state.attribute.CopyTo(targetImpl);
}
}
/// <summary>
/// Returns a string consisting of the class's simple name, the hex representation of the identity hash code,
/// and the current reflection of all attributes. </summary>
/// <seealso cref="ReflectAsString(bool)"/>
public override string ToString()
{
return this.GetType().Name + '@' + RuntimeHelpers.GetHashCode(this).ToString("x") + " " + ReflectAsString(false);
}
}
}
| |
// $ANTLR 3.1.2 BuildOptions\\ProfileGrammar.g3 2009-09-30 13:18:17
// The variable 'variable' is assigned but its value is never used.
#pragma warning disable 219
// Unreachable code detected.
#pragma warning disable 162
using System.Collections.Generic;
using Antlr.Runtime;
using Stack = System.Collections.Generic.Stack<object>;
using List = System.Collections.IList;
using ArrayList = System.Collections.Generic.List<object>;
using Antlr.Runtime.Debug;
using IOException = System.IO.IOException;
using Antlr.Runtime.Tree;
using RewriteRuleITokenStream = Antlr.Runtime.Tree.RewriteRuleTokenStream;
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "3.1.2")]
[System.CLSCompliant(false)]
public partial class ProfileGrammarParser : DebugParser
{
internal static readonly string[] tokenNames = new string[] {
"<invalid>", "<EOR>", "<DOWN>", "<UP>", "CALL", "FUNC", "ID", "INT", "NEWLINE", "WS", "'-'", "'%'", "'('", "')'", "'*'", "'/'", "'+'", "'='"
};
public const int EOF=-1;
public const int T__10=10;
public const int T__11=11;
public const int T__12=12;
public const int T__13=13;
public const int T__14=14;
public const int T__15=15;
public const int T__16=16;
public const int T__17=17;
public const int CALL=4;
public const int FUNC=5;
public const int ID=6;
public const int INT=7;
public const int NEWLINE=8;
public const int WS=9;
// delegates
// delegators
public static readonly string[] ruleNames =
new string[]
{
"invalidRule", "atom", "expr", "formalPar", "func", "multExpr", "prog",
"stat"
};
int ruleLevel = 0;
public virtual int RuleLevel { get { return ruleLevel; } }
public virtual void IncRuleLevel() { ruleLevel++; }
public virtual void DecRuleLevel() { ruleLevel--; }
public ProfileGrammarParser( ITokenStream input )
: this( input, new Profiler(null), new RecognizerSharedState() )
{
}
public ProfileGrammarParser( ITokenStream input, IDebugEventListener dbg, RecognizerSharedState state )
: base( input, dbg, state )
{
Profiler p = (Profiler)dbg;
p.setParser(this);
InitializeTreeAdaptor();
if ( TreeAdaptor == null )
TreeAdaptor = new CommonTreeAdaptor();
ITreeAdaptor adap = new CommonTreeAdaptor();
TreeAdaptor = adap;
proxy.TreeAdaptor = adap;
}
public ProfileGrammarParser( ITokenStream input, IDebugEventListener dbg )
: base( input, dbg )
{
Profiler p = (Profiler)dbg;
p.setParser(this);InitializeTreeAdaptor();
if ( TreeAdaptor == null )
TreeAdaptor = new CommonTreeAdaptor();
ITreeAdaptor adap = new CommonTreeAdaptor();
TreeAdaptor = adap;
}
public virtual bool AlreadyParsedRule( IIntStream input, int ruleIndex )
{
((Profiler)dbg).ExamineRuleMemoization(input, ruleIndex, ProfileGrammarParser.ruleNames[ruleIndex]);
return super.AlreadyParsedRule(input, ruleIndex);
}
public virtual void Memoize( IIntStream input, int ruleIndex, int ruleStartIndex )
{
((Profiler)dbg).Memoize(input, ruleIndex, ruleStartIndex, ProfileGrammarParser.ruleNames[ruleIndex]);
super.Memoize(input, ruleIndex, ruleStartIndex);
}
protected virtual bool EvalPredicate( bool result, string predicate )
{
dbg.SemanticPredicate( result, predicate );
return result;
}
// Implement this function in your helper file to use a custom tree adaptor
partial void InitializeTreeAdaptor();
protected DebugTreeAdaptor adaptor;
public ITreeAdaptor TreeAdaptor
{
get
{
return adaptor;
}
set
{
this.adaptor = new DebugTreeAdaptor(dbg,adaptor);
}
}
public override string[] TokenNames { get { return ProfileGrammarParser.tokenNames; } }
public override string GrammarFileName { get { return "BuildOptions\\ProfileGrammar.g3"; } }
#region Rules
public class prog_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "prog"
// BuildOptions\\ProfileGrammar.g3:50:0: prog : ( stat )* ;
private ProfileGrammarParser.prog_return prog( )
{
ProfileGrammarParser.prog_return retval = new ProfileGrammarParser.prog_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
ProfileGrammarParser.stat_return stat1 = default(ProfileGrammarParser.stat_return);
try
{
dbg.EnterRule( GrammarFileName, "prog" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 50, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:50:7: ( ( stat )* )
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:50:7: ( stat )*
{
root_0 = (CommonTree)adaptor.Nil();
dbg.Location( 50, 6 );
// BuildOptions\\ProfileGrammar.g3:50:7: ( stat )*
try
{
dbg.EnterSubRule( 1 );
for ( ; ; )
{
int alt1=2;
try
{
dbg.EnterDecision( 1 );
int LA1_0 = input.LA(1);
if ( ((LA1_0>=ID && LA1_0<=NEWLINE)||LA1_0==12) )
{
alt1=1;
}
}
finally
{
dbg.ExitDecision( 1 );
}
switch ( alt1 )
{
case 1:
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:50:9: stat
{
dbg.Location( 50, 8 );
PushFollow(Follow._stat_in_prog53);
stat1=stat();
state._fsp--;
adaptor.AddChild(root_0, stat1.Tree);
}
break;
default:
goto loop1;
}
}
loop1:
;
}
finally
{
dbg.ExitSubRule( 1 );
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
}
dbg.Location(51, 4);
}
finally
{
dbg.ExitRule( GrammarFileName, "prog" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "prog"
public class stat_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "stat"
// BuildOptions\\ProfileGrammar.g3:53:0: stat : ( expr NEWLINE -> expr | ID '=' expr NEWLINE -> ^( '=' ID expr ) | func NEWLINE -> func | NEWLINE ->);
private ProfileGrammarParser.stat_return stat( )
{
ProfileGrammarParser.stat_return retval = new ProfileGrammarParser.stat_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
IToken NEWLINE3=null;
IToken ID4=null;
IToken char_literal5=null;
IToken NEWLINE7=null;
IToken NEWLINE9=null;
IToken NEWLINE10=null;
ProfileGrammarParser.expr_return expr2 = default(ProfileGrammarParser.expr_return);
ProfileGrammarParser.expr_return expr6 = default(ProfileGrammarParser.expr_return);
ProfileGrammarParser.func_return func8 = default(ProfileGrammarParser.func_return);
CommonTree NEWLINE3_tree=null;
CommonTree ID4_tree=null;
CommonTree char_literal5_tree=null;
CommonTree NEWLINE7_tree=null;
CommonTree NEWLINE9_tree=null;
CommonTree NEWLINE10_tree=null;
RewriteRuleITokenStream stream_NEWLINE=new RewriteRuleITokenStream(adaptor,"token NEWLINE");
RewriteRuleITokenStream stream_ID=new RewriteRuleITokenStream(adaptor,"token ID");
RewriteRuleITokenStream stream_17=new RewriteRuleITokenStream(adaptor,"token 17");
RewriteRuleSubtreeStream stream_expr=new RewriteRuleSubtreeStream(adaptor,"rule expr");
RewriteRuleSubtreeStream stream_func=new RewriteRuleSubtreeStream(adaptor,"rule func");
try
{
dbg.EnterRule( GrammarFileName, "stat" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 53, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:53:9: ( expr NEWLINE -> expr | ID '=' expr NEWLINE -> ^( '=' ID expr ) | func NEWLINE -> func | NEWLINE ->)
int alt2=4;
try
{
dbg.EnterDecision( 2 );
try
{
isCyclicDecision = true;
alt2 = dfa2.Predict(input);
}
catch ( NoViableAltException nvae )
{
dbg.RecognitionException( nvae );
throw nvae;
}
}
finally
{
dbg.ExitDecision( 2 );
}
switch ( alt2 )
{
case 1:
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:53:9: expr NEWLINE
{
dbg.Location( 53, 8 );
PushFollow(Follow._expr_in_stat70);
expr2=expr();
state._fsp--;
stream_expr.Add(expr2.Tree);
dbg.Location( 53, 13 );
NEWLINE3=(IToken)Match(input,NEWLINE,Follow._NEWLINE_in_stat72);
stream_NEWLINE.Add(NEWLINE3);
{
// AST REWRITE
// elements: expr
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 53:41: -> expr
{
dbg.Location( 53, 43 );
adaptor.AddChild(root_0, stream_expr.NextTree());
}
retval.tree = root_0;
}
}
break;
case 2:
dbg.EnterAlt( 2 );
// BuildOptions\\ProfileGrammar.g3:54:9: ID '=' expr NEWLINE
{
dbg.Location( 54, 8 );
ID4=(IToken)Match(input,ID,Follow._ID_in_stat105);
stream_ID.Add(ID4);
dbg.Location( 54, 11 );
char_literal5=(IToken)Match(input,17,Follow._17_in_stat107);
stream_17.Add(char_literal5);
dbg.Location( 54, 15 );
PushFollow(Follow._expr_in_stat109);
expr6=expr();
state._fsp--;
stream_expr.Add(expr6.Tree);
dbg.Location( 54, 20 );
NEWLINE7=(IToken)Match(input,NEWLINE,Follow._NEWLINE_in_stat111);
stream_NEWLINE.Add(NEWLINE7);
{
// AST REWRITE
// elements: 17, ID, expr
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 54:41: -> ^( '=' ID expr )
{
dbg.Location( 54, 43 );
// BuildOptions\\ProfileGrammar.g3:54:44: ^( '=' ID expr )
{
CommonTree root_1 = (CommonTree)adaptor.Nil();
dbg.Location( 54, 45 );
root_1 = (CommonTree)adaptor.BecomeRoot(stream_17.NextNode(), root_1);
dbg.Location( 54, 49 );
adaptor.AddChild(root_1, stream_ID.NextNode());
dbg.Location( 54, 52 );
adaptor.AddChild(root_1, stream_expr.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
retval.tree = root_0;
}
}
break;
case 3:
dbg.EnterAlt( 3 );
// BuildOptions\\ProfileGrammar.g3:55:9: func NEWLINE
{
dbg.Location( 55, 8 );
PushFollow(Follow._func_in_stat143);
func8=func();
state._fsp--;
stream_func.Add(func8.Tree);
dbg.Location( 55, 13 );
NEWLINE9=(IToken)Match(input,NEWLINE,Follow._NEWLINE_in_stat145);
stream_NEWLINE.Add(NEWLINE9);
{
// AST REWRITE
// elements: func
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 55:41: -> func
{
dbg.Location( 55, 43 );
adaptor.AddChild(root_0, stream_func.NextTree());
}
retval.tree = root_0;
}
}
break;
case 4:
dbg.EnterAlt( 4 );
// BuildOptions\\ProfileGrammar.g3:56:9: NEWLINE
{
dbg.Location( 56, 8 );
NEWLINE10=(IToken)Match(input,NEWLINE,Follow._NEWLINE_in_stat178);
stream_NEWLINE.Add(NEWLINE10);
{
// AST REWRITE
// elements:
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 56:41: ->
{
dbg.Location( 57, 4 );
root_0 = null;
}
retval.tree = root_0;
}
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
}
dbg.Location(57, 4);
}
finally
{
dbg.ExitRule( GrammarFileName, "stat" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "stat"
public class func_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "func"
// BuildOptions\\ProfileGrammar.g3:59:0: func : ID '(' formalPar ')' '=' expr -> ^( FUNC ID formalPar expr ) ;
private ProfileGrammarParser.func_return func( )
{
ProfileGrammarParser.func_return retval = new ProfileGrammarParser.func_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
IToken ID11=null;
IToken char_literal12=null;
IToken char_literal14=null;
IToken char_literal15=null;
ProfileGrammarParser.formalPar_return formalPar13 = default(ProfileGrammarParser.formalPar_return);
ProfileGrammarParser.expr_return expr16 = default(ProfileGrammarParser.expr_return);
CommonTree ID11_tree=null;
CommonTree char_literal12_tree=null;
CommonTree char_literal14_tree=null;
CommonTree char_literal15_tree=null;
RewriteRuleITokenStream stream_ID=new RewriteRuleITokenStream(adaptor,"token ID");
RewriteRuleITokenStream stream_12=new RewriteRuleITokenStream(adaptor,"token 12");
RewriteRuleITokenStream stream_13=new RewriteRuleITokenStream(adaptor,"token 13");
RewriteRuleITokenStream stream_17=new RewriteRuleITokenStream(adaptor,"token 17");
RewriteRuleSubtreeStream stream_formalPar=new RewriteRuleSubtreeStream(adaptor,"rule formalPar");
RewriteRuleSubtreeStream stream_expr=new RewriteRuleSubtreeStream(adaptor,"rule expr");
try
{
dbg.EnterRule( GrammarFileName, "func" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 59, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:59:9: ( ID '(' formalPar ')' '=' expr -> ^( FUNC ID formalPar expr ) )
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:59:9: ID '(' formalPar ')' '=' expr
{
dbg.Location( 59, 8 );
ID11=(IToken)Match(input,ID,Follow._ID_in_func219);
stream_ID.Add(ID11);
dbg.Location( 59, 12 );
char_literal12=(IToken)Match(input,12,Follow._12_in_func222);
stream_12.Add(char_literal12);
dbg.Location( 59, 16 );
PushFollow(Follow._formalPar_in_func224);
formalPar13=formalPar();
state._fsp--;
stream_formalPar.Add(formalPar13.Tree);
dbg.Location( 59, 26 );
char_literal14=(IToken)Match(input,13,Follow._13_in_func226);
stream_13.Add(char_literal14);
dbg.Location( 59, 30 );
char_literal15=(IToken)Match(input,17,Follow._17_in_func228);
stream_17.Add(char_literal15);
dbg.Location( 59, 34 );
PushFollow(Follow._expr_in_func230);
expr16=expr();
state._fsp--;
stream_expr.Add(expr16.Tree);
{
// AST REWRITE
// elements: ID, formalPar, expr
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 59:41: -> ^( FUNC ID formalPar expr )
{
dbg.Location( 59, 43 );
// BuildOptions\\ProfileGrammar.g3:59:44: ^( FUNC ID formalPar expr )
{
CommonTree root_1 = (CommonTree)adaptor.Nil();
dbg.Location( 59, 45 );
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(FUNC, "FUNC"), root_1);
dbg.Location( 59, 50 );
adaptor.AddChild(root_1, stream_ID.NextNode());
dbg.Location( 59, 53 );
adaptor.AddChild(root_1, stream_formalPar.NextTree());
dbg.Location( 59, 63 );
adaptor.AddChild(root_1, stream_expr.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
retval.tree = root_0;
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
functionDefinitions.Add(((CommonTree)retval.Tree));
}
dbg.Location(60, 4);
}
finally
{
dbg.ExitRule( GrammarFileName, "func" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "func"
public class formalPar_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "formalPar"
// BuildOptions\\ProfileGrammar.g3:65:0: formalPar : ( ID | INT );
private ProfileGrammarParser.formalPar_return formalPar( )
{
ProfileGrammarParser.formalPar_return retval = new ProfileGrammarParser.formalPar_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
IToken set17=null;
CommonTree set17_tree=null;
try
{
dbg.EnterRule( GrammarFileName, "formalPar" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 65, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:66:9: ( ID | INT )
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:
{
root_0 = (CommonTree)adaptor.Nil();
dbg.Location( 66, 8 );
set17=(IToken)input.LT(1);
if ( (input.LA(1)>=ID && input.LA(1)<=INT) )
{
input.Consume();
adaptor.AddChild(root_0, (CommonTree)adaptor.Create(set17));
state.errorRecovery=false;
}
else
{
MismatchedSetException mse = new MismatchedSetException(null,input);
dbg.RecognitionException( mse );
throw mse;
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
}
dbg.Location(68, 1);
}
finally
{
dbg.ExitRule( GrammarFileName, "formalPar" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "formalPar"
public class expr_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "expr"
// BuildOptions\\ProfileGrammar.g3:73:0: expr : multExpr ( ( '+' | '-' ) multExpr )* ;
private ProfileGrammarParser.expr_return expr( )
{
ProfileGrammarParser.expr_return retval = new ProfileGrammarParser.expr_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
IToken char_literal19=null;
IToken char_literal20=null;
ProfileGrammarParser.multExpr_return multExpr18 = default(ProfileGrammarParser.multExpr_return);
ProfileGrammarParser.multExpr_return multExpr21 = default(ProfileGrammarParser.multExpr_return);
CommonTree char_literal19_tree=null;
CommonTree char_literal20_tree=null;
try
{
dbg.EnterRule( GrammarFileName, "expr" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 73, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:73:9: ( multExpr ( ( '+' | '-' ) multExpr )* )
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:73:9: multExpr ( ( '+' | '-' ) multExpr )*
{
root_0 = (CommonTree)adaptor.Nil();
dbg.Location( 73, 8 );
PushFollow(Follow._multExpr_in_expr288);
multExpr18=multExpr();
state._fsp--;
adaptor.AddChild(root_0, multExpr18.Tree);
dbg.Location( 73, 17 );
// BuildOptions\\ProfileGrammar.g3:73:18: ( ( '+' | '-' ) multExpr )*
try
{
dbg.EnterSubRule( 4 );
for ( ; ; )
{
int alt4=2;
try
{
dbg.EnterDecision( 4 );
int LA4_0 = input.LA(1);
if ( (LA4_0==10||LA4_0==16) )
{
alt4=1;
}
}
finally
{
dbg.ExitDecision( 4 );
}
switch ( alt4 )
{
case 1:
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:73:19: ( '+' | '-' ) multExpr
{
dbg.Location( 73, 18 );
// BuildOptions\\ProfileGrammar.g3:73:19: ( '+' | '-' )
int alt3=2;
try
{
dbg.EnterSubRule( 3 );
try
{
dbg.EnterDecision( 3 );
int LA3_0 = input.LA(1);
if ( (LA3_0==16) )
{
alt3=1;
}
else if ( (LA3_0==10) )
{
alt3=2;
}
else
{
NoViableAltException nvae = new NoViableAltException("", 3, 0, input);
dbg.RecognitionException( nvae );
throw nvae;
}
}
finally
{
dbg.ExitDecision( 3 );
}
switch ( alt3 )
{
case 1:
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:73:20: '+'
{
dbg.Location( 73, 22 );
char_literal19=(IToken)Match(input,16,Follow._16_in_expr292);
char_literal19_tree = (CommonTree)adaptor.Create(char_literal19);
root_0 = (CommonTree)adaptor.BecomeRoot(char_literal19_tree, root_0);
}
break;
case 2:
dbg.EnterAlt( 2 );
// BuildOptions\\ProfileGrammar.g3:73:25: '-'
{
dbg.Location( 73, 27 );
char_literal20=(IToken)Match(input,10,Follow._10_in_expr295);
char_literal20_tree = (CommonTree)adaptor.Create(char_literal20);
root_0 = (CommonTree)adaptor.BecomeRoot(char_literal20_tree, root_0);
}
break;
}
}
finally
{
dbg.ExitSubRule( 3 );
}
dbg.Location( 73, 30 );
PushFollow(Follow._multExpr_in_expr299);
multExpr21=multExpr();
state._fsp--;
adaptor.AddChild(root_0, multExpr21.Tree);
}
break;
default:
goto loop4;
}
}
loop4:
;
}
finally
{
dbg.ExitSubRule( 4 );
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
}
dbg.Location(74, 4);
}
finally
{
dbg.ExitRule( GrammarFileName, "expr" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "expr"
public class multExpr_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "multExpr"
// BuildOptions\\ProfileGrammar.g3:76:0: multExpr : atom ( ( '*' | '/' | '%' ) atom )* ;
private ProfileGrammarParser.multExpr_return multExpr( )
{
ProfileGrammarParser.multExpr_return retval = new ProfileGrammarParser.multExpr_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
IToken set23=null;
ProfileGrammarParser.atom_return atom22 = default(ProfileGrammarParser.atom_return);
ProfileGrammarParser.atom_return atom24 = default(ProfileGrammarParser.atom_return);
CommonTree set23_tree=null;
try
{
dbg.EnterRule( GrammarFileName, "multExpr" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 76, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:77:9: ( atom ( ( '*' | '/' | '%' ) atom )* )
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:77:9: atom ( ( '*' | '/' | '%' ) atom )*
{
root_0 = (CommonTree)adaptor.Nil();
dbg.Location( 77, 8 );
PushFollow(Follow._atom_in_multExpr320);
atom22=atom();
state._fsp--;
adaptor.AddChild(root_0, atom22.Tree);
dbg.Location( 77, 13 );
// BuildOptions\\ProfileGrammar.g3:77:14: ( ( '*' | '/' | '%' ) atom )*
try
{
dbg.EnterSubRule( 5 );
for ( ; ; )
{
int alt5=2;
try
{
dbg.EnterDecision( 5 );
int LA5_0 = input.LA(1);
if ( (LA5_0==11||(LA5_0>=14 && LA5_0<=15)) )
{
alt5=1;
}
}
finally
{
dbg.ExitDecision( 5 );
}
switch ( alt5 )
{
case 1:
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:77:15: ( '*' | '/' | '%' ) atom
{
dbg.Location( 77, 27 );
set23=(IToken)input.LT(1);
set23=(IToken)input.LT(1);
if ( input.LA(1)==11||(input.LA(1)>=14 && input.LA(1)<=15) )
{
input.Consume();
root_0 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(set23), root_0);
state.errorRecovery=false;
}
else
{
MismatchedSetException mse = new MismatchedSetException(null,input);
dbg.RecognitionException( mse );
throw mse;
}
dbg.Location( 77, 29 );
PushFollow(Follow._atom_in_multExpr332);
atom24=atom();
state._fsp--;
adaptor.AddChild(root_0, atom24.Tree);
}
break;
default:
goto loop5;
}
}
loop5:
;
}
finally
{
dbg.ExitSubRule( 5 );
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
}
dbg.Location(78, 4);
}
finally
{
dbg.ExitRule( GrammarFileName, "multExpr" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "multExpr"
public class atom_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "atom"
// BuildOptions\\ProfileGrammar.g3:80:0: atom : ( INT | ID | '(' expr ')' -> expr | ID '(' expr ')' -> ^( CALL ID expr ) );
private ProfileGrammarParser.atom_return atom( )
{
ProfileGrammarParser.atom_return retval = new ProfileGrammarParser.atom_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
IToken INT25=null;
IToken ID26=null;
IToken char_literal27=null;
IToken char_literal29=null;
IToken ID30=null;
IToken char_literal31=null;
IToken char_literal33=null;
ProfileGrammarParser.expr_return expr28 = default(ProfileGrammarParser.expr_return);
ProfileGrammarParser.expr_return expr32 = default(ProfileGrammarParser.expr_return);
CommonTree INT25_tree=null;
CommonTree ID26_tree=null;
CommonTree char_literal27_tree=null;
CommonTree char_literal29_tree=null;
CommonTree ID30_tree=null;
CommonTree char_literal31_tree=null;
CommonTree char_literal33_tree=null;
RewriteRuleITokenStream stream_12=new RewriteRuleITokenStream(adaptor,"token 12");
RewriteRuleITokenStream stream_13=new RewriteRuleITokenStream(adaptor,"token 13");
RewriteRuleITokenStream stream_ID=new RewriteRuleITokenStream(adaptor,"token ID");
RewriteRuleSubtreeStream stream_expr=new RewriteRuleSubtreeStream(adaptor,"rule expr");
try
{
dbg.EnterRule( GrammarFileName, "atom" );
if ( RuleLevel == 0 )
{
dbg.Commence();
}
IncRuleLevel();
dbg.Location( 80, -1 );
try
{
// BuildOptions\\ProfileGrammar.g3:80:9: ( INT | ID | '(' expr ')' -> expr | ID '(' expr ')' -> ^( CALL ID expr ) )
int alt6=4;
try
{
dbg.EnterDecision( 6 );
switch ( input.LA(1) )
{
case INT:
{
alt6=1;
}
break;
case ID:
{
int LA6_2 = input.LA(2);
if ( (LA6_2==12) )
{
alt6=4;
}
else if ( (LA6_2==NEWLINE||(LA6_2>=10 && LA6_2<=11)||(LA6_2>=13 && LA6_2<=16)) )
{
alt6=2;
}
else
{
NoViableAltException nvae = new NoViableAltException("", 6, 2, input);
dbg.RecognitionException( nvae );
throw nvae;
}
}
break;
case 12:
{
alt6=3;
}
break;
default:
{
NoViableAltException nvae = new NoViableAltException("", 6, 0, input);
dbg.RecognitionException( nvae );
throw nvae;
}
}
}
finally
{
dbg.ExitDecision( 6 );
}
switch ( alt6 )
{
case 1:
dbg.EnterAlt( 1 );
// BuildOptions\\ProfileGrammar.g3:80:9: INT
{
root_0 = (CommonTree)adaptor.Nil();
dbg.Location( 80, 8 );
INT25=(IToken)Match(input,INT,Follow._INT_in_atom348);
INT25_tree = (CommonTree)adaptor.Create(INT25);
adaptor.AddChild(root_0, INT25_tree);
}
break;
case 2:
dbg.EnterAlt( 2 );
// BuildOptions\\ProfileGrammar.g3:81:9: ID
{
root_0 = (CommonTree)adaptor.Nil();
dbg.Location( 81, 8 );
ID26=(IToken)Match(input,ID,Follow._ID_in_atom358);
ID26_tree = (CommonTree)adaptor.Create(ID26);
adaptor.AddChild(root_0, ID26_tree);
}
break;
case 3:
dbg.EnterAlt( 3 );
// BuildOptions\\ProfileGrammar.g3:82:9: '(' expr ')'
{
dbg.Location( 82, 8 );
char_literal27=(IToken)Match(input,12,Follow._12_in_atom368);
stream_12.Add(char_literal27);
dbg.Location( 82, 12 );
PushFollow(Follow._expr_in_atom370);
expr28=expr();
state._fsp--;
stream_expr.Add(expr28.Tree);
dbg.Location( 82, 17 );
char_literal29=(IToken)Match(input,13,Follow._13_in_atom372);
stream_13.Add(char_literal29);
{
// AST REWRITE
// elements: expr
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 82:25: -> expr
{
dbg.Location( 82, 27 );
adaptor.AddChild(root_0, stream_expr.NextTree());
}
retval.tree = root_0;
}
}
break;
case 4:
dbg.EnterAlt( 4 );
// BuildOptions\\ProfileGrammar.g3:83:9: ID '(' expr ')'
{
dbg.Location( 83, 8 );
ID30=(IToken)Match(input,ID,Follow._ID_in_atom389);
stream_ID.Add(ID30);
dbg.Location( 83, 11 );
char_literal31=(IToken)Match(input,12,Follow._12_in_atom391);
stream_12.Add(char_literal31);
dbg.Location( 83, 15 );
PushFollow(Follow._expr_in_atom393);
expr32=expr();
state._fsp--;
stream_expr.Add(expr32.Tree);
dbg.Location( 83, 20 );
char_literal33=(IToken)Match(input,13,Follow._13_in_atom395);
stream_13.Add(char_literal33);
{
// AST REWRITE
// elements: ID, expr
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 83:25: -> ^( CALL ID expr )
{
dbg.Location( 83, 27 );
// BuildOptions\\ProfileGrammar.g3:83:28: ^( CALL ID expr )
{
CommonTree root_1 = (CommonTree)adaptor.Nil();
dbg.Location( 83, 29 );
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(CALL, "CALL"), root_1);
dbg.Location( 83, 34 );
adaptor.AddChild(root_1, stream_ID.NextNode());
dbg.Location( 83, 37 );
adaptor.AddChild(root_1, stream_expr.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
retval.tree = root_0;
}
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
}
dbg.Location(84, 4);
}
finally
{
dbg.ExitRule( GrammarFileName, "atom" );
DecRuleLevel();
if ( RuleLevel == 0 )
{
dbg.Terminate();
}
}
return retval;
}
// $ANTLR end "atom"
#endregion Rules
#region DFA
DFA2 dfa2;
protected override void InitDFAs()
{
base.InitDFAs();
dfa2 = new DFA2( this );
}
class DFA2 : DFA
{
const string DFA2_eotS =
"\xA\xFFFF";
const string DFA2_eofS =
"\xA\xFFFF";
const string DFA2_minS =
"\x1\x6\x1\xFFFF\x1\x8\x1\xFFFF\x1\x6\x1\xFFFF\x2\xA\x1\x8\x1\xFFFF";
const string DFA2_maxS =
"\x1\xC\x1\xFFFF\x1\x11\x1\xFFFF\x1\xC\x1\xFFFF\x2\x10\x1\x11\x1\xFFFF";
const string DFA2_acceptS =
"\x1\xFFFF\x1\x1\x1\xFFFF\x1\x4\x1\xFFFF\x1\x2\x3\xFFFF\x1\x3";
const string DFA2_specialS =
"\xA\xFFFF}>";
static readonly string[] DFA2_transitionS =
{
"\x1\x2\x1\x1\x1\x3\x3\xFFFF\x1\x1",
"",
"\x1\x1\x1\xFFFF\x2\x1\x1\x4\x1\xFFFF\x3\x1\x1\x5",
"",
"\x1\x7\x1\x6\x4\xFFFF\x1\x1",
"",
"\x2\x1\x1\xFFFF\x1\x8\x3\x1",
"\x3\x1\x1\x8\x3\x1",
"\x1\x1\x1\xFFFF\x2\x1\x2\xFFFF\x3\x1\x1\x9",
""
};
static readonly short[] DFA2_eot = DFA.UnpackEncodedString(DFA2_eotS);
static readonly short[] DFA2_eof = DFA.UnpackEncodedString(DFA2_eofS);
static readonly char[] DFA2_min = DFA.UnpackEncodedStringToUnsignedChars(DFA2_minS);
static readonly char[] DFA2_max = DFA.UnpackEncodedStringToUnsignedChars(DFA2_maxS);
static readonly short[] DFA2_accept = DFA.UnpackEncodedString(DFA2_acceptS);
static readonly short[] DFA2_special = DFA.UnpackEncodedString(DFA2_specialS);
static readonly short[][] DFA2_transition;
static DFA2()
{
int numStates = DFA2_transitionS.Length;
DFA2_transition = new short[numStates][];
for ( int i=0; i < numStates; i++ )
{
DFA2_transition[i] = DFA.UnpackEncodedString(DFA2_transitionS[i]);
}
}
public DFA2( BaseRecognizer recognizer )
{
this.recognizer = recognizer;
this.decisionNumber = 2;
this.eot = DFA2_eot;
this.eof = DFA2_eof;
this.min = DFA2_min;
this.max = DFA2_max;
this.accept = DFA2_accept;
this.special = DFA2_special;
this.transition = DFA2_transition;
}
public override string GetDescription()
{
return "53:0: stat : ( expr NEWLINE -> expr | ID '=' expr NEWLINE -> ^( '=' ID expr ) | func NEWLINE -> func | NEWLINE ->);";
}
public override void Error( NoViableAltException nvae )
{
((DebugParser)recognizer).dbg.RecognitionException( nvae );
}
}
#endregion DFA
#region Follow sets
private static class Follow
{
public static readonly BitSet _stat_in_prog53 = new BitSet(new ulong[]{0x11C2UL});
public static readonly BitSet _expr_in_stat70 = new BitSet(new ulong[]{0x100UL});
public static readonly BitSet _NEWLINE_in_stat72 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _ID_in_stat105 = new BitSet(new ulong[]{0x20000UL});
public static readonly BitSet _17_in_stat107 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _expr_in_stat109 = new BitSet(new ulong[]{0x100UL});
public static readonly BitSet _NEWLINE_in_stat111 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _func_in_stat143 = new BitSet(new ulong[]{0x100UL});
public static readonly BitSet _NEWLINE_in_stat145 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _NEWLINE_in_stat178 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _ID_in_func219 = new BitSet(new ulong[]{0x1000UL});
public static readonly BitSet _12_in_func222 = new BitSet(new ulong[]{0xC0UL});
public static readonly BitSet _formalPar_in_func224 = new BitSet(new ulong[]{0x2000UL});
public static readonly BitSet _13_in_func226 = new BitSet(new ulong[]{0x20000UL});
public static readonly BitSet _17_in_func228 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _expr_in_func230 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _set_in_formalPar267 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _multExpr_in_expr288 = new BitSet(new ulong[]{0x10402UL});
public static readonly BitSet _16_in_expr292 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _10_in_expr295 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _multExpr_in_expr299 = new BitSet(new ulong[]{0x10402UL});
public static readonly BitSet _atom_in_multExpr320 = new BitSet(new ulong[]{0xC802UL});
public static readonly BitSet _set_in_multExpr323 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _atom_in_multExpr332 = new BitSet(new ulong[]{0xC802UL});
public static readonly BitSet _INT_in_atom348 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _ID_in_atom358 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _12_in_atom368 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _expr_in_atom370 = new BitSet(new ulong[]{0x2000UL});
public static readonly BitSet _13_in_atom372 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _ID_in_atom389 = new BitSet(new ulong[]{0x1000UL});
public static readonly BitSet _12_in_atom391 = new BitSet(new ulong[]{0x10C0UL});
public static readonly BitSet _expr_in_atom393 = new BitSet(new ulong[]{0x2000UL});
public static readonly BitSet _13_in_atom395 = new BitSet(new ulong[]{0x2UL});
}
#endregion Follow sets
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
// The Windows implementation of PipeStream sets the stream's handle during
// creation, and as such should always have a handle, but the Unix implementation
// sometimes sets the handle not during creation but later during connection.
// As such, validation during member access needs to verify a valid handle on
// Windows, but can't assume a valid handle on Unix.
internal const bool CheckOperationsRequiresSetHandle = false;
/// <summary>Characters that can't be used in a pipe's name.</summary>
private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars();
/// <summary>Prefix to prepend to all pipe names.</summary>
private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_");
internal static string GetPipePath(string serverName, string pipeName, bool isCurrentUserOnly)
{
if (serverName != "." && serverName != Interop.Sys.GetHostName())
{
// Cross-machine pipes are not supported.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes);
}
if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
// Match Windows constraint
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0)
{
// Since pipes are stored as files in the file system, we don't support
// pipe names that are actually paths or that otherwise have invalid
// filename characters in them.
throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars);
}
// Return the pipe path. The pipe is created directly under %TMPDIR%. We previously
// didn't put it into a subdirectory because it only existed on disk for the duration
// between when the server started listening in WaitForConnection and when the client
// connected, after which the pipe was deleted. We now create the pipe when the
// server stream is created, which leaves it on disk longer, but we can't change the
// naming scheme used as that breaks the ability for code running on an older
// runtime to connect to code running on the newer runtime. That means we're stuck
// with a tmp file for the lifetime of the server stream.
if (isCurrentUserOnly)
{
string directory = Path.Combine(Path.GetTempPath(), ".NET" + Interop.Sys.GetEUid());
Directory.CreateDirectory(directory);
if (Interop.Sys.ChMod(directory, (int)Interop.Sys.Permissions.S_IRWXU) == -1)
{
throw CreateExceptionForLastError();
}
return Path.Combine(directory, pipeName);
}
return s_pipePrefix + pipeName;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
if (safePipeHandle.NamedPipeSocket == null)
{
Interop.Sys.FileStatus status;
int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status));
if (result == 0)
{
if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO &&
(status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// nop
}
internal virtual void DisposeCore(bool disposing)
{
// nop
}
private unsafe int ReadCore(Span<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, receive on the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Read syscall as is done
// for reading an anonymous pipe. However, for a non-blocking socket, Read could
// end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case
// is already handled by Socket.Receive, so we use it here.
try
{
return socket.Receive(buffer, SocketFlags.None);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, read from the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr, buffer.Length));
Debug.Assert(result <= buffer.Length);
return result;
}
}
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, send to the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Write syscall as is done
// for writing to anonymous pipe. However, for a non-blocking socket, Write could
// end up returning EWOULDBLOCK rather than blocking waiting for space available.
// Such a case is already handled by Socket.Send, so we use it here.
try
{
while (buffer.Length > 0)
{
int bytesWritten = socket.Send(buffer, SocketFlags.None);
buffer = buffer.Slice(bytesWritten);
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, write the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
while (buffer.Length > 0)
{
int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr, buffer.Length));
buffer = buffer.Slice(bytesWritten);
}
}
}
private async Task<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
Socket socket = InternalHandle.NamedPipeSocket;
try
{
// TODO #22608:
// Remove all of this cancellation workaround once Socket.ReceiveAsync
// that accepts a CancellationToken is available.
// If a cancelable token is used and there's no data, issue a zero-length read so that
// we're asynchronously notified when data is available, and concurrently monitor the
// supplied cancellation token. If cancellation is requested, we will end up "leaking"
// the zero-length read until data becomes available, at which point it'll be satisfied.
// But it's very rare to reuse a stream after an operation has been canceled, so even if
// we do incur such a situation, it's likely to be very short lived.
if (cancellationToken.CanBeCanceled)
{
cancellationToken.ThrowIfCancellationRequested();
if (socket.Available == 0)
{
Task<int> t = socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None);
if (!t.IsCompletedSuccessfully)
{
var cancelTcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs))
{
if (t == await Task.WhenAny(t, cancelTcs.Task).ConfigureAwait(false))
{
t.GetAwaiter().GetResult(); // propagate any failure
}
cancellationToken.ThrowIfCancellationRequested();
// At this point there was data available. In the rare case where multiple concurrent
// ReadAsyncs are issued against the PipeStream, worst case is the reads that lose
// the race condition for the data will end up in a non-cancelable state as part of
// the actual async receive operation.
}
}
}
}
// Issue the asynchronous read.
return await (destination.TryGetArray(out ArraySegment<byte> buffer) ?
socket.ReceiveAsync(buffer, SocketFlags.None) :
socket.ReceiveAsync(destination.ToArray(), SocketFlags.None)).ConfigureAwait(false);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
// TODO #22608: Remove this terribly inefficient special-case once Socket.SendAsync
// accepts a Memory<T> in the near future.
byte[] buffer;
int offset, count;
if (MemoryMarshal.TryGetArray(source, out ArraySegment<byte> segment))
{
buffer = segment.Array;
offset = segment.Offset;
count = segment.Count;
}
else
{
buffer = source.ToArray();
offset = 0;
count = buffer.Length;
}
while (count > 0)
{
// cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if
// cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and
// most writes will complete immediately as they simply store data into the socket's buffer. The only time we end
// up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation.
cancellationToken.ThrowIfCancellationRequested();
int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
Debug.Assert(bytesWritten <= count);
count -= bytesWritten;
offset += bytesWritten;
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private IOException GetIOExceptionForSocketException(SocketException e)
{
if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE
{
State = PipeState.Broken;
}
return new IOException(e.Message, e);
}
// Blocks until the other end of the pipe has read in all written buffer.
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// For named pipes on sockets, we could potentially partially implement this
// via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However,
// that would require polling, and it wouldn't actually mean that the other
// end has read all of the data, just that the data has left this end's buffer.
throw new PlatformNotSupportedException(); // not fully implementable on unix
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return GetPipeBufferSize();
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return GetPipeBufferSize();
}
}
public virtual PipeTransmissionMode ReadMode
{
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// nop, since it's already the only valid value
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// We want to ensure that only one asynchronous operation is actually in flight
/// at a time. The base Stream class ensures this by serializing execution via a
/// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due
/// to having specialized support for cancellation, we do the same serialization here.
/// </summary>
private SemaphoreSlim _asyncActiveSemaphore;
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
private static void CreateDirectory(string directoryPath)
{
int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask);
// If successful created, we're done.
if (result >= 0)
return;
// If the directory already exists, consider it a success.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
return;
// Otherwise, fail.
throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
}
/// <summary>Creates an anonymous pipe.</summary>
/// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param>
/// <param name="reader">The resulting reader end of the pipe.</param>
/// <param name="writer">The resulting writer end of the pipe.</param>
internal static unsafe void CreateAnonymousPipe(
HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer)
{
// Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
reader = new SafePipeHandle();
writer = new SafePipeHandle();
// Create the OS pipe
int* fds = stackalloc int[2];
CreateAnonymousPipe(inheritability, fds);
// Store the file descriptors into our safe handles
reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
}
internal int CheckPipeCall(int result)
{
if (result == -1)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
State = PipeState.Broken;
throw Interop.GetExceptionForIoErrno(errorInfo);
}
return result;
}
private int GetPipeBufferSize()
{
if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
{
throw new PlatformNotSupportedException(); // OS does not support getting pipe size
}
// If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
// If we don't, just return the buffer size that was passed to the constructor.
return _handle != null ?
CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) :
_outBufferSize;
}
internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr)
{
var flags = (inheritability & HandleInheritability.Inheritable) == 0 ?
Interop.Sys.PipeFlags.O_CLOEXEC : 0;
Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags));
}
internal static void ConfigureSocket(
Socket s, SafePipeHandle pipeHandle,
PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
{
if (inBufferSize > 0)
{
s.ReceiveBufferSize = inBufferSize;
}
if (outBufferSize > 0)
{
s.SendBufferSize = outBufferSize;
}
if (inheritability != HandleInheritability.Inheritable)
{
Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt
}
switch (direction)
{
case PipeDirection.In:
s.Shutdown(SocketShutdown.Send);
break;
case PipeDirection.Out:
s.Shutdown(SocketShutdown.Receive);
break;
}
}
internal static Exception CreateExceptionForLastError(string pipeName = null)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
return error.Error == Interop.Error.ENOTSUP ?
new PlatformNotSupportedException(SR.Format(SR.PlatformNotSupported_OperatingSystemError, nameof(Interop.Error.ENOTSUP))) :
Interop.GetExceptionForIoErrno(error, pipeName);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------
//------------------------------------------------------------
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
namespace System.Xml
{
internal abstract class XmlStreamNodeWriter : XmlNodeWriter
{
private Stream _stream;
private byte[] _buffer;
private int _offset;
private bool _ownsStream;
private const int bufferLength = 512;
private const int maxEntityLength = 32;
private const int maxBytesPerChar = 3;
private Encoding _encoding;
private static UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true);
protected XmlStreamNodeWriter()
{
_buffer = new byte[bufferLength];
}
protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
{
_stream = stream;
_ownsStream = ownsStream;
_offset = 0;
_encoding = encoding;
}
// Getting/Setting the Stream exists for fragmenting
public Stream Stream
{
get
{
return _stream;
}
set
{
_stream = value;
}
}
// StreamBuffer/BufferOffset exists only for the BinaryWriter to fix up nodes
public byte[] StreamBuffer
{
get
{
return _buffer;
}
}
public int BufferOffset
{
get
{
return _offset;
}
}
public int Position
{
get
{
return (int)_stream.Position + _offset;
}
}
private int GetByteCount(char[] chars)
{
if (_encoding == null)
{
return s_UTF8Encoding.GetByteCount(chars);
}
else
{
return _encoding.GetByteCount(chars);
}
}
protected byte[] GetBuffer(int count, out int offset)
{
DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, "");
int bufferOffset = _offset;
if (bufferOffset + count <= bufferLength)
{
offset = bufferOffset;
}
else
{
FlushBuffer();
offset = 0;
}
#if DEBUG
DiagnosticUtility.DebugAssert(offset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
_buffer[offset + i] = (byte)'<';
}
#endif
return _buffer;
}
protected void Advance(int count)
{
DiagnosticUtility.DebugAssert(_offset + count <= bufferLength, "");
_offset += count;
}
private void EnsureByte()
{
if (_offset >= bufferLength)
{
FlushBuffer();
}
}
protected void WriteByte(byte b)
{
EnsureByte();
_buffer[_offset++] = b;
}
protected void WriteByte(char ch)
{
DiagnosticUtility.DebugAssert(ch < 0x80, "");
WriteByte((byte)ch);
}
protected void WriteBytes(byte b1, byte b2)
{
byte[] buffer = _buffer;
int offset = _offset;
if (offset + 1 >= bufferLength)
{
FlushBuffer();
offset = 0;
}
buffer[offset + 0] = b1;
buffer[offset + 1] = b2;
_offset += 2;
}
protected void WriteBytes(char ch1, char ch2)
{
DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, "");
WriteBytes((byte)ch1, (byte)ch2);
}
public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount)
{
if (byteCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(byteCount, out offset);
Buffer.BlockCopy(byteBuffer, byteOffset, buffer, offset, byteCount);
Advance(byteCount);
}
else
{
FlushBuffer();
_stream.Write(byteBuffer, byteOffset, byteCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteBytes(byte* bytes, int byteCount)
{
FlushBuffer();
byte[] buffer = _buffer;
while (byteCount >= bufferLength)
{
for (int i = 0; i < bufferLength; i++)
buffer[i] = bytes[i];
_stream.Write(buffer, 0, bufferLength);
bytes += bufferLength;
byteCount -= bufferLength;
}
{
for (int i = 0; i < byteCount; i++)
buffer[i] = bytes[i];
_stream.Write(buffer, 0, byteCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe protected void WriteUTF8Char(int ch)
{
if (ch < 0x80)
{
WriteByte((byte)ch);
}
else if (ch <= char.MaxValue)
{
char* chars = stackalloc char[1];
chars[0] = (char)ch;
UnsafeWriteUTF8Chars(chars, 1);
}
else
{
SurrogateChar surrogateChar = new SurrogateChar(ch);
char* chars = stackalloc char[2];
chars[0] = surrogateChar.HighChar;
chars[1] = surrogateChar.LowChar;
UnsafeWriteUTF8Chars(chars, 2);
}
}
protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount)
{
if (charCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(charCount, out offset);
Buffer.BlockCopy(chars, charOffset, buffer, offset, charCount);
Advance(charCount);
}
else
{
FlushBuffer();
_stream.Write(chars, charOffset, charCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe protected void WriteUTF8Chars(string value)
{
int count = value.Length;
if (count > 0)
{
fixed (char* chars = value)
{
UnsafeWriteUTF8Chars(chars, count);
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteUTF8Chars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / maxBytesPerChar;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, charCount, buffer, offset));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteUnicodeChars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / 2;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, charCount, buffer, offset));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
char value = *chars++;
buffer[offset++] = (byte)value;
value >>= 8;
buffer[offset++] = (byte)value;
}
return charCount * 2;
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Length(char* chars, int charCount)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
if (*chars >= 0x80)
break;
chars++;
}
if (chars == charsMax)
return charCount;
char[] chArray = new char[charsMax - chars];
for (int i = 0; i < chArray.Length; i++)
{
chArray[i] = chars[i];
}
return (int)(chars - (charsMax - charCount)) + GetByteCount(chArray);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset)
{
if (charCount > 0)
{
fixed (byte* _bytes = &buffer[offset])
{
byte* bytes = _bytes;
byte* bytesMax = &bytes[buffer.Length - offset];
char* charsMax = &chars[charCount];
while (true)
{
while (chars < charsMax && *chars < 0x80)
{
*bytes = (byte)*chars;
bytes++;
chars++;
}
if (chars >= charsMax)
break;
char* charsStart = chars;
while (chars < charsMax && *chars >= 0x80)
{
chars++;
}
string tmp = new string(charsStart, 0, (int)(chars - charsStart));
byte[] newBytes = _encoding != null ? _encoding.GetBytes(tmp) : s_UTF8Encoding.GetBytes(tmp);
int toCopy = Math.Min(newBytes.Length, (int)(bytesMax - bytes));
Array.Copy(newBytes, 0, buffer, (int)(bytes - _bytes) + offset, toCopy);
bytes += toCopy;
if (chars >= charsMax)
break;
}
return (int)(bytes - _bytes);
}
}
return 0;
}
protected virtual void FlushBuffer()
{
if (_offset != 0)
{
_stream.Write(_buffer, 0, _offset);
_offset = 0;
}
}
public override void Flush()
{
FlushBuffer();
_stream.Flush();
}
public override void Close()
{
if (_stream != null)
{
if (_ownsStream)
{
_stream.Dispose();
}
_stream = null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) Copyright 2002 Franklin Wise
// (C) Copyright 2002 Rodrigo Moya
// (C) Copyright 2003 Daniel Morgan
// (C) Copyright 2003 Martin Willemoes Hansen
// (C) Copyright 2011 Xamarin Inc
//
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Data.SqlTypes;
using Xunit;
namespace System.Data.Tests
{
public class DataColumnTest
{
private DataTable _tbl;
public DataColumnTest()
{
_tbl = new DataTable();
}
[Fact]
public void Ctor()
{
string colName = "ColName";
DataColumn col = new DataColumn();
//These should all ctor without an exception
col = new DataColumn(colName);
col = new DataColumn(colName, typeof(int));
col = new DataColumn(colName, typeof(int), null);
col = new DataColumn(colName, typeof(int), null, MappingType.Attribute);
}
[Fact]
public void Constructor3_DataType_Null()
{
try
{
new DataColumn("ColName", null);
Assert.False(true);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
// Never premise English.
// Assert.NotNull (ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("dataType", ex.ParamName);
}
}
[Fact]
public void AllowDBNull()
{
DataColumn col = new DataColumn("NullCheck", typeof(int));
_tbl.Columns.Add(col);
col.AllowDBNull = true;
_tbl.Rows.Add(_tbl.NewRow());
_tbl.Rows[0]["NullCheck"] = DBNull.Value;
try
{
col.AllowDBNull = false;
Assert.False(true);
}
catch (DataException)
{
}
}
[Fact]
public void AllowDBNull1()
{
DataTable tbl = _tbl;
tbl.Columns.Add("id", typeof(int));
tbl.Columns.Add("name", typeof(string));
tbl.PrimaryKey = new DataColumn[] { tbl.Columns["id"] };
tbl.Rows.Add(new object[] { 1, "RowState 1" });
tbl.Rows.Add(new object[] { 2, "RowState 2" });
tbl.Rows.Add(new object[] { 3, "RowState 3" });
tbl.AcceptChanges();
// Update Table with following changes: Row0 unmodified,
// Row1 modified, Row2 deleted, Row3 added, Row4 not-present.
tbl.Rows[1]["name"] = "Modify 2";
tbl.Rows[2].Delete();
DataColumn col = tbl.Columns["name"];
col.AllowDBNull = true;
col.AllowDBNull = false;
Assert.False(col.AllowDBNull);
}
[Fact]
public void AutoIncrement()
{
DataColumn col = new DataColumn("Auto", typeof(string));
col.AutoIncrement = true;
//Check for Correct Default Values
Assert.Equal(0L, col.AutoIncrementSeed);
Assert.Equal(1L, col.AutoIncrementStep);
//Check for auto type convert
Assert.Equal(typeof(int), col.DataType);
}
[Fact]
public void AutoIncrementExceptions()
{
DataColumn col = new DataColumn();
col.Expression = "SomeExpression";
//if computed column exception is thrown
try
{
col.AutoIncrement = true;
Assert.False(true);
}
catch (ArgumentException)
{
}
}
[Fact]
public void Caption()
{
DataColumn col = new DataColumn("ColName");
//Caption not set at this point
Assert.Equal(col.ColumnName, col.Caption);
//Set caption
col.Caption = "MyCaption";
Assert.Equal("MyCaption", col.Caption);
//Clear caption
col.Caption = null;
Assert.Equal(string.Empty, col.Caption);
}
[Fact]
public void DateTimeMode_Valid()
{
DataColumn col = new DataColumn("birthdate", typeof(DateTime));
col.DateTimeMode = DataSetDateTime.Local;
Assert.Equal(DataSetDateTime.Local, col.DateTimeMode);
col.DateTimeMode = DataSetDateTime.Unspecified;
Assert.Equal(DataSetDateTime.Unspecified, col.DateTimeMode);
col.DateTimeMode = DataSetDateTime.Utc;
Assert.Equal(DataSetDateTime.Utc, col.DateTimeMode);
}
[Fact]
public void DateTime_DataType_Invalid()
{
DataColumn col = new DataColumn("birthdate", typeof(int));
try
{
col.DateTimeMode = DataSetDateTime.Local;
Assert.False(true);
}
catch (InvalidOperationException ex)
{
// The DateTimeMode can be set only on DataColumns
// of type DateTime
Assert.Equal(typeof(InvalidOperationException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("DateTimeMode") != -1);
Assert.True(ex.Message.IndexOf("DateTime") != -1);
}
}
[Fact]
public void DateTimeMode_Invalid()
{
DataColumn col = new DataColumn("birthdate", typeof(DateTime));
try
{
col.DateTimeMode = (DataSetDateTime)666;
Assert.False(true);
}
catch (InvalidEnumArgumentException ex)
{
// The DataSetDateTime enumeration value, 666, is invalid
Assert.Equal(typeof(InvalidEnumArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("DataSetDateTime") != -1);
Assert.True(ex.Message.IndexOf("666") != -1);
Assert.Null(ex.ParamName);
}
}
[Fact]
public void ForColumnNameException()
{
DataColumn col = new DataColumn();
DataColumn col2 = new DataColumn();
DataColumn col3 = new DataColumn();
DataColumn col4 = new DataColumn();
col.ColumnName = "abc";
Assert.Equal("abc", col.ColumnName);
_tbl.Columns.Add(col);
//Duplicate name exception
try
{
col2.ColumnName = "abc";
_tbl.Columns.Add(col2);
Assert.Equal("abc", col2.ColumnName);
Assert.False(true);
}
catch (DuplicateNameException)
{
}
// Make sure case matters in duplicate checks
col3.ColumnName = "ABC";
_tbl.Columns.Add(col3);
}
[Fact]
public void DefaultValue()
{
DataTable tbl = new DataTable();
tbl.Columns.Add("MyCol", typeof(int));
//Set default Value if Autoincrement is true
tbl.Columns[0].AutoIncrement = true;
try
{
tbl.Columns[0].DefaultValue = 2;
Assert.False(true);
}
catch (ArgumentException)
{
}
tbl.Columns[0].AutoIncrement = false;
//Set default value to an incompatible datatype
try
{
tbl.Columns[0].DefaultValue = "hello";
Assert.False(true);
}
catch (FormatException)
{
}
}
[Fact]
public void Defaults1()
{
//Check for defaults - ColumnName not set at the beginning
DataTable table = new DataTable();
DataColumn column = new DataColumn();
Assert.Equal(string.Empty, column.ColumnName);
Assert.Equal(typeof(string), column.DataType);
table.Columns.Add(column);
Assert.Equal("Column1", table.Columns[0].ColumnName);
Assert.Equal(typeof(string), table.Columns[0].DataType);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataRow dataRow = table.Rows[0];
object v = dataRow.ItemArray[0];
Assert.Equal(typeof(DBNull), v.GetType());
Assert.Equal(DBNull.Value, v);
}
[Fact]
public void Defaults2()
{
//Check for defaults - ColumnName set at the beginning
string blah = "Blah";
//Check for defaults - ColumnName not set at the beginning
DataTable table = new DataTable();
DataColumn column = new DataColumn(blah);
Assert.Equal(blah, column.ColumnName);
Assert.Equal(typeof(string), column.DataType);
table.Columns.Add(column);
Assert.Equal(blah, table.Columns[0].ColumnName);
Assert.Equal(typeof(string), table.Columns[0].DataType);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataRow dataRow = table.Rows[0];
object v = dataRow.ItemArray[0];
Assert.Equal(typeof(DBNull), v.GetType());
Assert.Equal(DBNull.Value, v);
}
[Fact]
public void Defaults3()
{
DataColumn col = new DataColumn("foo", typeof(SqlBoolean));
Assert.Equal(SqlBoolean.Null, col.DefaultValue);
col.DefaultValue = SqlBoolean.True;
// FIXME: not working yet
//col.DefaultValue = true;
//Assert.Equal (SqlBoolean.True, col.DefaultValue);
col.DefaultValue = DBNull.Value;
Assert.Equal(SqlBoolean.Null, col.DefaultValue);
}
[Fact]
public void ChangeTypeAfterSettingDefaultValue()
{
Assert.Throws<DataException>(() =>
{
DataColumn col = new DataColumn("foo", typeof(SqlBoolean));
col.DefaultValue = true;
col.DataType = typeof(int);
});
}
[Fact]
public void ExpressionSubstringlimits()
{
DataTable t = new DataTable();
t.Columns.Add("aaa");
t.Rows.Add(new object[] { "xxx" });
DataColumn c = t.Columns.Add("bbb");
try
{
c.Expression = "SUBSTRING(aaa, 6000000000000000, 2)";
Assert.False(true);
}
catch (OverflowException)
{
}
}
[Fact]
public void ExpressionFunctions()
{
DataTable T = new DataTable("test");
DataColumn C = new DataColumn("name");
T.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T.Columns.Add(C);
C = new DataColumn("id");
C.Expression = "substring (name, 1, 3) + len (name) + age";
T.Columns.Add(C);
DataSet Set = new DataSet("TestSet");
Set.Tables.Add(T);
DataRow Row = null;
for (int i = 0; i < 100; i++)
{
Row = T.NewRow();
Row[0] = "human" + i;
Row[1] = i;
T.Rows.Add(Row);
}
Row = T.NewRow();
Row[0] = "h*an";
Row[1] = DBNull.Value;
T.Rows.Add(Row);
Assert.Equal("hum710", T.Rows[10][2]);
Assert.Equal("hum64", T.Rows[4][2]);
C = T.Columns[2];
C.Expression = "isnull (age, 'succ[[]]ess')";
Assert.Equal("succ[[]]ess", T.Rows[100][2]);
C.Expression = "iif (age = 24, 'hurrey', 'boo')";
Assert.Equal("boo", T.Rows[50][2]);
Assert.Equal("hurrey", T.Rows[24][2]);
C.Expression = "convert (age, 'System.Boolean')";
Assert.Equal(bool.TrueString, T.Rows[50][2]);
Assert.Equal(bool.FalseString, T.Rows[0][2]);
//
// Exceptions
//
try
{
// The expression contains undefined function call iff().
C.Expression = "iff (age = 24, 'hurrey', 'boo')";
Assert.False(true);
}
catch (EvaluateException)
{
}
catch (SyntaxErrorException)
{
}
//The following two cases fail on mono. MS.net evaluates the expression
//immediatly upon assignment. We don't do this yet hence we don't throw
//an exception at this point.
try
{
C.Expression = "iif (nimi = 24, 'hurrey', 'boo')";
Assert.False(true);
}
catch (EvaluateException e)
{
Assert.Equal(typeof(EvaluateException), e.GetType());
// Never premise English.
//Assert.Equal ("Cannot find column [nimi].", e.Message);
}
try
{
C.Expression = "iif (name = 24, 'hurrey', 'boo')";
Assert.False(true);
}
catch (EvaluateException e)
{
Assert.Equal(typeof(EvaluateException), e.GetType());
//AssertEquals ("DC41", "Cannot perform '=' operation on System.String and System.Int32.", e.Message);
}
try
{
C.Expression = "convert (age, Boolean)";
Assert.False(true);
}
catch (EvaluateException e)
{
Assert.Equal(typeof(EvaluateException), e.GetType());
// Never premise English.
//Assert.Equal ("Invalid type name 'Boolean'.", e.Message);
}
}
[Fact]
public void ExpressionAggregates()
{
DataTable T = new DataTable("test");
DataTable T2 = new DataTable("test2");
DataColumn C = new DataColumn("name");
T.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T.Columns.Add(C);
C = new DataColumn("childname");
T.Columns.Add(C);
C = new DataColumn("expression");
T.Columns.Add(C);
DataSet Set = new DataSet("TestSet");
Set.Tables.Add(T);
Set.Tables.Add(T2);
DataRow Row = null;
for (int i = 0; i < 100; i++)
{
Row = T.NewRow();
Row[0] = "human" + i;
Row[1] = i;
Row[2] = "child" + i;
T.Rows.Add(Row);
}
Row = T.NewRow();
Row[0] = "h*an";
Row[1] = DBNull.Value;
T.Rows.Add(Row);
C = new DataColumn("name");
T2.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T2.Columns.Add(C);
for (int i = 0; i < 100; i++)
{
Row = T2.NewRow();
Row[0] = "child" + i;
Row[1] = i;
T2.Rows.Add(Row);
Row = T2.NewRow();
Row[0] = "child" + i;
Row[1] = i - 2;
T2.Rows.Add(Row);
}
DataRelation Rel = new DataRelation("Rel", T.Columns[2], T2.Columns[0]);
Set.Relations.Add(Rel);
C = T.Columns[3];
C.Expression = "Sum (Child.age)";
Assert.Equal("-2", T.Rows[0][3]);
Assert.Equal("98", T.Rows[50][3]);
C.Expression = "Count (Child.age)";
Assert.Equal("2", T.Rows[0][3]);
Assert.Equal("2", T.Rows[60][3]);
C.Expression = "Avg (Child.age)";
Assert.Equal("-1", T.Rows[0][3]);
Assert.Equal("59", T.Rows[60][3]);
C.Expression = "Min (Child.age)";
Assert.Equal("-2", T.Rows[0][3]);
Assert.Equal("58", T.Rows[60][3]);
C.Expression = "Max (Child.age)";
Assert.Equal("0", T.Rows[0][3]);
Assert.Equal("60", T.Rows[60][3]);
C.Expression = "stdev (Child.age)";
Assert.Equal((1.4142135623731).ToString(T.Locale), T.Rows[0][3]);
Assert.Equal((1.4142135623731).ToString(T.Locale), T.Rows[60][3]);
C.Expression = "var (Child.age)";
Assert.Equal("2", T.Rows[0][3]);
Assert.Equal("2", T.Rows[60][3]);
}
[Fact]
public void ExpressionOperator()
{
DataTable T = new DataTable("test");
DataColumn C = new DataColumn("name");
T.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T.Columns.Add(C);
C = new DataColumn("id");
C.Expression = "substring (name, 1, 3) + len (name) + age";
T.Columns.Add(C);
DataSet Set = new DataSet("TestSet");
Set.Tables.Add(T);
DataRow Row = null;
for (int i = 0; i < 100; i++)
{
Row = T.NewRow();
Row[0] = "human" + i;
Row[1] = i;
T.Rows.Add(Row);
}
Row = T.NewRow();
Row[0] = "h*an";
Row[1] = DBNull.Value;
T.Rows.Add(Row);
C = T.Columns[2];
C.Expression = "age + 4";
Assert.Equal("68", T.Rows[64][2]);
C.Expression = "age - 4";
Assert.Equal("60", T.Rows[64][2]);
C.Expression = "age * 4";
Assert.Equal("256", T.Rows[64][2]);
C.Expression = "age / 4";
Assert.Equal("16", T.Rows[64][2]);
C.Expression = "age % 5";
Assert.Equal("4", T.Rows[64][2]);
C.Expression = "age in (5, 10, 15, 20, 25)";
Assert.Equal("False", T.Rows[64][2]);
Assert.Equal("True", T.Rows[25][2]);
C.Expression = "name like 'human1%'";
Assert.Equal("True", T.Rows[1][2]);
Assert.Equal("False", T.Rows[25][2]);
C.Expression = "age < 4";
Assert.Equal("False", T.Rows[4][2]);
Assert.Equal("True", T.Rows[3][2]);
C.Expression = "age <= 4";
Assert.Equal("True", T.Rows[4][2]);
Assert.Equal("False", T.Rows[5][2]);
C.Expression = "age > 4";
Assert.Equal("False", T.Rows[4][2]);
Assert.Equal("True", T.Rows[5][2]);
C.Expression = "age >= 4";
Assert.Equal("True", T.Rows[4][2]);
Assert.Equal("False", T.Rows[1][2]);
C.Expression = "age = 4";
Assert.Equal("True", T.Rows[4][2]);
Assert.Equal("False", T.Rows[1][2]);
C.Expression = "age <> 4";
Assert.Equal("False", T.Rows[4][2]);
Assert.Equal("True", T.Rows[1][2]);
}
[Fact]
public void SetMaxLengthException()
{
// Setting MaxLength on SimpleContent -> exception
DataSet ds = new DataSet("Example");
ds.Tables.Add("MyType");
ds.Tables["MyType"].Columns.Add(new DataColumn("Desc",
typeof(string), "", MappingType.SimpleContent));
try
{
ds.Tables["MyType"].Columns["Desc"].MaxLength = 32;
Assert.False(true);
}
catch (ArgumentException)
{
}
}
[Fact]
public void SetMaxLengthNegativeValue()
{
// however setting MaxLength on SimpleContent is OK
DataSet ds = new DataSet("Example");
ds.Tables.Add("MyType");
ds.Tables["MyType"].Columns.Add(
new DataColumn("Desc", typeof(string), "", MappingType.SimpleContent));
ds.Tables["MyType"].Columns["Desc"].MaxLength = -1;
}
[Fact]
public void AdditionToConstraintCollectionTest()
{
DataTable myTable = new DataTable("myTable");
DataColumn idCol = new DataColumn("id", typeof(int));
idCol.Unique = true;
myTable.Columns.Add(idCol);
ConstraintCollection cc = myTable.Constraints;
//cc just contains a single UniqueConstraint object.
UniqueConstraint uc = cc[0] as UniqueConstraint;
Assert.Equal("id", uc.Columns[0].ColumnName);
}
[Fact]
public void CalcStatisticalFunction_SingleElement()
{
DataTable table = new DataTable();
table.Columns.Add("test", typeof(int));
table.Rows.Add(new object[] { 0 });
table.Columns.Add("result_var", typeof(double), "var(test)");
table.Columns.Add("result_stdev", typeof(double), "stdev(test)");
// Check DBNull.Value is set as the result
Assert.Equal(typeof(DBNull), (table.Rows[0]["result_var"]).GetType());
Assert.Equal(typeof(DBNull), (table.Rows[0]["result_stdev"]).GetType());
}
[Fact]
public void Aggregation_CheckIfChangesDynamically()
{
DataTable table = new DataTable();
table.Columns.Add("test", typeof(int));
table.Columns.Add("result_count", typeof(int), "count(test)");
table.Columns.Add("result_sum", typeof(int), "sum(test)");
table.Columns.Add("result_avg", typeof(int), "avg(test)");
table.Columns.Add("result_max", typeof(int), "max(test)");
table.Columns.Add("result_min", typeof(int), "min(test)");
table.Columns.Add("result_var", typeof(double), "var(test)");
table.Columns.Add("result_stdev", typeof(double), "stdev(test)");
// Adding the rows after all the expression columns are added
table.Rows.Add(new object[] { 0 });
Assert.Equal(1, table.Rows[0]["result_count"]);
Assert.Equal(0, table.Rows[0]["result_sum"]);
Assert.Equal(0, table.Rows[0]["result_avg"]);
Assert.Equal(0, table.Rows[0]["result_max"]);
Assert.Equal(0, table.Rows[0]["result_min"]);
Assert.Equal(DBNull.Value, table.Rows[0]["result_var"]);
Assert.Equal(DBNull.Value, table.Rows[0]["result_stdev"]);
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { -2 });
// Check if the aggregate columns are updated correctly
Assert.Equal(3, table.Rows[0]["result_count"]);
Assert.Equal(-1, table.Rows[0]["result_sum"]);
Assert.Equal(0, table.Rows[0]["result_avg"]);
Assert.Equal(1, table.Rows[0]["result_max"]);
Assert.Equal(-2, table.Rows[0]["result_min"]);
Assert.Equal((7.0 / 3), table.Rows[0]["result_var"]);
Assert.Equal(Math.Sqrt(7.0 / 3), table.Rows[0]["result_stdev"]);
}
[Fact]
public void Aggregation_CheckIfChangesDynamically_ChildTable()
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
DataTable table2 = new DataTable();
ds.Tables.Add(table);
ds.Tables.Add(table2);
table.Columns.Add("test", typeof(int));
table2.Columns.Add("test", typeof(int));
table2.Columns.Add("val", typeof(int));
DataRelation rel = new DataRelation("rel", table.Columns[0], table2.Columns[0]);
ds.Relations.Add(rel);
table.Columns.Add("result_count", typeof(int), "count(child.test)");
table.Columns.Add("result_sum", typeof(int), "sum(child.test)");
table.Columns.Add("result_avg", typeof(int), "avg(child.test)");
table.Columns.Add("result_max", typeof(int), "max(child.test)");
table.Columns.Add("result_min", typeof(int), "min(child.test)");
table.Columns.Add("result_var", typeof(double), "var(child.test)");
table.Columns.Add("result_stdev", typeof(double), "stdev(child.test)");
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { 2 });
// Add rows to the child table
for (int j = 0; j < 10; j++)
table2.Rows.Add(new object[] { 1, j });
// Check the values for the expression columns in parent table
Assert.Equal(10, table.Rows[0]["result_count"]);
Assert.Equal(0, table.Rows[1]["result_count"]);
Assert.Equal(10, table.Rows[0]["result_sum"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_sum"]);
Assert.Equal(1, table.Rows[0]["result_avg"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_avg"]);
Assert.Equal(1, table.Rows[0]["result_max"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_max"]);
Assert.Equal(1, table.Rows[0]["result_min"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_min"]);
Assert.Equal(0.0, table.Rows[0]["result_var"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_var"]);
Assert.Equal(0.0, table.Rows[0]["result_stdev"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_stdev"]);
}
[Fact]
public void Aggregation_TestForSyntaxErrors()
{
string error = "Aggregation functions cannot be called on Singular(Parent) Columns";
DataSet ds = new DataSet();
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
DataTable table3 = new DataTable();
table1.Columns.Add("test", typeof(int));
table2.Columns.Add("test", typeof(int));
table3.Columns.Add("test", typeof(int));
ds.Tables.Add(table1);
ds.Tables.Add(table2);
ds.Tables.Add(table3);
DataRelation rel1 = new DataRelation("rel1", table1.Columns[0], table2.Columns[0]);
DataRelation rel2 = new DataRelation("rel2", table2.Columns[0], table3.Columns[0]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
error = "Aggregation Functions cannot be called on Columns Returning Single Row (Parent Column)";
try
{
table2.Columns.Add("result", typeof(int), "count(parent.test)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
error = "Numerical or Functions cannot be called on Columns Returning Multiple Rows (Child Column)";
// Check arithematic operator
try
{
table2.Columns.Add("result", typeof(int), "10*(child.test)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
// Check rel operator
try
{
table2.Columns.Add("result", typeof(int), "(child.test) > 10");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
// Check predicates
try
{
table2.Columns.Add("result", typeof(int), "(child.test) IN (1,2,3)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
try
{
table2.Columns.Add("result", typeof(int), "(child.test) LIKE 1");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
try
{
table2.Columns.Add("result", typeof(int), "(child.test) IS null");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
// Check Calc Functions
try
{
table2.Columns.Add("result", typeof(int), "isnull(child.test,10)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
}
[Fact]
public void CheckValuesAfterRemovedFromCollection()
{
DataTable table = new DataTable("table1");
DataColumn col1 = new DataColumn("col1", typeof(int));
DataColumn col2 = new DataColumn("col2", typeof(int));
Assert.Equal(-1, col1.Ordinal);
Assert.Null(col1.Table);
table.Columns.Add(col1);
table.Columns.Add(col2);
Assert.Equal(0, col1.Ordinal);
Assert.Equal(table, col1.Table);
table.Columns.RemoveAt(0);
Assert.Equal(-1, col1.Ordinal);
Assert.Null(col1.Table);
table.Columns.Clear();
Assert.Equal(-1, col2.Ordinal);
Assert.Null(col2.Table);
}
[Fact]
public void B565616_NonIConvertibleTypeTest()
{
try
{
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
dt.Columns.Add("ID", typeof(string));
DataRow row = dt.NewRow();
row["ID"] = id;
Assert.Equal(id.ToString(), row["ID"]);
}
catch (InvalidCastException ex)
{
Assert.False(true);
}
}
[Fact]
public void B623451_SetOrdinalTest()
{
try
{
DataTable t = new DataTable();
t.Columns.Add("one");
t.Columns.Add("two");
t.Columns.Add("three");
Assert.Equal("one", t.Columns[0].ColumnName);
Assert.Equal("two", t.Columns[1].ColumnName);
Assert.Equal("three", t.Columns[2].ColumnName);
t.Columns["three"].SetOrdinal(0);
Assert.Equal("three", t.Columns[0].ColumnName);
Assert.Equal("one", t.Columns[1].ColumnName);
Assert.Equal("two", t.Columns[2].ColumnName);
t.Columns["three"].SetOrdinal(1);
Assert.Equal("one", t.Columns[0].ColumnName);
Assert.Equal("three", t.Columns[1].ColumnName);
Assert.Equal("two", t.Columns[2].ColumnName);
}
catch (ArgumentOutOfRangeException ex)
{
Assert.False(true);
}
}
[Fact]
public void Xamarin665()
{
var t = new DataTable();
var c1 = t.Columns.Add("c1");
var c2 = t.Columns.Add("c2");
c2.Expression = "TRIM(ISNULL(c1,' '))";
c2.Expression = "SUBSTRING(ISNULL(c1,' '), 1, 10)";
}
[Fact]
public void NonSqlNullableType_RequiresPublicStaticNull()
{
var t = new DataTable();
var c1 = t.Columns.Add("c1", typeof(NullableTypeWithNullProperty));
var c2 = t.Columns.Add("c2", typeof(NullableTypeWithNullField));
Assert.Throws<ArgumentException>(() => t.Columns.Add("c3", typeof(NullableTypeWithoutNullMember)));
}
private sealed class NullableTypeWithNullProperty : INullable
{
public bool IsNull => true;
public static NullableTypeWithNullProperty Null { get; } = new NullableTypeWithNullProperty();
}
private sealed class NullableTypeWithNullField : INullable
{
public bool IsNull => true;
public static readonly NullableTypeWithNullField Null = new NullableTypeWithNullField();
}
private sealed class NullableTypeWithoutNullMember : INullable
{
public bool IsNull => true;
}
private DataColumn MakeColumn(string col, string test)
{
return new DataColumn()
{
ColumnName = col,
Expression = test
};
}
#if false
// Check Windows output for the row [0] value
[Fact]
public void NullStrings ()
{
var a = MakeColumn ("nullbar", "null+'bar'");
var b = MakeColumn ("barnull", "'bar'+null");
var c = MakeColumn ("foobar", "'foo'+'bar'");
var table = new DataTable();
table.Columns.Add(a);
table.Columns.Add(b);
table.Columns.Add(c);
var row = table.NewRow();
table.Rows.Add(row);
Assert.Equal (row [0], DBNull.Value);
Assert.Equal (row [1], DBNull.Value);
Assert.Equal (row [2], "foobar");
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Enables instruction counting and displaying stats at process exit.
// #define STATS
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Dynamic.Utils;
namespace System.Linq.Expressions.Interpreter
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
[DebuggerTypeProxy(typeof(InstructionArray.DebugView))]
internal struct InstructionArray
{
internal readonly int MaxStackDepth;
internal readonly int MaxContinuationDepth;
internal readonly Instruction[] Instructions;
internal readonly object[] Objects;
internal readonly RuntimeLabel[] Labels;
// list of (instruction index, cookie) sorted by instruction index:
internal readonly List<KeyValuePair<int, object>> DebugCookies;
internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions,
object[] objects, RuntimeLabel[] labels, List<KeyValuePair<int, object>> debugCookies)
{
MaxStackDepth = maxStackDepth;
MaxContinuationDepth = maxContinuationDepth;
Instructions = instructions;
DebugCookies = debugCookies;
Objects = objects;
Labels = labels;
}
internal int Length
{
get { return Instructions.Length; }
}
#region Debug View
internal sealed class DebugView
{
private readonly InstructionArray _array;
public DebugView(InstructionArray array)
{
_array = array;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public InstructionList.DebugView.InstructionView[]/*!*/ A0
{
get
{
return InstructionList.DebugView.GetInstructionViews(
_array.Instructions,
_array.Objects,
(index) => _array.Labels[index].Index,
_array.DebugCookies
);
}
}
}
#endregion
}
[DebuggerTypeProxy(typeof(InstructionList.DebugView))]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class InstructionList
{
private readonly List<Instruction> _instructions = new List<Instruction>();
private List<object> _objects;
private int _currentStackDepth;
private int _maxStackDepth;
private int _currentContinuationsDepth;
private int _maxContinuationDepth;
private int _runtimeLabelCount;
private List<BranchLabel> _labels;
// list of (instruction index, cookie) sorted by instruction index:
private List<KeyValuePair<int, object>> _debugCookies = null;
#region Debug View
internal sealed class DebugView
{
private readonly InstructionList _list;
public DebugView(InstructionList list)
{
_list = list;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public InstructionView[]/*!*/ A0
{
get
{
return GetInstructionViews(
_list._instructions,
_list._objects,
(index) => _list._labels[index].TargetIndex,
_list._debugCookies
);
}
}
internal static InstructionView[] GetInstructionViews(IList<Instruction> instructions, IList<object> objects,
Func<int, int> labelIndexer, IList<KeyValuePair<int, object>> debugCookies)
{
var result = new List<InstructionView>();
int index = 0;
int stackDepth = 0;
int continuationsDepth = 0;
var cookieEnumerator = (debugCookies != null ? debugCookies : new KeyValuePair<int, object>[0]).GetEnumerator();
var hasCookie = cookieEnumerator.MoveNext();
for (int i = 0; i < instructions.Count; i++)
{
object cookie = null;
while (hasCookie && cookieEnumerator.Current.Key == i)
{
cookie = cookieEnumerator.Current.Value;
hasCookie = cookieEnumerator.MoveNext();
}
int stackDiff = instructions[i].StackBalance;
int contDiff = instructions[i].ContinuationsBalance;
string name = instructions[i].ToDebugString(i, cookie, labelIndexer, objects);
result.Add(new InstructionView(instructions[i], name, i, stackDepth, continuationsDepth));
index++;
stackDepth += stackDiff;
continuationsDepth += contDiff;
}
return result.ToArray();
}
[DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")]
internal struct InstructionView
{
private readonly int _index;
private readonly int _stackDepth;
private readonly int _continuationsDepth;
private readonly string _name;
private readonly Instruction _instruction;
internal string GetName()
{
return _index +
(_continuationsDepth == 0 ? "" : " C(" + _continuationsDepth + ")") +
(_stackDepth == 0 ? "" : " S(" + _stackDepth + ")");
}
internal string GetValue()
{
return _name;
}
internal string GetDisplayType()
{
return _instruction.ContinuationsBalance + "/" + _instruction.StackBalance;
}
public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth)
{
_instruction = instruction;
_name = name;
_index = index;
_stackDepth = stackDepth;
_continuationsDepth = continuationsDepth;
}
}
}
#endregion
#region Core Emit Ops
public void Emit(Instruction instruction)
{
_instructions.Add(instruction);
UpdateStackDepth(instruction);
}
private void UpdateStackDepth(Instruction instruction)
{
Debug.Assert(instruction.ConsumedStack >= 0 && instruction.ProducedStack >= 0 &&
instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0, "bad instruction " + instruction.ToString());
_currentStackDepth -= instruction.ConsumedStack;
Debug.Assert(_currentStackDepth >= 0, "negative stack depth " + instruction.ToString());
_currentStackDepth += instruction.ProducedStack;
if (_currentStackDepth > _maxStackDepth)
{
_maxStackDepth = _currentStackDepth;
}
_currentContinuationsDepth -= instruction.ConsumedContinuations;
Debug.Assert(_currentContinuationsDepth >= 0, "negative continuations " + instruction.ToString());
_currentContinuationsDepth += instruction.ProducedContinuations;
if (_currentContinuationsDepth > _maxContinuationDepth)
{
_maxContinuationDepth = _currentContinuationsDepth;
}
}
/// <summary>
/// Attaches a cookie to the last emitted instruction.
/// </summary>
[Conditional("DEBUG")]
public void SetDebugCookie(object cookie)
{
#if DEBUG
if (_debugCookies == null)
{
_debugCookies = new List<KeyValuePair<int, object>>();
}
Debug.Assert(Count > 0);
_debugCookies.Add(new KeyValuePair<int, object>(Count - 1, cookie));
#endif
}
public int Count
{
get { return _instructions.Count; }
}
public int CurrentStackDepth
{
get { return _currentStackDepth; }
}
public int CurrentContinuationsDepth
{
get { return _currentContinuationsDepth; }
}
public int MaxStackDepth
{
get { return _maxStackDepth; }
}
internal Instruction GetInstruction(int index)
{
return _instructions[index];
}
#if STATS
private static Dictionary<string, int> _executedInstructions = new Dictionary<string, int>();
private static Dictionary<string, Dictionary<object, bool>> _instances = new Dictionary<string, Dictionary<object, bool>>();
static InstructionList()
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler((_, __) =>
{
PerfTrack.DumpHistogram(_executedInstructions);
Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, (sum, value) => sum + value));
Console.WriteLine("-----");
var referenced = new Dictionary<string, int>();
int total = 0;
foreach (var entry in _instances)
{
referenced[entry.Key] = entry.Value.Count;
total += entry.Value.Count;
}
PerfTrack.DumpHistogram(referenced);
Console.WriteLine("-- Total referenced: {0}", total);
Console.WriteLine("-----");
});
}
#endif
public InstructionArray ToArray()
{
#if STATS
lock (_executedInstructions)
{
_instructions.ForEach((instr) =>
{
int value = 0;
var name = instr.GetType().Name;
_executedInstructions.TryGetValue(name, out value);
_executedInstructions[name] = value + 1;
Dictionary<object, bool> dict;
if (!_instances.TryGetValue(name, out dict))
{
_instances[name] = dict = new Dictionary<object, bool>();
}
dict[instr] = true;
});
}
#endif
return new InstructionArray(
_maxStackDepth,
_maxContinuationDepth,
_instructions.ToArray(),
(_objects != null) ? _objects.ToArray() : null,
BuildRuntimeLabels(),
_debugCookies
);
}
#endregion
#region Stack Operations
private const int PushIntMinCachedValue = -100;
private const int PushIntMaxCachedValue = 100;
private const int CachedObjectCount = 256;
private static Instruction s_null;
private static Instruction s_true;
private static Instruction s_false;
private static Instruction[] s_ints;
private static Instruction[] s_loadObjectCached;
public void EmitLoad(object value)
{
EmitLoad(value, null);
}
public void EmitLoad(bool value)
{
if ((bool)value)
{
Emit(s_true ?? (s_true = new LoadObjectInstruction(value)));
}
else
{
Emit(s_false ?? (s_false = new LoadObjectInstruction(value)));
}
}
public void EmitLoad(object value, Type type)
{
if (value == null)
{
Emit(s_null ?? (s_null = new LoadObjectInstruction(null)));
return;
}
if (type == null || type.GetTypeInfo().IsValueType)
{
if (value is bool)
{
EmitLoad((bool)value);
return;
}
if (value is int)
{
int i = (int)value;
if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue)
{
if (s_ints == null)
{
s_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1];
}
i -= PushIntMinCachedValue;
Emit(s_ints[i] ?? (s_ints[i] = new LoadObjectInstruction(value)));
return;
}
}
}
if (_objects == null)
{
_objects = new List<object>();
if (s_loadObjectCached == null)
{
s_loadObjectCached = new Instruction[CachedObjectCount];
}
}
if (_objects.Count < s_loadObjectCached.Length)
{
uint index = (uint)_objects.Count;
_objects.Add(value);
Emit(s_loadObjectCached[index] ?? (s_loadObjectCached[index] = new LoadCachedObjectInstruction(index)));
}
else
{
Emit(new LoadObjectInstruction(value));
}
}
public void EmitDup()
{
Emit(DupInstruction.Instance);
}
public void EmitPop()
{
Emit(PopInstruction.Instance);
}
#endregion
#region Locals
internal void SwitchToBoxed(int index, int instructionIndex)
{
var instruction = _instructions[instructionIndex] as IBoxableInstruction;
if (instruction != null)
{
var newInstruction = instruction.BoxIfIndexMatches(index);
if (newInstruction != null)
{
_instructions[instructionIndex] = newInstruction;
}
}
}
private const int LocalInstrCacheSize = 64;
private static Instruction[] s_loadLocal;
private static Instruction[] s_loadLocalBoxed;
private static Instruction[] s_loadLocalFromClosure;
private static Instruction[] s_loadLocalFromClosureBoxed;
private static Instruction[] s_assignLocal;
private static Instruction[] s_storeLocal;
private static Instruction[] s_assignLocalBoxed;
private static Instruction[] s_storeLocalBoxed;
private static Instruction[] s_assignLocalToClosure;
public void EmitLoadLocal(int index)
{
if (s_loadLocal == null)
{
s_loadLocal = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocal.Length)
{
Emit(s_loadLocal[index] ?? (s_loadLocal[index] = new LoadLocalInstruction(index)));
}
else
{
Emit(new LoadLocalInstruction(index));
}
}
public void EmitLoadLocalBoxed(int index)
{
Emit(LoadLocalBoxed(index));
}
internal static Instruction LoadLocalBoxed(int index)
{
if (s_loadLocalBoxed == null)
{
s_loadLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocalBoxed.Length)
{
return s_loadLocalBoxed[index] ?? (s_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index));
}
else
{
return new LoadLocalBoxedInstruction(index);
}
}
public void EmitLoadLocalFromClosure(int index)
{
if (s_loadLocalFromClosure == null)
{
s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocalFromClosure.Length)
{
Emit(s_loadLocalFromClosure[index] ?? (s_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index)));
}
else
{
Emit(new LoadLocalFromClosureInstruction(index));
}
}
public void EmitLoadLocalFromClosureBoxed(int index)
{
if (s_loadLocalFromClosureBoxed == null)
{
s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocalFromClosureBoxed.Length)
{
Emit(s_loadLocalFromClosureBoxed[index] ?? (s_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index)));
}
else
{
Emit(new LoadLocalFromClosureBoxedInstruction(index));
}
}
public void EmitAssignLocal(int index)
{
if (s_assignLocal == null)
{
s_assignLocal = new Instruction[LocalInstrCacheSize];
}
if (index < s_assignLocal.Length)
{
Emit(s_assignLocal[index] ?? (s_assignLocal[index] = new AssignLocalInstruction(index)));
}
else
{
Emit(new AssignLocalInstruction(index));
}
}
public void EmitStoreLocal(int index)
{
if (s_storeLocal == null)
{
s_storeLocal = new Instruction[LocalInstrCacheSize];
}
if (index < s_storeLocal.Length)
{
Emit(s_storeLocal[index] ?? (s_storeLocal[index] = new StoreLocalInstruction(index)));
}
else
{
Emit(new StoreLocalInstruction(index));
}
}
public void EmitAssignLocalBoxed(int index)
{
Emit(AssignLocalBoxed(index));
}
internal static Instruction AssignLocalBoxed(int index)
{
if (s_assignLocalBoxed == null)
{
s_assignLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_assignLocalBoxed.Length)
{
return s_assignLocalBoxed[index] ?? (s_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index));
}
else
{
return new AssignLocalBoxedInstruction(index);
}
}
public void EmitStoreLocalBoxed(int index)
{
Emit(StoreLocalBoxed(index));
}
internal static Instruction StoreLocalBoxed(int index)
{
if (s_storeLocalBoxed == null)
{
s_storeLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_storeLocalBoxed.Length)
{
return s_storeLocalBoxed[index] ?? (s_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index));
}
else
{
return new StoreLocalBoxedInstruction(index);
}
}
public void EmitAssignLocalToClosure(int index)
{
if (s_assignLocalToClosure == null)
{
s_assignLocalToClosure = new Instruction[LocalInstrCacheSize];
}
if (index < s_assignLocalToClosure.Length)
{
Emit(s_assignLocalToClosure[index] ?? (s_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index)));
}
else
{
Emit(new AssignLocalToClosureInstruction(index));
}
}
public void EmitStoreLocalToClosure(int index)
{
EmitAssignLocalToClosure(index);
EmitPop();
}
public void EmitInitializeLocal(int index, Type type)
{
object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type);
if (value != null)
{
Emit(new InitializeLocalInstruction.ImmutableValue(index, value));
}
else if (type.GetTypeInfo().IsValueType)
{
Emit(new InitializeLocalInstruction.MutableValue(index, type));
}
else
{
Emit(InitReference(index));
}
}
internal void EmitInitializeParameter(int index, Type parameterType)
{
Emit(Parameter(index, parameterType));
}
internal static Instruction Parameter(int index, Type parameterType)
{
return new InitializeLocalInstruction.Parameter(index, parameterType);
}
internal static Instruction ParameterBox(int index)
{
return new InitializeLocalInstruction.ParameterBox(index);
}
internal static Instruction InitReference(int index)
{
return new InitializeLocalInstruction.Reference(index);
}
internal static Instruction InitImmutableRefBox(int index)
{
return new InitializeLocalInstruction.ImmutableRefBox(index);
}
public void EmitNewRuntimeVariables(int count)
{
Emit(new RuntimeVariablesInstruction(count));
}
#endregion
#region Array Operations
public void EmitGetArrayItem()
{
Emit(GetArrayItemInstruction.Instruction);
}
public void EmitSetArrayItem()
{
Emit(new SetArrayItemInstruction());
}
public void EmitNewArray(Type elementType)
{
Emit(new NewArrayInstruction(elementType));
}
public void EmitNewArrayBounds(Type elementType, int rank)
{
Emit(new NewArrayBoundsInstruction(elementType, rank));
}
public void EmitNewArrayInit(Type elementType, int elementCount)
{
Emit(new NewArrayInitInstruction(elementType, elementCount));
}
#endregion
#region Arithmetic Operations
public void EmitAdd(Type type, bool @checked)
{
if (@checked)
{
Emit(AddOvfInstruction.Create(type));
}
else
{
Emit(AddInstruction.Create(type));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitSub(Type type, bool @checked)
{
if (@checked)
{
Emit(SubOvfInstruction.Create(type));
}
else
{
Emit(SubInstruction.Create(type));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitMul(Type type, bool @checked)
{
if (@checked)
{
Emit(MulOvfInstruction.Create(type));
}
else
{
Emit(MulInstruction.Create(type));
}
}
public void EmitDiv(Type type)
{
Emit(DivInstruction.Create(type));
}
public void EmitModulo(Type type)
{
Emit(ModuloInstruction.Create(type));
}
#endregion
#region Comparisons
public void EmitExclusiveOr(Type type)
{
Emit(ExclusiveOrInstruction.Create(type));
}
public void EmitAnd(Type type)
{
Emit(AndInstruction.Create(type));
}
public void EmitOr(Type type)
{
Emit(OrInstruction.Create(type));
}
public void EmitLeftShift(Type type)
{
Emit(LeftShiftInstruction.Create(type));
}
public void EmitRightShift(Type type)
{
Emit(RightShiftInstruction.Create(type));
}
public void EmitEqual(Type type, bool liftedToNull = false)
{
Emit(EqualInstruction.Create(type, liftedToNull));
}
public void EmitNotEqual(Type type, bool liftedToNull = false)
{
Emit(NotEqualInstruction.Create(type, liftedToNull));
}
public void EmitLessThan(Type type, bool liftedToNull)
{
Emit(LessThanInstruction.Create(type, liftedToNull));
}
public void EmitLessThanOrEqual(Type type, bool liftedToNull)
{
Emit(LessThanOrEqualInstruction.Create(type, liftedToNull));
}
public void EmitGreaterThan(Type type, bool liftedToNull)
{
Emit(GreaterThanInstruction.Create(type, liftedToNull));
}
public void EmitGreaterThanOrEqual(Type type, bool liftedToNull)
{
Emit(GreaterThanOrEqualInstruction.Create(type, liftedToNull));
}
#endregion
#region Conversions
public void EmitNumericConvertChecked(TypeCode from, TypeCode to, bool isLiftedToNull)
{
Emit(new NumericConvertInstruction.Checked(from, to, isLiftedToNull));
}
public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to, bool isLiftedToNull)
{
Emit(new NumericConvertInstruction.Unchecked(from, to, isLiftedToNull));
}
public void EmitCast(Type toType)
{
Emit(CastInstruction.Create(toType));
}
public void EmitCastToEnum(Type toType)
{
Emit(new CastToEnumInstruction(toType));
}
#endregion
#region Boolean Operators
public void EmitNot(Type type)
{
Emit(NotInstruction.Create(type));
}
#endregion
#region Types
public void EmitDefaultValue(Type type)
{
Emit(new DefaultValueInstruction(type));
}
public void EmitNew(ConstructorInfo constructorInfo)
{
Emit(new NewInstruction(constructorInfo));
}
public void EmitByRefNew(ConstructorInfo constructorInfo, ByRefUpdater[] updaters)
{
Emit(new ByRefNewInstruction(constructorInfo, updaters));
}
internal void EmitCreateDelegate(LightDelegateCreator creator)
{
Emit(new CreateDelegateInstruction(creator));
}
public void EmitTypeEquals()
{
Emit(TypeEqualsInstruction.Instance);
}
public void EmitNullableTypeEquals()
{
Emit(NullableTypeEqualsInstruction.Instance);
}
public void EmitArrayLength()
{
Emit(ArrayLengthInstruction.Instance);
}
public void EmitNegate(Type type)
{
Emit(NegateInstruction.Create(type));
}
public void EmitNegateChecked(Type type)
{
Emit(NegateCheckedInstruction.Create(type));
}
public void EmitOnesComplement(Type type)
{
Emit(OnesComplementInstruction.Create(type));
}
public void EmitIncrement(Type type)
{
Emit(IncrementInstruction.Create(type));
}
public void EmitDecrement(Type type)
{
Emit(DecrementInstruction.Create(type));
}
public void EmitTypeIs(Type type)
{
Emit(new TypeIsInstruction(type));
}
public void EmitTypeAs(Type type)
{
Emit(new TypeAsInstruction(type));
}
#endregion
#region Fields and Methods
private static readonly Dictionary<FieldInfo, Instruction> s_loadFields = new Dictionary<FieldInfo, Instruction>();
public void EmitLoadField(FieldInfo field)
{
Emit(GetLoadField(field));
}
private Instruction GetLoadField(FieldInfo field)
{
lock (s_loadFields)
{
Instruction instruction;
if (!s_loadFields.TryGetValue(field, out instruction))
{
if (field.IsStatic)
{
instruction = new LoadStaticFieldInstruction(field);
}
else
{
instruction = new LoadFieldInstruction(field);
}
s_loadFields.Add(field, instruction);
}
return instruction;
}
}
public void EmitStoreField(FieldInfo field)
{
if (field.IsStatic)
{
Emit(new StoreStaticFieldInstruction(field));
}
else
{
Emit(new StoreFieldInstruction(field));
}
}
public void EmitCall(MethodInfo method)
{
EmitCall(method, method.GetParameters());
}
public void EmitCall(MethodInfo method, ParameterInfo[] parameters)
{
Emit(CallInstruction.Create(method, parameters));
}
public void EmitByRefCall(MethodInfo method, ParameterInfo[] parameters, ByRefUpdater[] byrefArgs)
{
Emit(new ByRefMethodInfoCallInstruction(method, method.IsStatic ? parameters.Length : parameters.Length + 1, byrefArgs));
}
public void EmitNullableCall(MethodInfo method, ParameterInfo[] parameters)
{
Emit(NullableMethodCallInstruction.Create(method.Name, parameters.Length, method));
}
#endregion
#region Control Flow
private static readonly RuntimeLabel[] s_emptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) };
private RuntimeLabel[] BuildRuntimeLabels()
{
if (_runtimeLabelCount == 0)
{
return s_emptyRuntimeLabels;
}
var result = new RuntimeLabel[_runtimeLabelCount + 1];
foreach (BranchLabel label in _labels)
{
if (label.HasRuntimeLabel)
{
result[label.LabelIndex] = label.ToRuntimeLabel();
}
}
// "return and rethrow" label:
result[result.Length - 1] = new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0);
return result;
}
public BranchLabel MakeLabel()
{
if (_labels == null)
{
_labels = new List<BranchLabel>();
}
var label = new BranchLabel();
_labels.Add(label);
return label;
}
internal void FixupBranch(int branchIndex, int offset)
{
_instructions[branchIndex] = ((OffsetInstruction)_instructions[branchIndex]).Fixup(offset);
}
private int EnsureLabelIndex(BranchLabel label)
{
if (label.HasRuntimeLabel)
{
return label.LabelIndex;
}
label.LabelIndex = _runtimeLabelCount;
_runtimeLabelCount++;
return label.LabelIndex;
}
public int MarkRuntimeLabel()
{
BranchLabel handlerLabel = MakeLabel();
MarkLabel(handlerLabel);
return EnsureLabelIndex(handlerLabel);
}
public void MarkLabel(BranchLabel label)
{
label.Mark(this);
}
public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue, bool labelTargetGetsValue)
{
Emit(GotoInstruction.Create(EnsureLabelIndex(label), hasResult, hasValue, labelTargetGetsValue));
}
private void EmitBranch(OffsetInstruction instruction, BranchLabel label)
{
Emit(instruction);
label.AddBranch(this, Count - 1);
}
public void EmitBranch(BranchLabel label)
{
EmitBranch(new BranchInstruction(), label);
}
public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue)
{
EmitBranch(new BranchInstruction(hasResult, hasValue), label);
}
public void EmitCoalescingBranch(BranchLabel leftNotNull)
{
EmitBranch(new CoalescingBranchInstruction(), leftNotNull);
}
public void EmitBranchTrue(BranchLabel elseLabel)
{
EmitBranch(new BranchTrueInstruction(), elseLabel);
}
public void EmitBranchFalse(BranchLabel elseLabel)
{
EmitBranch(new BranchFalseInstruction(), elseLabel);
}
public void EmitThrow()
{
Emit(ThrowInstruction.Throw);
}
public void EmitThrowVoid()
{
Emit(ThrowInstruction.VoidThrow);
}
public void EmitRethrow()
{
Emit(ThrowInstruction.Rethrow);
}
public void EmitRethrowVoid()
{
Emit(ThrowInstruction.VoidRethrow);
}
public void EmitEnterTryFinally(BranchLabel finallyStartLabel)
{
Emit(EnterTryCatchFinallyInstruction.CreateTryFinally(EnsureLabelIndex(finallyStartLabel)));
}
public void EmitEnterTryCatch()
{
Emit(EnterTryCatchFinallyInstruction.CreateTryCatch());
}
public void EmitEnterFinally(BranchLabel finallyStartLabel)
{
Emit(EnterFinallyInstruction.Create(EnsureLabelIndex(finallyStartLabel)));
}
public void EmitLeaveFinally()
{
Emit(LeaveFinallyInstruction.Instance);
}
public void EmitLeaveFault(bool hasValue)
{
Emit(hasValue ? LeaveFaultInstruction.NonVoid : LeaveFaultInstruction.Void);
}
public void EmitEnterExceptionHandlerNonVoid()
{
Emit(EnterExceptionHandlerInstruction.NonVoid);
}
public void EmitEnterExceptionHandlerVoid()
{
Emit(EnterExceptionHandlerInstruction.Void);
}
public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel)
{
Emit(LeaveExceptionHandlerInstruction.Create(EnsureLabelIndex(tryExpressionEndLabel), hasValue));
}
public void EmitIntSwitch<T>(Dictionary<T, int> cases)
{
Emit(new IntSwitchInstruction<T>(cases));
}
public void EmitStringSwitch(Dictionary<string, int> cases, StrongBox<int> nullCase)
{
Emit(new StringSwitchInstruction(cases, nullCase));
}
#endregion
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal class CGUnzipFiles
{
//
// UnZip Class
//
// Chris Eastwood July 1999
//
public enum ZMessageLevel
{
All = 0,
Less = 1,
NoMessages = 2
}
public enum ZExtractType
{
Extract = 0,
ListContents = 1
}
public enum ZPrivilege
{
Ignore = 0,
ACL = 1,
Privileges = 2
}
// 1 = Extract Only Newer, Else 0
private short miExtractNewer;
// 1 = Convert Space To Underscore, Else 0
private short miSpaceUnderScore;
// 1 = Prompt To Overwrite Required, Else 0
private short miPromptOverwrite;
// 2 = No Messages, 1 = Less, 0 = All
private ZMessageLevel miQuiet;
// 1 = Write To Stdout, Else 0
private short miWriteStdOut;
// 1 = Test Zip File, Else 0
private short miTestZip;
// 0 = Extract, 1 = List Contents
private ZExtractType miExtractList;
// 1 = Extract Only Newer, Else 0
private short miExtractOnlyNewer;
// 1 = Display Zip File Comment, Else 0
private short miDisplayComment;
// 1 = Honor Directories, Else 0
private short miHonorDirectories;
// 1 = Overwrite Files, Else 0
private short miOverWriteFiles;
// 1 = Convert CR To CRLF, Else 0
private short miConvertCR_CRLF;
// 1 = Zip Info Verbose
private short miVerbose;
// 1 = Case Insensitivity, 0 = Case Sensitivity
private short miCaseSensitivity;
// 1 = ACL, 2 = Privileges, Else 0
private ZPrivilege miPrivilege;
// The Zip File Name
private string msZipFileName;
// Extraction Directory, Null If Current Directory
private string msExtractDir;
public bool ExtractNewer {
get { return miExtractNewer == 1; }
set { miExtractNewer = (value ? 1 : 0); }
}
public bool SpaceToUnderScore {
get { return miSpaceUnderScore == 1; }
set { miSpaceUnderScore = (value ? 1 : 0); }
}
public bool PromptOverwrite {
get { return miPromptOverwrite == 1; }
set { miPromptOverwrite = (value ? 1 : 0); }
}
public ZMessageLevel MessageLevel {
get { return miQuiet; }
set { miQuiet = value; }
}
public bool WriteToStdOut {
get { return miWriteStdOut == 1; }
set { miWriteStdOut = (value ? 1 : 0); }
}
public bool TestZip {
get { return miTestZip == 1; }
set { miTestZip = (value ? 1 : 0); }
}
public ZExtractType ExtractList {
get { return miExtractList; }
set { miExtractList = value; }
}
public bool ExtractOnlyNewer {
get { return miExtractOnlyNewer == 1; }
set { miExtractOnlyNewer = (value ? 1 : 0); }
}
public bool DisplayComment {
get { return miDisplayComment == 1; }
set { miDisplayComment = (value ? 1 : 0); }
}
public bool HonorDirectories {
get { return miHonorDirectories == 1; }
set { miHonorDirectories = (value ? 1 : 0); }
}
public bool OverWriteFiles {
get { return miOverWriteFiles == 1; }
set { miOverWriteFiles = (value ? 1 : 0); }
}
public bool ConvertCRtoCRLF {
get { return miConvertCR_CRLF == 1; }
set { miConvertCR_CRLF = (value ? 1 : 0); }
}
public bool Verbose {
get { return miVerbose == 1; }
set { miVerbose = (value ? 1 : 0); }
}
public bool CaseSensitive {
get { return miCaseSensitivity == 1; }
set { miCaseSensitivity = (value ? 1 : 0); }
}
public ZPrivilege Privilege {
get { return miPrivilege; }
set { miPrivilege = value; }
}
public string ZipFileName {
get { return msZipFileName; }
set { msZipFileName = value; }
}
public string ExtractDir {
get { return msExtractDir; }
set { msExtractDir = value; }
}
public int Unzip(ref string sZipFileName = "", ref string sExtractDir = "")
{
int functionReturnValue = 0;
// ERROR: Not supported in C#: OnErrorStatement
int lRet = 0;
if (Strings.Len(sZipFileName) > 0) {
msZipFileName = sZipFileName;
}
if (Strings.Len(sExtractDir) > 0) {
msExtractDir = sExtractDir;
}
lRet = CodeModule.VBUnzip(ref msZipFileName, ref msExtractDir, ref miExtractNewer, ref miSpaceUnderScore, ref miPromptOverwrite, ref Convert.ToInt16(miQuiet), ref miWriteStdOut, ref miTestZip, ref Convert.ToInt16(miExtractList), ref miExtractOnlyNewer,
ref miDisplayComment, ref miHonorDirectories, ref miOverWriteFiles, ref miConvertCR_CRLF, ref miVerbose, ref miCaseSensitivity, ref Convert.ToInt16(miPrivilege));
functionReturnValue = lRet;
return functionReturnValue;
vbErrorHandler:
Err().Raise(Err().Number, "CGUnZipFiles::Unzip", Err().Description);
return functionReturnValue;
}
//UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
private void Class_Initialize_Renamed()
{
miExtractNewer = 0;
miSpaceUnderScore = 0;
miPromptOverwrite = 0;
miQuiet = ZMessageLevel.NoMessages;
miWriteStdOut = 0;
miTestZip = 0;
miExtractList = ZExtractType.Extract;
miExtractOnlyNewer = 0;
miDisplayComment = 0;
miHonorDirectories = 1;
miOverWriteFiles = 1;
miConvertCR_CRLF = 0;
miVerbose = 0;
miCaseSensitivity = 1;
miPrivilege = ZPrivilege.Ignore;
}
public CGUnzipFiles() : base()
{
Class_Initialize_Renamed();
}
public string GetLastMessage()
{
return CodeModule.msOutput;
}
}
}
| |
// 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.Xml;
using System.Diagnostics; // for the debugger display attribute
using System.Collections;
using System.Collections.Generic;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is responsible for executing the target. Target only executs once within a project,
/// so this class comes into existance for the execution and is thrown away once the execution is
/// complete. It wraps all of the data and methods needed to execute a target. The execution
/// is done via state machine with three primary states - BuildingDependencies, RunningTasks,
/// BuildingErrorClause. This states map to the primary actions that are performed during target
/// execution. The execution is blocking in single threaded mode and is iterative in multi-threaded
/// mode.
/// </summary>
[DebuggerDisplay("Target (Name = { Name }, State = { inProgressBuildState })")]
internal class TargetExecutionWrapper
{
#region Constructors
internal TargetExecutionWrapper
(
Target targetClass,
ArrayList taskElementList,
List<string> targetParameters,
XmlElement targetElement,
Expander expander,
BuildEventContext targetBuildEventContext
)
{
// Initialize the data about the target XML that has been calculated in the target class
this.targetClass = targetClass;
this.parentEngine = targetClass.ParentEngine;
this.parentProject = targetClass.ParentProject;
this.targetElement = targetElement;
this.taskElementList = taskElementList;
this.targetParameters = targetParameters;
this.targetBuildEventContext = targetBuildEventContext;
// Expand the list of depends on targets
dependsOnTargetNames = expander.ExpandAllIntoStringList(targetClass.DependsOnTargets, targetClass.DependsOnTargetsAttribute);
// Starting to build the target
inProgressBuildState = InProgressBuildState.StartingBuild;
// No messages have been logged
loggedTargetStart = false;
}
#endregion
#region Data
// Local cache of data from the target being executed
private Target targetClass;
private Engine parentEngine;
private Project parentProject;
private XmlElement targetElement;
private ArrayList taskElementList;
private List<string> targetParameters;
private ProjectBuildState initiatingBuildContext;
private BuildEventContext targetBuildEventContext;
// Current state of the execution
private InProgressBuildState inProgressBuildState;
private bool overallSuccess;
// the outputs of the target as BuildItems (if it builds successfully)
private List<BuildItem> targetOutputItems;
private List<ProjectBuildState> waitingTargets;
// Names of the dependent targets
private List<string> dependsOnTargetNames;
private int currentDependentTarget;
// Names of the error targets (lazily initialized on error)
private List<string> onErrorTargets;
private int currentErrorTarget;
// Array of buckets and the index of current bucket
private ArrayList buckets;
private int currentBucket;
private bool haveRunANonIntrinsicTask = false;
// Lookup containing project content used to
// initialize the target batches
private Lookup projectContent;
private LookupEntry placeholderForClonedProjectContent;
// State for execution within a particular bucket
private DependencyAnalysisResult howToBuild;
private Lookup lookupForInference;
private Lookup lookupForExecution;
private string projectFileOfTaskNode;
private int currentTask;
private int skippedNodeCount;
private bool targetBuildSuccessful;
private bool exitBatchDueToError;
private bool loggedTargetStart;
#endregion
#region Properties
internal ProjectBuildState InitiatingBuildContext
{
get
{
return this.initiatingBuildContext;
}
}
internal bool BuildingRequiredTargets
{
get
{
return (inProgressBuildState == InProgressBuildState.BuildingDependencies ||
inProgressBuildState == InProgressBuildState.BuildingErrorClause);
}
}
#endregion
#region Methods
internal void ContinueBuild
(
ProjectBuildState buildContext, TaskExecutionContext taskExecutionContext
)
{
// Verify that the target is in progress
ErrorUtilities.VerifyThrow(inProgressBuildState != InProgressBuildState.NotInProgress, "Not in progress");
bool exitedDueToError = true;
try
{
// In the single threaded mode we want to avoid looping all the way back to the
// engine because there is no need for to be interruptable to address
// other build requests. Instead we loop inside this function untill the target is
// fully built.
do
{
// Transition the state machine appropriatly
if (inProgressBuildState == InProgressBuildState.RunningTasks)
{
ContinueRunningTasks(buildContext, taskExecutionContext, false);
}
else if (inProgressBuildState == InProgressBuildState.BuildingDependencies)
{
ContinueBuildingDependencies(buildContext);
}
else if (inProgressBuildState == InProgressBuildState.StartingBuild)
{
initiatingBuildContext = buildContext;
inProgressBuildState = InProgressBuildState.BuildingDependencies;
currentDependentTarget = 0;
ExecuteDependentTarget(buildContext);
}
else if (inProgressBuildState == InProgressBuildState.BuildingErrorClause)
{
ContinueBuildingErrorClause(buildContext);
}
// In the single threaded mode we need to pull up the outputs of the previous
// step
if (parentEngine.Router.SingleThreadedMode &&
inProgressBuildState == InProgressBuildState.RunningTasks)
{
taskExecutionContext = parentEngine.GetTaskOutputUpdates();
}
} while (parentEngine.Router.SingleThreadedMode && inProgressBuildState == InProgressBuildState.RunningTasks);
// Indicate that we exited successfully
exitedDueToError = false;
}
finally
{
if (exitedDueToError)
{
inProgressBuildState = InProgressBuildState.NotInProgress;
NotifyBuildCompletion(Target.BuildState.CompletedUnsuccessfully, buildContext);
}
}
}
/// <summary>
/// Mark the target data structures and notify waiting targets since the target has completed
/// </summary>
internal void NotifyBuildCompletion
(
Target.BuildState stateOfBuild,
ProjectBuildState errorContext
)
{
targetClass.UpdateTargetStateOnBuildCompletion(stateOfBuild, targetOutputItems);
if (initiatingBuildContext.NameOfBlockingTarget == null)
{
initiatingBuildContext.BuildRequest.ResultByTarget[targetClass.Name] = stateOfBuild;
}
if (!parentEngine.Router.SingleThreadedMode)
{
// Notify targets that have been waiting on the execution
NotifyWaitingTargets(errorContext);
}
}
#region Methods for building dependencies ( InProgressBuildState.BuildingDependencies )
private void ContinueBuildingDependencies (ProjectBuildState buildContext)
{
// Verify that the target is in the right state
ErrorUtilities.VerifyThrow(inProgressBuildState == InProgressBuildState.BuildingDependencies, "Wrong state");
// Check if all dependent targets have been evaluated
ErrorUtilities.VerifyThrow(currentDependentTarget < dependsOnTargetNames.Count, "No dependent targets left");
// Verify that the target we were waiting on has completed building
string nameDependentTarget = dependsOnTargetNames[currentDependentTarget];
ErrorUtilities.VerifyThrow(
parentProject.Targets[nameDependentTarget].TargetBuildState != Target.BuildState.InProgress &&
parentProject.Targets[nameDependentTarget].TargetBuildState != Target.BuildState.NotStarted ||
buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.ExceptionThrown,
"This target should only be updated once the dependent target is completed");
if (buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.ExceptionThrown)
{
inProgressBuildState = InProgressBuildState.NotInProgress;
// Call the parent project to update targets waiting on us
NotifyBuildCompletion(Target.BuildState.CompletedUnsuccessfully, buildContext);
return;
}
// If the dependent target failed to build we need to execute the onerrorclause (if there is one)
// or mark this target as failed (if there is not an error clause)
else if (parentProject.Targets[nameDependentTarget].TargetBuildState == Target.BuildState.CompletedUnsuccessfully)
{
// Transition the state machine into building the error clause state
InitializeOnErrorClauseExecution();
inProgressBuildState = InProgressBuildState.BuildingErrorClause;
ExecuteErrorTarget(buildContext);
return;
}
// Now that the previous dependent target has been build we need to move to the next dependent target if
// there is one
currentDependentTarget++;
// Execute the current target or transition to a different state if necessary
ExecuteDependentTarget(buildContext);
}
private void ExecuteDependentTarget
(
ProjectBuildState buildContext
)
{
if (currentDependentTarget < dependsOnTargetNames.Count)
{
// Get the Target object for the dependent target.
string nameDependentTarget = dependsOnTargetNames[currentDependentTarget];
Target targetToBuild = parentProject.Targets[nameDependentTarget];
// If we couldn't find the dependent Target object, we have a problem.
ProjectErrorUtilities.VerifyThrowInvalidProject(targetToBuild != null, targetClass.DependsOnTargetsAttribute,
"TargetDoesNotExist", nameDependentTarget);
// Update the name of the blocking target
buildContext.AddBlockingTarget(nameDependentTarget);
}
else
{
// We completed building the dependencies so we need to start running the tasks
dependsOnTargetNames = null;
inProgressBuildState = InProgressBuildState.RunningTasks;
ContinueRunningTasks(buildContext, null, true);
}
}
#endregion
#region Methods for build error targets ( InProgressBuildState.BuildingErrorClause )
private void ContinueBuildingErrorClause (ProjectBuildState buildContext)
{
// Verify that the target is in the right state
ErrorUtilities.VerifyThrow(inProgressBuildState == InProgressBuildState.BuildingErrorClause, "Wrong state");
// Check if all dependent targets have been evaluated
ErrorUtilities.VerifyThrow(currentErrorTarget < onErrorTargets.Count, "No error targets left");
// Verify that the target we were waiting on has completed building
string nameErrorTarget = onErrorTargets[currentErrorTarget];
ErrorUtilities.VerifyThrow(
parentProject.Targets[nameErrorTarget].TargetBuildState != Target.BuildState.InProgress &&
parentProject.Targets[nameErrorTarget].TargetBuildState != Target.BuildState.NotStarted ||
buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.ExceptionThrown,
"This target should only be updated once the error target is completed");
if (buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.ExceptionThrown)
{
inProgressBuildState = InProgressBuildState.NotInProgress;
// Call the parent project to update targets waiting on us
NotifyBuildCompletion(Target.BuildState.CompletedUnsuccessfully, buildContext);
return;
}
// We don't care if the target has completed successfully, we simply move on to the next one
currentErrorTarget++;
ExecuteErrorTarget(buildContext);
}
private void ExecuteErrorTarget
(
ProjectBuildState buildContext
)
{
if (onErrorTargets != null && currentErrorTarget < onErrorTargets.Count)
{
// Get the Target object for the dependent target.
string nameErrorTarget = onErrorTargets[currentErrorTarget];
Target targetToBuild = parentProject.Targets[nameErrorTarget];
// If we couldn't find the on error Target object, we have a problem.
ProjectErrorUtilities.VerifyThrowInvalidProject(targetToBuild != null, targetElement,
"TargetDoesNotExist", nameErrorTarget);
// Update the name of the blocking target
buildContext.AddBlockingTarget(nameErrorTarget);
}
else
{
// We completed building the error targets so this target is now failed and we have no more work to do
onErrorTargets = null;
inProgressBuildState = InProgressBuildState.NotInProgress;
// Call the parent project to update targets waiting on us
NotifyBuildCompletion(Target.BuildState.CompletedUnsuccessfully, null);
}
}
/// <summary>
/// Creates a list of targets to execute for the OnErrorClause
/// </summary>
private void InitializeOnErrorClauseExecution()
{
// Give default values;
currentErrorTarget = 0;
onErrorTargets = null;
// Loop through each of the child nodes of the <target> element.
List<XmlElement> childElements = ProjectXmlUtilities.GetValidChildElements(targetElement);
foreach (XmlElement childElement in childElements)
{
switch (childElement.Name)
{
case XMakeElements.onError:
ProjectXmlUtilities.VerifyThrowProjectNoChildElements(childElement);
XmlAttribute condition = null;
XmlAttribute executeTargets = null;
foreach (XmlAttribute onErrorAttribute in childElement.Attributes)
{
switch (onErrorAttribute.Name)
{
case XMakeAttributes.condition:
condition = childElement.Attributes[XMakeAttributes.condition];
break;
case XMakeAttributes.executeTargets:
executeTargets = childElement.Attributes[XMakeAttributes.executeTargets];
break;
default:
ProjectXmlUtilities.ThrowProjectInvalidAttribute(onErrorAttribute);
break;
}
}
ProjectErrorUtilities.VerifyThrowInvalidProject(executeTargets != null, childElement, "MissingRequiredAttribute", XMakeAttributes.executeTargets, XMakeElements.onError);
Expander expander = new Expander(this.parentProject.evaluatedProperties, this.parentProject.evaluatedItemsByName);
bool runErrorTargets = true;
if (condition != null)
{
if
(
!Utilities.EvaluateCondition
(
condition.InnerText, condition, expander,
null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists,
parentEngine.LoggingServices, targetBuildEventContext
)
)
{
runErrorTargets = false;
}
}
if (runErrorTargets)
{
if (onErrorTargets == null)
{
onErrorTargets = expander.ExpandAllIntoStringList(executeTargets.InnerText, executeTargets);
}
else
{
onErrorTargets.AddRange(expander.ExpandAllIntoStringList(executeTargets.InnerText, executeTargets));
}
}
break;
default:
// Ignore
break;
}
}
}
#endregion
#region Methods for running tasks ( InProgressBuildState.RunningTasks )
private void ContinueRunningTasks
(
ProjectBuildState buildContext, TaskExecutionContext taskExecutionContext,
bool startingFirstTask
)
{
bool exitDueToError = true;
try
{
// If this is the first task - initialize for running it
if (startingFirstTask)
{
InitializeForRunningTargetBatches();
}
// If run a task then process its outputs
if (currentTask != targetElement.ChildNodes.Count && !startingFirstTask)
{
ProcessTaskOutputs(taskExecutionContext);
}
// Check if we processed the last node in a batch or terminated the batch due to error
if (currentTask == targetElement.ChildNodes.Count || exitBatchDueToError)
{
FinishRunningSingleTargetBatch();
// On failure transition into unsuccessful state
if (!targetBuildSuccessful)
{
overallSuccess = false;
FinishRunningTargetBatches(buildContext);
// Transition the state machine into building the error clause state
InitializeOnErrorClauseExecution();
inProgressBuildState = InProgressBuildState.BuildingErrorClause;
ExecuteErrorTarget(buildContext);
exitDueToError = false;
return;
}
//Check if this was the last bucket
if (currentBucket == buckets.Count)
{
FinishRunningTargetBatches(buildContext);
inProgressBuildState = InProgressBuildState.NotInProgress;
// Notify targets that are waiting for the results
NotifyBuildCompletion(Target.BuildState.CompletedSuccessfully, null);
exitDueToError = false;
return;
}
// Prepare the next bucket
InitializeForRunningSingleTargetBatch();
}
// Execute the current task
ExecuteCurrentTask(buildContext);
exitDueToError = false;
}
catch (InvalidProjectFileException e)
{
// Make sure the Invalid Project error gets logged *before* TargetFinished. Otherwise,
// the log is confusing.
this.parentEngine.LoggingServices.LogInvalidProjectFileError(targetBuildEventContext, e);
throw;
}
finally
{
if (exitDueToError && loggedTargetStart)
{
// Log that the target has failed
parentEngine.LoggingServices.LogTargetFinished(
targetBuildEventContext,
targetClass.Name,
this.parentProject.FullFileName,
targetClass.ProjectFileOfTargetElement,
false);
}
}
}
private void InitializeForRunningTargetBatches()
{
// Make sure the <target> node has been given to us.
ErrorUtilities.VerifyThrow(targetElement != null,
"Need an XML node representing the <target> element.");
// Make sure this really is the <target> node.
ProjectXmlUtilities.VerifyThrowElementName(targetElement, XMakeElements.target);
overallSuccess = true;
projectContent = new Lookup(parentProject.evaluatedItemsByName, parentProject.evaluatedItems, parentProject.evaluatedProperties, parentProject.ItemDefinitionLibrary);
// If we need to use the task thread - ie, we encounter a non-intrinsic task - we will need to make sure
// the task thread only sees clones of the project items and properties. We insert a scope to allow us to
// do that later. See comment in InitializeForRunningFirstNonIntrinsicTask()
placeholderForClonedProjectContent = projectContent.EnterScope();
buckets = BatchingEngine.PrepareBatchingBuckets(targetElement, targetParameters, projectContent);
currentBucket = 0;
// Initialize the first bucket
InitializeForRunningSingleTargetBatch();
}
private void InitializeForRunningSingleTargetBatch()
{
// Verify that the target is in the right state
ErrorUtilities.VerifyThrow(inProgressBuildState == InProgressBuildState.RunningTasks, "Wrong state");
// Check if the current task number is valid
ErrorUtilities.VerifyThrow(currentBucket < buckets.Count, "No buckets left");
Hashtable changedTargetInputs = null;
Hashtable upToDateTargetInputs = null;
howToBuild = DependencyAnalysisResult.FullBuild;
ItemBucket bucket = (ItemBucket)buckets[currentBucket];
// For the first batch of a target use the targets original targetID. for each batch after the first one use a uniqueId to identity the target in the batch
if (currentBucket != 0)
{
targetBuildEventContext = new BuildEventContext(targetBuildEventContext.NodeId, parentEngine.GetNextTargetId(), targetBuildEventContext.ProjectContextId, targetBuildEventContext.TaskId);
}
// Flag the start of the target.
parentEngine.LoggingServices.LogTargetStarted(
targetBuildEventContext,
targetClass.Name,
this.parentProject.FullFileName,
targetClass.ProjectFileOfTargetElement);
loggedTargetStart = true;
// Figure out how we should build the target
TargetDependencyAnalyzer dependencyAnalyzer = new TargetDependencyAnalyzer(parentProject.ProjectDirectory, targetClass, parentEngine.LoggingServices, targetBuildEventContext);
howToBuild = dependencyAnalyzer.PerformDependencyAnalysis(bucket, out changedTargetInputs, out upToDateTargetInputs);
targetBuildSuccessful = true;
exitBatchDueToError = false;
// If we need to build the target - initialize the data structure for
// running the tasks
if ((howToBuild != DependencyAnalysisResult.SkipNoInputs) &&
(howToBuild != DependencyAnalysisResult.SkipNoOutputs))
{
// Within each target batch items are divided into lookup and execution; they must be
// kept separate: enforce this by cloning and entering scope
lookupForInference = bucket.Lookup;
lookupForExecution = bucket.Lookup.Clone();
lookupForInference.EnterScope();
lookupForExecution.EnterScope();
// if we're doing an incremental build, we need to effectively run the task twice -- once
// to infer the outputs for up-to-date input items, and once to actually execute the task;
// as a result we need separate sets of item and property collections to track changes
if (howToBuild == DependencyAnalysisResult.IncrementalBuild)
{
// subset the relevant items to those that are up-to-date
foreach (DictionaryEntry upToDateTargetInputsEntry in upToDateTargetInputs)
{
lookupForInference.PopulateWithItems((string)upToDateTargetInputsEntry.Key, (BuildItemGroup)upToDateTargetInputsEntry.Value);
}
// subset the relevant items to those that have changed
foreach (DictionaryEntry changedTargetInputsEntry in changedTargetInputs)
{
lookupForExecution.PopulateWithItems((string)changedTargetInputsEntry.Key, (BuildItemGroup)changedTargetInputsEntry.Value);
}
}
projectFileOfTaskNode = XmlUtilities.GetXmlNodeFile(targetElement, parentProject.FullFileName);
// count the tasks in the target
currentTask = 0;
skippedNodeCount = 0;
}
else
{
currentTask = targetElement.ChildNodes.Count;
}
}
/// <summary>
/// Called before the first non-intrinsic task is run by this object.
/// </summary>
private void InitializeForRunningFirstNonIntrinsicTask()
{
// We need the task thread to see cloned project content for two reasons:
// (1) clone items because BuildItemGroups storage is a List, which
// is not safe to read from (task thread) and write to (engine thread) concurrently.
// Project properties are in a virtual property group which stores its properties in a hashtable, however
// (2) we must clone both items and properties so that project items and properties modified by a
// target called by this target are not visible to this target (Whidbey behavior)
//
// So, we populate the empty scope we inserted earlier with clones of the items and properties, and we
// mark it so that lookups truncate their walk at this scope, and don't reach the real items and properties below.
// Later, back on the engine thread, we'll leave this scope and the task changes will go into the project.
Hashtable items = new Hashtable(parentProject.evaluatedItemsByName.Count, StringComparer.OrdinalIgnoreCase);
foreach (DictionaryEntry entry in parentProject.evaluatedItemsByName)
{
BuildItemGroup group = (BuildItemGroup)entry.Value;
BuildItemGroup clonedGroup = group.ShallowClone();
items.Add(entry.Key, clonedGroup);
}
BuildPropertyGroup properties = parentProject.evaluatedProperties.ShallowClone();
placeholderForClonedProjectContent.Items = items;
placeholderForClonedProjectContent.Properties = properties;
placeholderForClonedProjectContent.TruncateLookupsAtThisScope = true;
}
/// <summary>
/// Executes all tasks in the target linearly from beginning to end, for one batch of the target.
/// </summary>
private void ExecuteCurrentTask(ProjectBuildState buildContext)
{
// Check if this is an empty target
if (currentTask == targetElement.ChildNodes.Count)
{
// This is an empty target so we should transition into completed state
ContinueRunningTasks(buildContext, null, false);
return;
}
// Get the current child nodes of the <Target> element.
XmlNode targetChildNode = targetElement.ChildNodes[currentTask];
// Handle XML comments under the <target> node (just ignore them) and
// also skip OnError tags because they are processed separately and later.
// Also evaluate any intrinsic tasks immediately and continue.
while ((targetChildNode.NodeType == XmlNodeType.Comment) ||
(targetChildNode.NodeType == XmlNodeType.Whitespace) ||
(targetChildNode.Name == XMakeElements.onError) ||
(IntrinsicTask.IsIntrinsicTaskName(targetChildNode.Name)))
{
if (IntrinsicTask.IsIntrinsicTaskName(targetChildNode.Name))
{
ExecuteIntrinsicTask((XmlElement)targetChildNode);
}
else
{
skippedNodeCount++;
}
currentTask++;
// Check if this was the last task in the target
if (currentTask == targetElement.ChildNodes.Count)
{
// Transition into appropriate state
ContinueRunningTasks(buildContext, null, false);
return;
}
targetChildNode = targetElement.ChildNodes[currentTask];
}
// Any child node other than a task element or <OnError> is not supported.
ProjectXmlUtilities.VerifyThrowProjectXmlElementChild(targetChildNode);
// Make <ItemDefinitionGroup> illegal inside targets, so we can possibly allow it in future.
ProjectErrorUtilities.VerifyThrowInvalidProject(!String.Equals(targetChildNode.Name, XMakeElements.itemDefinitionGroup, StringComparison.Ordinal),
targetElement, "ItemDefinitionGroupNotLegalInsideTarget", targetChildNode.Name, XMakeElements.target);
ErrorUtilities.VerifyThrow(taskElementList.Count > (currentTask - skippedNodeCount),
"The TaskElementCollection in this target doesn't have the same number of BuildTask objects as the number of actual task elements.");
// Send the task for execution
SubmitNonIntrinsicTask(
(XmlElement)targetChildNode,
((BuildTask)taskElementList[(currentTask - skippedNodeCount)]).HostObject,
buildContext);
return;
}
private TaskExecutionMode DetermineExecutionMode()
{
TaskExecutionMode executionMode;
if ((howToBuild == DependencyAnalysisResult.SkipUpToDate) ||
(howToBuild == DependencyAnalysisResult.IncrementalBuild))
{
executionMode = TaskExecutionMode.InferOutputsOnly;
}
else
{
executionMode = TaskExecutionMode.ExecuteTaskAndGatherOutputs;
}
// execute the task using the items that need to be (re)built
if ((howToBuild == DependencyAnalysisResult.FullBuild) ||
(howToBuild == DependencyAnalysisResult.IncrementalBuild))
{
executionMode = executionMode | TaskExecutionMode.ExecuteTaskAndGatherOutputs;
}
return executionMode;
}
/// <summary>
/// Create a new build event context for tasks
/// </summary>
private BuildEventContext PrepareBuildEventContext(bool setInvalidTaskId)
{
BuildEventContext buildEventContext = new BuildEventContext
(
targetBuildEventContext.NodeId,
targetBuildEventContext.TargetId,
targetBuildEventContext.ProjectContextId,
setInvalidTaskId ? BuildEventContext.InvalidTaskId : parentEngine.GetNextTaskId()
);
return buildEventContext;
}
private void ExecuteIntrinsicTask(XmlElement taskNode)
{
// Intrinsic tasks should have their messages logged in the context of the target as they will not have task started or finished events so use an invalid taskID
BuildEventContext buildEventContext = PrepareBuildEventContext(true);
TaskExecutionMode executionMode = DetermineExecutionMode();
IntrinsicTask task = new IntrinsicTask(taskNode,
parentEngine.LoggingServices,
buildEventContext,
parentProject.ProjectDirectory,
parentProject.ItemDefinitionLibrary);
if ((executionMode & TaskExecutionMode.InferOutputsOnly) != TaskExecutionMode.Invalid)
{
task.ExecuteTask(lookupForInference);
}
if ((executionMode & TaskExecutionMode.ExecuteTaskAndGatherOutputs) != TaskExecutionMode.Invalid)
{
task.ExecuteTask(lookupForExecution);
}
}
/// <summary>
/// Create a TaskExecutionState structure which contains all the information necessary
/// to execute the task and send this information over to the TEM for task execution
/// </summary>
internal void SubmitNonIntrinsicTask
(
XmlElement taskNode,
ITaskHost hostObject,
ProjectBuildState buildContext
)
{
if (!haveRunANonIntrinsicTask)
{
InitializeForRunningFirstNonIntrinsicTask();
haveRunANonIntrinsicTask = true;
}
TaskExecutionMode executionMode = DetermineExecutionMode();
// A TaskExecutionMode of ExecuteTaskAndGatherOutputs should have its messages logged in the context of the task and therefore should have a valid taskID
// A TaskExecutionMode of InferOutputs or Invalid should have its messages logged in the context of the target and therefore should have an invalid taskID
BuildEventContext buildEventContext = PrepareBuildEventContext(executionMode == TaskExecutionMode.ExecuteTaskAndGatherOutputs ? false: true);
// Create the task execution context
int handleId = parentEngine.EngineCallback.CreateTaskContext(parentProject, targetClass, buildContext,
taskNode, EngineCallback.inProcNode, buildEventContext);
// Create the task execution state
TaskExecutionState taskState =
new TaskExecutionState
(
executionMode,
lookupForInference,
lookupForExecution,
taskNode,
hostObject,
projectFileOfTaskNode,
parentProject.FullFileName,
parentProject.ProjectDirectory,
handleId,
buildEventContext
);
// Send the request for task execution to the node
parentEngine.NodeManager.ExecuteTask(taskState);
}
private void ProcessTaskOutputs(TaskExecutionContext executionContext)
{
// Get the success or failure
if (targetBuildSuccessful)
{
if (!executionContext.TaskExecutedSuccessfully)
{
targetBuildSuccessful = false;
// Check if the task threw an unhandled exception during its execution
if (executionContext.ThrownException != null)
{
// The stack trace for remote task InvalidProjectFileException can be ignored
// since it is not recorded and the exception will be caught inside the project
// class
if (executionContext.ThrownException is InvalidProjectFileException)
{
throw executionContext.ThrownException;
}
else
{
// The error occured outside of the user code (it may still be caused
// by bad user input), the build should be terminated. The exception
// will be logged as a fatal build error in engine. The exceptions caused
// by user code are converted into LogFatalTaskError messages by the TaskEngine
RemoteErrorException.Throw(executionContext.ThrownException,
targetBuildEventContext,
"RemoteErrorDuringTaskExecution",
parentProject.FullFileName,
targetClass.Name);
}
}
// We need to disable the execution of the task if it was previously enabled,
// and if were only doing execution we can stop processing at the point the
// error occurred. If the task fails (which implies that ContinueOnError != 'true'), then do
// not execute the remaining tasks because they may depend on the completion
// of this task.
ErrorUtilities.VerifyThrow(howToBuild == DependencyAnalysisResult.FullBuild ||
howToBuild == DependencyAnalysisResult.IncrementalBuild,
"We can only see a failure for an execution stage");
if (howToBuild != DependencyAnalysisResult.FullBuild)
howToBuild = DependencyAnalysisResult.SkipUpToDate;
else
exitBatchDueToError = true;
}
}
currentTask++;
}
private void FinishRunningSingleTargetBatch
(
)
{
if ((howToBuild != DependencyAnalysisResult.SkipNoInputs) &&
(howToBuild != DependencyAnalysisResult.SkipNoOutputs))
{
// publish all output items and properties to the target scope;
// inference and execution are now combined
// roll up the outputs in the right order -- inferred before generated
// NOTE: this order is important because when we infer outputs, we are trying
// to produce the same results as would be produced from a full build; as such
// if we're doing both the infer and execute steps, we want the outputs from
// the execute step to override the outputs of the infer step -- this models
// the full build scenario more correctly than if the steps were reversed
lookupForInference.LeaveScope();
lookupForExecution.LeaveScope();
}
// Flag the completion of the target.
parentEngine.LoggingServices.LogTargetFinished(
targetBuildEventContext,
targetClass.Name,
this.parentProject.FullFileName,
targetClass.ProjectFileOfTargetElement,
(overallSuccess && targetBuildSuccessful));
loggedTargetStart = false;
// Get the next bucket
currentBucket++;
}
private void FinishRunningTargetBatches(ProjectBuildState buildContext)
{
// first, publish all task outputs to the project level
foreach (ItemBucket bucket in buckets)
{
bucket.Lookup.LeaveScope();
}
// and also leave the extra scope we created with the cloned project items
projectContent.LeaveScope();
// if all batches of the target build successfully
if (overallSuccess)
{
// then, gather the target outputs
// NOTE: it is possible that the target outputs computed at this point will be different from the target outputs
// used for dependency analysis, but we assume that's what the user intended
GatherTargetOutputs();
// Only contexts which are generated from an MSBuild task could need
// the outputs of the target, such contexts have a non-null evaluation
// request
if (buildContext.BuildRequest.OutputsByTarget != null &&
buildContext.NameOfBlockingTarget == null)
{
ErrorUtilities.VerifyThrow(
String.Compare(EscapingUtilities.UnescapeAll(buildContext.NameOfTargetInProgress), targetClass.Name, StringComparison.OrdinalIgnoreCase) == 0,
"The name of the target in progress is inconsistent with the target being built");
ErrorUtilities.VerifyThrow(targetOutputItems != null,
"If the target built successfully, we must have its outputs.");
buildContext.BuildRequest.OutputsByTarget[targetClass.Name] = targetOutputItems.ToArray();
}
}
}
/// <summary>
/// Gathers the target's outputs, per its output specification (if any).
/// </summary>
/// <remarks>
/// This method computes the target's outputs using the items currently available in the project; depending on when this
/// method is called, it may compute a different set of outputs -- as a result, we only want to gather the target's
/// outputs once, and cache them until the target's build state is reset.
/// </remarks>
private void GatherTargetOutputs()
{
// allocate storage for target outputs -- if the target has no outputs this list will remain empty
targetOutputItems = new List<BuildItem>();
XmlAttribute targetOutputsAttribute = targetElement.Attributes[XMakeAttributes.outputs];
// Hack to help the 3.5 engine at least pretend to still be able to build on top of
// the 4.0 targets. In cases where there is no Outputs attribute, just a Returns attribute,
// we can approximate the correct behaviour by making the Returns attribute our "outputs" attribute.
if (targetOutputsAttribute == null)
{
targetOutputsAttribute = targetElement.Attributes[XMakeAttributes.returns];
}
if (targetOutputsAttribute != null)
{
// NOTE: we need to gather the outputs in batches, because the output specification may reference item metadata
foreach (ItemBucket bucket in BatchingEngine.PrepareBatchingBuckets(targetElement, targetParameters, new Lookup(parentProject.evaluatedItemsByName, parentProject.evaluatedProperties, parentProject.ItemDefinitionLibrary)))
{
targetOutputItems.AddRange(bucket.Expander.ExpandAllIntoBuildItems(targetOutputsAttribute.Value, targetOutputsAttribute));
}
}
}
#endregion
#region Methods for managing the wait states
/// <summary>
/// Add a build context that should get a result of the target once it is finished
/// </summary>
internal void AddWaitingBuildContext(ProjectBuildState buildContext)
{
if (waitingTargets == null)
{
waitingTargets = new List<ProjectBuildState>();
}
parentEngine.Scheduler.NotifyOfBlockedRequest(buildContext.BuildRequest);
waitingTargets.Add(buildContext);
}
/// <summary>
/// Get the list of build contexts currently waiting on the target
/// </summary>
internal List<ProjectBuildState> GetWaitingBuildContexts()
{
return waitingTargets;
}
/// <summary>
/// Iterate over the contexts waiting for the target - triggering updates for each of them since the target
/// is complete
/// </summary>
internal void NotifyWaitingTargets(ProjectBuildState errorContext)
{
// If there was a failure (either unhandled exception or a cycle) the stack will
// not unwind properly (i.e. via ContinueBuild call). Therefore the initiating request
// must be notified the target completed if the error occurred in another context
if (errorContext != null)
{
AddWaitingBuildContext(initiatingBuildContext);
}
// Notify the target within the same project that are waiting for current target
// These targets are in the process of either building dependencies or error targets
// or part of a sequential build context
while (waitingTargets != null && waitingTargets.Count != 0)
{
//Grab the first context
ProjectBuildState buildContext = waitingTargets[0];
waitingTargets.RemoveAt(0);
//Don't report any messages within the context in which the error occured. That context
//is addressed as the base of the stack
if (buildContext == errorContext ||
buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.RequestFilled)
{
continue;
}
parentEngine.Scheduler.NotifyOfUnblockedRequest(buildContext.BuildRequest);
ErrorUtilities.VerifyThrow(
buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.WaitingForTarget ||
buildContext == initiatingBuildContext,
"This context should be waiting for a target to be evaluated");
if (buildContext.NameOfBlockingTarget == null)
{
ErrorUtilities.VerifyThrow(
String.Compare(EscapingUtilities.UnescapeAll(buildContext.NameOfTargetInProgress), targetClass.Name, StringComparison.OrdinalIgnoreCase) == 0,
"The name of the target in progress is inconsistent with the target being built");
// This target was part of a sequential request so we need to notify the parent project
// to start building the next target in the sequence
if (Engine.debugMode)
{
Console.WriteLine("Finished " + buildContext.BuildRequest.ProjectFileName + ":" + targetClass.Name + " for node:" +
buildContext.BuildRequest.NodeIndex + " HandleId " + buildContext.BuildRequest.HandleId);
}
}
else
{
// The target on the waiting list must be waiting for this target to complete due to
// a dependent or onerror relationship between targets
ErrorUtilities.VerifyThrow(
String.Compare(buildContext.NameOfBlockingTarget, targetClass.Name, StringComparison.OrdinalIgnoreCase) == 0,
"This target should only be updated once the dependent target is completed");
if (Engine.debugMode)
{
Console.WriteLine("Finished " + targetClass.Name + " notifying " + EscapingUtilities.UnescapeAll(buildContext.NameOfTargetInProgress));
}
}
// Post a dummy context to the queue to cause the target to run in this context
TaskExecutionContext taskExecutionContext =
new TaskExecutionContext(parentProject, null, null, buildContext,
EngineCallback.invalidEngineHandle, EngineCallback.inProcNode, null);
parentEngine.PostTaskOutputUpdates(taskExecutionContext);
}
}
#endregion
#endregion
#region Enums
internal enum InProgressBuildState
{
// This target is not in the process of building
NotInProgress,
// The target is being started but no work has been done
StartingBuild,
// This target is in process of building dependencies
BuildingDependencies,
// This target is in process of building the error clause
BuildingErrorClause,
// This target is current running the tasks for each bucket
RunningTasks
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using NCsvLib;
using NUnit.Framework;
using System.IO;
namespace NCsvLibTestSuite
{
[TestFixture]
public class DataSourceRecordReaderEnumerableTest
{
[SetUp]
public void SetUp()
{
}
[TearDown]
public void TearDown()
{
}
[Test]
public void OpenCloseSingle()
{
DataSourceReaderBase rdr = new DataSourceReaderBase();
IEnumerable<Csvtest1> c = PrepareCsvtest1Collection();
DataSourceRecordReaderEnumerable<Csvtest1> rec =
new DataSourceRecordReaderEnumerable<Csvtest1>(
Helpers.R1, c);
rdr.Add(Helpers.R1, rec);
rec.Open();
Assert.That(rdr[Helpers.R1].Eof(), Is.False);
rec.Close();
}
[Test]
public void OpenCloseMulti()
{
DataSourceReaderBase rdr = new DataSourceReaderBase();
rdr.Add(Helpers.R1,
new DataSourceRecordReaderEnumerable<Csvtest1>(Helpers.R1,
PrepareCsvtest1Collection()));
rdr.Add(Helpers.R2,
new DataSourceRecordReaderEnumerable<Csvtest2>(Helpers.R2,
PrepareCsvtest2Collection()));
rdr.Add(Helpers.R3,
new DataSourceRecordReaderEnumerable<Csvtest3>(Helpers.R3,
PrepareCsvtest3Collection()));
rdr.Add(Helpers.R4,
new DataSourceRecordReaderEnumerable<Csvtest4>(Helpers.R4,
PrepareCsvtest4Collection()));
rdr.Add(Helpers.R5,
new DataSourceRecordReaderEnumerable<Csvtest5>(Helpers.R5,
PrepareCsvtest5Collection()));
rdr.Add(Helpers.R6,
new DataSourceRecordReaderEnumerable<Csvtest6>(Helpers.R6,
PrepareCsvtest6Collection()));
rdr[Helpers.R1].Open();
Assert.That(rdr[Helpers.R1].Eof(), Is.False);
rdr[Helpers.R1].Close();
rdr[Helpers.R2].Open();
Assert.That(rdr[Helpers.R2].Eof(), Is.False);
rdr[Helpers.R2].Close();
rdr[Helpers.R3].Open();
Assert.That(rdr[Helpers.R3].Eof(), Is.False);
rdr[Helpers.R3].Close();
rdr[Helpers.R4].Open();
Assert.That(rdr[Helpers.R4].Eof(), Is.False);
rdr[Helpers.R4].Close();
rdr[Helpers.R5].Open();
Assert.That(rdr[Helpers.R5].Eof(), Is.False);
rdr[Helpers.R5].Close();
rdr[Helpers.R6].Open();
Assert.That(rdr[Helpers.R6].Eof(), Is.False);
rdr[Helpers.R6].Close();
}
[Test]
public void OpenCloseAll()
{
DataSourceReaderBase rdr = new DataSourceReaderBase();
rdr.Add(Helpers.R1,
new DataSourceRecordReaderEnumerable<Csvtest1>(Helpers.R1,
PrepareCsvtest1Collection()));
rdr.Add(Helpers.R2,
new DataSourceRecordReaderEnumerable<Csvtest2>(Helpers.R2,
PrepareCsvtest2Collection()));
rdr.Add(Helpers.R3,
new DataSourceRecordReaderEnumerable<Csvtest3>(Helpers.R3,
PrepareCsvtest3Collection()));
rdr.Add(Helpers.R4,
new DataSourceRecordReaderEnumerable<Csvtest4>(Helpers.R4,
PrepareCsvtest4Collection()));
rdr.Add(Helpers.R5,
new DataSourceRecordReaderEnumerable<Csvtest5>(Helpers.R5,
PrepareCsvtest5Collection()));
rdr.Add(Helpers.R6,
new DataSourceRecordReaderEnumerable<Csvtest6>(Helpers.R6,
PrepareCsvtest6Collection()));
rdr.OpenAll();
rdr.CloseAll();
}
[Test]
public void ReadSingle()
{
DataSourceReaderBase rdr = new DataSourceReaderBase();
DataSourceRecordReaderEnumerable<Csvtest1> rec =
new DataSourceRecordReaderEnumerable<Csvtest1>(Helpers.R1,
PrepareCsvtest1Collection());
rdr.Add(Helpers.R1, rec);
rec.Open();
for (int i = 0; i < 4; i++)
Assert.That(rec.Read(), Is.True);
Assert.That(rec.Read(), Is.False);
rec.Close();
}
[Test]
public void ReadMulti()
{
DataSourceReaderBase rdr = new DataSourceReaderBase();
rdr.Add(Helpers.R1,
new DataSourceRecordReaderEnumerable<Csvtest1>(Helpers.R1,
PrepareCsvtest1Collection()));
rdr.Add(Helpers.R2,
new DataSourceRecordReaderEnumerable<Csvtest2>(Helpers.R2,
PrepareCsvtest2Collection()));
rdr.Add(Helpers.R3,
new DataSourceRecordReaderEnumerable<Csvtest3>(Helpers.R3,
PrepareCsvtest3Collection()));
rdr.Add(Helpers.R4,
new DataSourceRecordReaderEnumerable<Csvtest4>(Helpers.R4,
PrepareCsvtest4Collection()));
rdr.Add(Helpers.R5,
new DataSourceRecordReaderEnumerable<Csvtest5>(Helpers.R5,
PrepareCsvtest5Collection()));
rdr.Add(Helpers.R6,
new DataSourceRecordReaderEnumerable<Csvtest6>(Helpers.R6,
PrepareCsvtest6Collection()));
rdr[Helpers.R1].Open();
rdr[Helpers.R2].Open();
rdr[Helpers.R3].Open();
rdr[Helpers.R4].Open();
rdr[Helpers.R5].Open();
rdr[Helpers.R6].Open();
for (int i = 0; i < 4; i++)
{
Assert.That(rdr[Helpers.R1].Read(), Is.True);
Assert.That(rdr[Helpers.R2].Read(), Is.True);
Assert.That(rdr[Helpers.R3].Read(), Is.True);
Assert.That(rdr[Helpers.R4].Read(), Is.True);
Assert.That(rdr[Helpers.R5].Read(), Is.True);
Assert.That(rdr[Helpers.R6].Read(), Is.True);
}
Assert.That(rdr[Helpers.R1].Read(), Is.False);
//Records 2 and 3 have 8 records in db
Assert.That(rdr[Helpers.R2].Read(), Is.True);
Assert.That(rdr[Helpers.R3].Read(), Is.True);
//Record 4 has 9 records in db
for (int i = 0; i < 5; i++)
Assert.That(rdr[Helpers.R4].Read(), Is.True);
Assert.That(rdr[Helpers.R4].Read(), Is.False);
//Record 5 has 8 records in db
for (int i = 0; i < 4; i++)
Assert.That(rdr[Helpers.R5].Read(), Is.True);
Assert.That(rdr[Helpers.R5].Read(), Is.False);
//Record 6 has 8 records in db
for (int i = 0; i < 4; i++)
Assert.That(rdr[Helpers.R6].Read(), Is.True);
Assert.That(rdr[Helpers.R6].Read(), Is.False);
rdr[Helpers.R1].Close();
rdr[Helpers.R2].Close();
rdr[Helpers.R3].Close();
rdr[Helpers.R4].Close();
rdr[Helpers.R5].Close();
rdr[Helpers.R6].Close();
}
[Test]
public void GetFieldSingle()
{
DataSourceField fld;
DataSourceReaderBase rdr = new DataSourceReaderBase();
DataSourceRecordReaderEnumerable<Csvtest1> rec =
new DataSourceRecordReaderEnumerable<Csvtest1>(Helpers.R1,
PrepareCsvtest1Collection());
rdr.Add(Helpers.R1, rec);
rdr[Helpers.R1].Open();
rdr[Helpers.R1].Read();
fld = rdr[Helpers.R1].GetField("intfld");
Assert.That(fld.Name, Is.EqualTo("intfld"));
Assert.That((int)fld.Value, Is.EqualTo(1));
fld = rdr[Helpers.R1].GetField("strfld");
Assert.That((string)fld.Value, Is.EqualTo("aaa"));
fld = rdr[Helpers.R1].GetField("doublefld");
Assert.That((double)fld.Value, Is.EqualTo(100.1));
fld = rdr[Helpers.R1].GetField("decimalfld");
Assert.That((decimal)fld.Value, Is.EqualTo((decimal)1000.11));
fld = rdr[Helpers.R1].GetField("dtfld");
Assert.That((DateTime)fld.Value, Is.EqualTo(new DateTime(2001, 1, 11, 10, 11, 12)));
fld = rdr[Helpers.R1].GetField("strfld2");
Assert.That((string)fld.Value, Is.EqualTo("TEST1"));
fld = rdr[Helpers.R1].GetField("boolfld");
Assert.That((int)fld.Value, Is.EqualTo((int)1));
rdr[Helpers.R1].Read();
rdr[Helpers.R1].Read();
fld = rdr[Helpers.R1].GetField("intfld");
Assert.That((int)fld.Value, Is.EqualTo(3));
fld = rdr[Helpers.R1].GetField("strfld");
Assert.That((string)fld.Value, Is.EqualTo("ccc"));
fld = rdr[Helpers.R1].GetField("doublefld");
Assert.That((double)fld.Value, Is.EqualTo(300.3));
fld = rdr[Helpers.R1].GetField("decimalfld");
Assert.That((decimal)fld.Value, Is.EqualTo((decimal)3000.33));
fld = rdr[Helpers.R1].GetField("dtfld");
Assert.That((DateTime)fld.Value, Is.EqualTo(new DateTime(2003, 3, 13, 13, 14, 15)));
fld = rdr[Helpers.R1].GetField("strfld2");
Assert.That((string)fld.Value, Is.EqualTo("TEST3"));
fld = rdr[Helpers.R1].GetField("boolfld");
Assert.That((int)fld.Value, Is.EqualTo((int)1));
rdr[Helpers.R1].Close();
}
[Test]
public void GetFieldMulti()
{
DataSourceField fld;
DataSourceReaderBase rdr = new DataSourceReaderBase();
rdr.Add(Helpers.R1,
new DataSourceRecordReaderEnumerable<Csvtest1>(Helpers.R1,
PrepareCsvtest1Collection()));
rdr.Add(Helpers.R2,
new DataSourceRecordReaderEnumerable<Csvtest2>(Helpers.R2,
PrepareCsvtest2Collection()));
rdr.Add(Helpers.R3,
new DataSourceRecordReaderEnumerable<Csvtest3>(Helpers.R3,
PrepareCsvtest3Collection()));
rdr.Add(Helpers.R4,
new DataSourceRecordReaderEnumerable<Csvtest4>(Helpers.R4,
PrepareCsvtest4Collection()));
rdr.Add(Helpers.R5,
new DataSourceRecordReaderEnumerable<Csvtest5>(Helpers.R5,
PrepareCsvtest5Collection()));
rdr.Add(Helpers.R6,
new DataSourceRecordReaderEnumerable<Csvtest6>(Helpers.R6,
PrepareCsvtest6Collection()));
rdr[Helpers.R1].Open();
rdr[Helpers.R2].Open();
rdr[Helpers.R3].Open();
rdr[Helpers.R4].Open();
rdr[Helpers.R5].Open();
rdr[Helpers.R6].Open();
rdr[Helpers.R2].Read();
fld = rdr[Helpers.R2].GetField("intr2");
Assert.That(fld.Name, Is.EqualTo("intr2"));
Assert.That((int)fld.Value, Is.EqualTo(1));
fld = rdr[Helpers.R2].GetField("strr2");
Assert.That((string)fld.Value, Is.EqualTo("r2_1"));
fld = rdr[Helpers.R2].GetField("bool2");
Assert.That((string)fld.Value, Is.EqualTo("T"));
rdr[Helpers.R2].Read();
rdr[Helpers.R2].Read();
fld = rdr[Helpers.R2].GetField("intr2");
Assert.That(fld.Name, Is.EqualTo("intr2"));
Assert.That((int)fld.Value, Is.EqualTo(3));
fld = rdr[Helpers.R2].GetField("intr2left");
Assert.That(fld.Name, Is.EqualTo("intr2left"));
Assert.That((int)fld.Value, Is.EqualTo(33));
fld = rdr[Helpers.R2].GetField("strr2");
Assert.That((string)fld.Value, Is.EqualTo("r2_3"));
fld = rdr[Helpers.R2].GetField("bool2");
Assert.That((string)fld.Value, Is.EqualTo("T"));
rdr[Helpers.R3].Read();
fld = rdr[Helpers.R3].GetField("intr3");
Assert.That(fld.Name, Is.EqualTo("intr3"));
Assert.That((int)fld.Value, Is.EqualTo(1));
fld = rdr[Helpers.R3].GetField("strr3");
Assert.That((string)fld.Value, Is.EqualTo("r3_1"));
rdr[Helpers.R3].Read();
rdr[Helpers.R3].Read();
fld = rdr[Helpers.R3].GetField("intr3");
Assert.That(fld.Name, Is.EqualTo("intr3"));
Assert.That((int)fld.Value, Is.EqualTo(3));
fld = rdr[Helpers.R3].GetField("strr3");
Assert.That((string)fld.Value, Is.EqualTo("r3_3"));
rdr[Helpers.R4].Read();
fld = rdr[Helpers.R4].GetField("intr4");
Assert.That(fld.Name, Is.EqualTo("intr4"));
Assert.That((int)fld.Value, Is.EqualTo(1));
fld = rdr[Helpers.R4].GetField("doubler4");
Assert.That((double)fld.Value, Is.EqualTo(11.1));
fld = rdr[Helpers.R4].GetField("decimalr4");
Assert.That((decimal)fld.Value, Is.EqualTo((decimal)111.11));
rdr[Helpers.R4].Read();
rdr[Helpers.R4].Read();
fld = rdr[Helpers.R4].GetField("intr4");
Assert.That(fld.Name, Is.EqualTo("intr4"));
Assert.That((int)fld.Value, Is.EqualTo(3));
fld = rdr[Helpers.R4].GetField("doubler4");
Assert.That((double)fld.Value, Is.EqualTo(33.3));
fld = rdr[Helpers.R4].GetField("decimalr4");
Assert.That((decimal)fld.Value, Is.EqualTo((decimal)333.33));
rdr[Helpers.R5].Read();
fld = rdr[Helpers.R5].GetField("intr5");
Assert.That(fld.Name, Is.EqualTo("intr5"));
Assert.That((int)fld.Value, Is.EqualTo(1));
fld = rdr[Helpers.R5].GetField("strr5");
Assert.That(fld.Name, Is.EqualTo("strr5"));
Assert.That(fld.Value, Is.EqualTo("AA"));
rdr[Helpers.R5].Read();
rdr[Helpers.R5].Read();
rdr[Helpers.R5].Read();
fld = rdr[Helpers.R5].GetField("intr5");
Assert.That(fld.Name, Is.EqualTo("intr5"));
Assert.That((int)fld.Value, Is.EqualTo(4));
fld = rdr[Helpers.R5].GetField("strr5");
Assert.That(fld.Name, Is.EqualTo("strr5"));
Assert.That(fld.Value, Is.EqualTo("DD"));
rdr[Helpers.R6].Read();
fld = rdr[Helpers.R6].GetField("intr6");
Assert.That(fld.Name, Is.EqualTo("intr6"));
Assert.That((int)fld.Value, Is.EqualTo(11));
fld = rdr[Helpers.R6].GetField("strr6");
Assert.That(fld.Name, Is.EqualTo("strr6"));
Assert.That(fld.Value, Is.EqualTo("AAA"));
rdr[Helpers.R6].Read();
rdr[Helpers.R6].Read();
fld = rdr[Helpers.R6].GetField("intr6");
Assert.That(fld.Name, Is.EqualTo("intr6"));
Assert.That((int)fld.Value, Is.EqualTo(33));
fld = rdr[Helpers.R6].GetField("strr6");
Assert.That(fld.Name, Is.EqualTo("strr6"));
Assert.That(fld.Value, Is.EqualTo("CCC"));
}
private List<Csvtest1> PrepareCsvtest1Collection()
{
List<Csvtest1> c = new List<Csvtest1>();
c.Add(new Csvtest1(1, "aaa", 100.10, 1000.11M,
new DateTime(2001, 1, 11, 10, 11, 12), "TEST1", 1));
c.Add(new Csvtest1(2, "bbb", 200.20, 2000.22M,
new DateTime(2002, 2, 12, 12, 13, 14), "TEST2", 0));
c.Add(new Csvtest1(3, "ccc", 300.30, 3000.33M,
new DateTime(2003, 3, 13, 13, 14, 15), "TEST3", 1));
c.Add(new Csvtest1(4, "ddd", 400.40, 4000.44M,
new DateTime(2004, 4, 14, 14, 15, 16), "TEST4", 0));
return c;
}
private List<Csvtest2> PrepareCsvtest2Collection()
{
List<Csvtest2> c = new List<Csvtest2>();
c.Add(new Csvtest2(1, 11, "r2_1", "T"));
c.Add(new Csvtest2(2, 22, "r2_2", "F"));
c.Add(new Csvtest2(3, 33, "r2_3", "T"));
c.Add(new Csvtest2(4, 44, null, "F"));
c.Add(new Csvtest2(5, 55, "r2_5", "T"));
c.Add(new Csvtest2(6, 66, "r2_6", "F"));
c.Add(new Csvtest2(7, 77, "r2_7", "T"));
c.Add(new Csvtest2(8, 88, "r2_8", "F"));
c.Add(new Csvtest2(9, 99, "r2_9", "F"));
c.Add(new Csvtest2(10, 100, "r2_10", "F"));
c.Add(new Csvtest2(11, 110, "r2_11", "F"));
return c;
}
private List<Csvtest3> PrepareCsvtest3Collection()
{
List<Csvtest3> c = new List<Csvtest3>();
c.Add(new Csvtest3(1, "r3_1"));
c.Add(new Csvtest3(2, "r3_2"));
c.Add(new Csvtest3(3, "r3_3"));
c.Add(new Csvtest3(4, "r3_4"));
c.Add(new Csvtest3(5, "r3_5"));
c.Add(new Csvtest3(6, "r3_6"));
c.Add(new Csvtest3(7, "r3_7"));
c.Add(new Csvtest3(8, "r3_8"));
c.Add(new Csvtest3(9, "r3_9"));
c.Add(new Csvtest3(10, "r3_10"));
c.Add(new Csvtest3(11, "r3_11"));
c.Add(new Csvtest3(12, "r3_12"));
return c;
}
private List<Csvtest4> PrepareCsvtest4Collection()
{
List<Csvtest4> c = new List<Csvtest4>();
c.Add(new Csvtest4(1, 11.1, 111.11M));
c.Add(new Csvtest4(2, 22.2, 222.22M));
c.Add(new Csvtest4(3, 33.3, 333.33M));
c.Add(new Csvtest4(4, 44.4, 444.44M));
c.Add(new Csvtest4(5, 55.5, 555.55M));
c.Add(new Csvtest4(6, 66.6, 666.66M));
c.Add(new Csvtest4(7, 77.7, 777.77M));
c.Add(new Csvtest4(8, 88.8, 888.88M));
c.Add(new Csvtest4(9, 99.9, 999.99M));
return c;
}
private List<Csvtest5> PrepareCsvtest5Collection()
{
List<Csvtest5> c = new List<Csvtest5>();
c.Add(new Csvtest5(1, "AA"));
c.Add(new Csvtest5(2, "BB"));
c.Add(new Csvtest5(3, "CC"));
c.Add(new Csvtest5(4, "DD"));
c.Add(new Csvtest5(5, "EE"));
c.Add(new Csvtest5(6, "FF"));
c.Add(new Csvtest5(7, "GG"));
c.Add(new Csvtest5(8, "HH"));
return c;
}
private List<Csvtest6> PrepareCsvtest6Collection()
{
List<Csvtest6> c = new List<Csvtest6>();
c.Add(new Csvtest6(11, "AAA"));
c.Add(new Csvtest6(22, "BBB"));
c.Add(new Csvtest6(33, "CCC"));
c.Add(new Csvtest6(44, "DDD"));
c.Add(new Csvtest6(55, "EEE"));
c.Add(new Csvtest6(66, "FFF"));
c.Add(new Csvtest6(77, "GGG"));
c.Add(new Csvtest6(88, "HHH"));
return c;
}
public class Csvtest1
{
public int _intfld;
public int intfld { get { return _intfld; } set { _intfld = value; } }
public string _strfld;
public string strfld { get { return _strfld; } set { _strfld = value; } }
public double _doublefld;
public double doublefld { get { return _doublefld; } set { _doublefld = value; } }
public decimal _decimalfld;
public decimal decimalfld { get { return _decimalfld; } set { _decimalfld = value; } }
public DateTime _dtfld;
public DateTime dtfld { get { return _dtfld; } set { _dtfld = value; } }
public string _strfld2;
public string strfld2 { get { return _strfld2; } set { _strfld2 = value; } }
public int _boolfld;
public int boolfld { get { return _boolfld; } set { _boolfld = value; } }
public Csvtest1(int intfldVal, string strfldVal,
double doublefldVal, decimal decimalfldVal,
DateTime dtfldVal, string strfld2Val, int boolfldVal)
{
intfld = intfldVal;
strfld = strfldVal;
doublefld = doublefldVal;
decimalfld = decimalfldVal;
dtfld = dtfldVal;
strfld2 = strfld2Val;
boolfld = boolfldVal;
}
}
public class Csvtest2
{
public int _intr2;
public int intr2 { get { return _intr2; } set { _intr2 = value; } }
public int _intr2left;
public int intr2left { get { return _intr2left; } set { _intr2left = value; } }
public string _strr2;
public string strr2 { get { return _strr2; } set { _strr2 = value; } }
public string _bool2;
public string bool2 { get { return _bool2; } set { _bool2 = value; } }
public Csvtest2(int intr2Val, int intr2leftVal, string strr2Val,
string bool2Val)
{
intr2 = intr2Val;
intr2left = intr2leftVal;
strr2 = strr2Val;
bool2 = bool2Val;
}
}
public class Csvtest3
{
public int _intr3;
public int intr3 { get { return _intr3; } set { _intr3 = value; } }
public string _strr3;
public string strr3 { get { return _strr3; } set { _strr3 = value; } }
public Csvtest3(int intr3Val, string strr3Val)
{
intr3 = intr3Val;
strr3 = strr3Val;
}
}
public class Csvtest4
{
public int _intr4;
public int intr4 { get { return _intr4; } set { _intr4 = value; } }
public double _doubler4;
public double doubler4 { get { return _doubler4; } set { _doubler4 = value; } }
public decimal _decimalr4;
public decimal decimalr4 { get { return _decimalr4; } set { _decimalr4 = value; } }
public Csvtest4(int intr4Val, double doubler4Val,
decimal decimalr4Val)
{
intr4 = intr4Val;
doubler4 = doubler4Val;
decimalr4 = decimalr4Val;
}
}
public class Csvtest5
{
public int _intr5;
public int intr5 { get { return _intr5; } set { _intr5 = value; } }
public string _strr5;
public string strr5 { get { return _strr5; } set { _strr5 = value; } }
public Csvtest5(int intr5Val, string strr5Val)
{
intr5 = intr5Val;
strr5 = strr5Val;
}
}
public class Csvtest6
{
public int _intr6;
public int intr6 { get { return _intr6; } set { _intr6 = value; } }
public string _strr6;
public string strr6 { get { return _strr6; } set { _strr6 = value; } }
public Csvtest6(int intr6Val, string strr6Val)
{
intr6 = intr6Val;
strr6 = strr6Val;
}
}
}
}
| |
namespace System.Windows.Forms
{
using System;
using System.ComponentModel;
using System.Reactive;
using System.Reactive.Linq;
/// <summary>
/// Extension methods providing IObservable wrappers for the events on ToolStripDropDown.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ObservableToolStripDropDownEvents
{
/// <summary>
/// Returns an observable sequence wrapping the BackgroundImageChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundImageChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundImageChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundImageChanged += handler,
handler => instance.BackgroundImageChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BackgroundImageLayoutChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundImageLayoutChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundImageLayoutChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundImageLayoutChanged += handler,
handler => instance.BackgroundImageLayoutChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BindingContextChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the BindingContextChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> BindingContextChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BindingContextChanged += handler,
handler => instance.BindingContextChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ChangeUICues event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the ChangeUICues event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<UICuesEventArgs>> ChangeUICuesObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<UICuesEventHandler, UICuesEventArgs>(
handler => instance.ChangeUICues += handler,
handler => instance.ChangeUICues -= handler);
}
#if NETFRAMEWORK
/// <summary>
/// Returns an observable sequence wrapping the ContextMenuChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the ContextMenuChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> ContextMenuChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ContextMenuChanged += handler,
handler => instance.ContextMenuChanged -= handler);
}
#endif
/// <summary>
/// Returns an observable sequence wrapping the ContextMenuStripChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the ContextMenuStripChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> ContextMenuStripChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ContextMenuStripChanged += handler,
handler => instance.ContextMenuStripChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the DockChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the DockChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> DockChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.DockChanged += handler,
handler => instance.DockChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Closed event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Closed event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<ToolStripDropDownClosedEventArgs>> ClosedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<ToolStripDropDownClosedEventHandler, ToolStripDropDownClosedEventArgs>(
handler => instance.Closed += handler,
handler => instance.Closed -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Closing event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Closing event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<ToolStripDropDownClosingEventArgs>> ClosingObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<ToolStripDropDownClosingEventHandler, ToolStripDropDownClosingEventArgs>(
handler => instance.Closing += handler,
handler => instance.Closing -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Enter event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Enter event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> EnterObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Enter += handler,
handler => instance.Enter -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the FontChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the FontChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> FontChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.FontChanged += handler,
handler => instance.FontChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ForeColorChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the ForeColorChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> ForeColorChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ForeColorChanged += handler,
handler => instance.ForeColorChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the GiveFeedback event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the GiveFeedback event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<GiveFeedbackEventArgs>> GiveFeedbackObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<GiveFeedbackEventHandler, GiveFeedbackEventArgs>(
handler => instance.GiveFeedback += handler,
handler => instance.GiveFeedback -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the HelpRequested event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the HelpRequested event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<HelpEventArgs>> HelpRequestedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<HelpEventHandler, HelpEventArgs>(
handler => instance.HelpRequested += handler,
handler => instance.HelpRequested -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ImeModeChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the ImeModeChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> ImeModeChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ImeModeChanged += handler,
handler => instance.ImeModeChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the KeyDown event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the KeyDown event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<KeyEventArgs>> KeyDownObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<KeyEventHandler, KeyEventArgs>(
handler => instance.KeyDown += handler,
handler => instance.KeyDown -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the KeyPress event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the KeyPress event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<KeyPressEventArgs>> KeyPressObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<KeyPressEventHandler, KeyPressEventArgs>(
handler => instance.KeyPress += handler,
handler => instance.KeyPress -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the KeyUp event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the KeyUp event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<KeyEventArgs>> KeyUpObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<KeyEventHandler, KeyEventArgs>(
handler => instance.KeyUp += handler,
handler => instance.KeyUp -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Leave event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Leave event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> LeaveObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Leave += handler,
handler => instance.Leave -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Opening event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Opening event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<CancelEventArgs>> OpeningObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<CancelEventHandler, CancelEventArgs>(
handler => instance.Opening += handler,
handler => instance.Opening -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Opened event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Opened event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> OpenedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Opened += handler,
handler => instance.Opened -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the RegionChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the RegionChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> RegionChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.RegionChanged += handler,
handler => instance.RegionChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Scroll event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Scroll event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<ScrollEventArgs>> ScrollObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<ScrollEventHandler, ScrollEventArgs>(
handler => instance.Scroll += handler,
handler => instance.Scroll -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the StyleChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the StyleChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> StyleChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.StyleChanged += handler,
handler => instance.StyleChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TabStopChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the TabStopChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> TabStopChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TabStopChanged += handler,
handler => instance.TabStopChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TextChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the TextChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> TextChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TextChanged += handler,
handler => instance.TextChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TabIndexChanged event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the TabIndexChanged event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> TabIndexChangedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TabIndexChanged += handler,
handler => instance.TabIndexChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Validated event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Validated event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<EventArgs>> ValidatedObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Validated += handler,
handler => instance.Validated -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Validating event on the ToolStripDropDown instance.
/// </summary>
/// <param name="instance">The ToolStripDropDown instance to observe.</param>
/// <returns>An observable sequence wrapping the Validating event on the ToolStripDropDown instance.</returns>
public static IObservable<EventPattern<CancelEventArgs>> ValidatingObservable(this ToolStripDropDown instance)
{
return Observable.FromEventPattern<CancelEventHandler, CancelEventArgs>(
handler => instance.Validating += handler,
handler => instance.Validating -= handler);
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Params.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Params
{
/// <java-name>
/// org/apache/http/client/params/CookiePolicy
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/CookiePolicy", AccessFlags = 49)]
public sealed partial class CookiePolicy
/* scope: __dot42__ */
{
/// <summary>
/// <para>The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents. </para>
/// </summary>
/// <java-name>
/// BROWSER_COMPATIBILITY
/// </java-name>
[Dot42.DexImport("BROWSER_COMPATIBILITY", "Ljava/lang/String;", AccessFlags = 25)]
public const string BROWSER_COMPATIBILITY = "compatibility";
/// <summary>
/// <para>The Netscape cookie draft compliant policy. </para>
/// </summary>
/// <java-name>
/// NETSCAPE
/// </java-name>
[Dot42.DexImport("NETSCAPE", "Ljava/lang/String;", AccessFlags = 25)]
public const string NETSCAPE = "netscape";
/// <summary>
/// <para>The RFC 2109 compliant policy. </para>
/// </summary>
/// <java-name>
/// RFC_2109
/// </java-name>
[Dot42.DexImport("RFC_2109", "Ljava/lang/String;", AccessFlags = 25)]
public const string RFC_2109 = "rfc2109";
/// <summary>
/// <para>The RFC 2965 compliant policy. </para>
/// </summary>
/// <java-name>
/// RFC_2965
/// </java-name>
[Dot42.DexImport("RFC_2965", "Ljava/lang/String;", AccessFlags = 25)]
public const string RFC_2965 = "rfc2965";
/// <summary>
/// <para>The default 'best match' policy. </para>
/// </summary>
/// <java-name>
/// BEST_MATCH
/// </java-name>
[Dot42.DexImport("BEST_MATCH", "Ljava/lang/String;", AccessFlags = 25)]
public const string BEST_MATCH = "best-match";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal CookiePolicy() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/client/params/ClientParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientParamBean", AccessFlags = 33)]
public partial class ClientParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public ClientParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionManagerFactoryClassName
/// </java-name>
[Dot42.DexImport("setConnectionManagerFactoryClassName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetConnectionManagerFactoryClassName(string factory) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionManagerFactory
/// </java-name>
[Dot42.DexImport("setConnectionManagerFactory", "(Lorg/apache/http/conn/ClientConnectionManagerFactory;)V", AccessFlags = 1)]
public virtual void SetConnectionManagerFactory(global::Org.Apache.Http.Conn.IClientConnectionManagerFactory factory) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHandleRedirects
/// </java-name>
[Dot42.DexImport("setHandleRedirects", "(Z)V", AccessFlags = 1)]
public virtual void SetHandleRedirects(bool handle) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setRejectRelativeRedirect
/// </java-name>
[Dot42.DexImport("setRejectRelativeRedirect", "(Z)V", AccessFlags = 1)]
public virtual void SetRejectRelativeRedirect(bool reject) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setMaxRedirects
/// </java-name>
[Dot42.DexImport("setMaxRedirects", "(I)V", AccessFlags = 1)]
public virtual void SetMaxRedirects(int maxRedirects) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setAllowCircularRedirects
/// </java-name>
[Dot42.DexImport("setAllowCircularRedirects", "(Z)V", AccessFlags = 1)]
public virtual void SetAllowCircularRedirects(bool allow) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHandleAuthentication
/// </java-name>
[Dot42.DexImport("setHandleAuthentication", "(Z)V", AccessFlags = 1)]
public virtual void SetHandleAuthentication(bool handle) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setCookiePolicy
/// </java-name>
[Dot42.DexImport("setCookiePolicy", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetCookiePolicy(string policy) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setVirtualHost
/// </java-name>
[Dot42.DexImport("setVirtualHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetVirtualHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setDefaultHeaders
/// </java-name>
[Dot42.DexImport("setDefaultHeaders", "(Ljava/util/Collection;)V", AccessFlags = 1, Signature = "(Ljava/util/Collection<Lorg/apache/http/Header;>;)V")]
public virtual void SetDefaultHeaders(global::Java.Util.ICollection<global::Org.Apache.Http.IHeader> headers) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setDefaultHost
/// </java-name>
[Dot42.DexImport("setDefaultHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetDefaultHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ClientParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>An adaptor for accessing HTTP client parameters in HttpParams.</para><para><para></para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/HttpClientParams
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/HttpClientParams", AccessFlags = 33)]
public partial class HttpClientParams
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpClientParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// isRedirecting
/// </java-name>
[Dot42.DexImport("isRedirecting", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsRedirecting(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setRedirecting
/// </java-name>
[Dot42.DexImport("setRedirecting", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetRedirecting(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isAuthenticating
/// </java-name>
[Dot42.DexImport("isAuthenticating", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setAuthenticating
/// </java-name>
[Dot42.DexImport("setAuthenticating", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getCookiePolicy
/// </java-name>
[Dot42.DexImport("getCookiePolicy", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// setCookiePolicy
/// </java-name>
[Dot42.DexImport("setCookiePolicy", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params, string cookiePolicy) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Collected parameter names for the HttpClient module. This interface combines the parameter definitions of the HttpClient module and all dependency modules or informational units. It does not define additional parameter names, but references other interfaces defining parameter names. <br></br> This interface is meant as a navigation aid for developers. When referring to parameter names, you should use the interfaces in which the respective constants are actually defined.</para><para><para></para><title>Revision:</title><para>576078 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/AllClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/AllClientPNames", AccessFlags = 1537)]
public partial interface IAllClientPNames : global::Org.Apache.Http.Params.ICoreConnectionPNames, global::Org.Apache.Http.Params.ICoreProtocolPNames, global::Org.Apache.Http.Client.Params.IClientPNames, global::Org.Apache.Http.Auth.Params.IAuthPNames, global::Org.Apache.Http.Cookie.Params.ICookieSpecPNames, global::Org.Apache.Http.Conn.Params.IConnConnectionPNames, global::Org.Apache.Http.Conn.Params.IConnManagerPNames, global::Org.Apache.Http.Conn.Params.IConnRoutePNames
/* scope: __dot42__ */
{
}
/// <java-name>
/// org/apache/http/client/params/AuthPolicy
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/AuthPolicy", AccessFlags = 49)]
public sealed partial class AuthPolicy
/* scope: __dot42__ */
{
/// <summary>
/// <para>The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes). </para>
/// </summary>
/// <java-name>
/// NTLM
/// </java-name>
[Dot42.DexImport("NTLM", "Ljava/lang/String;", AccessFlags = 25)]
public const string NTLM = "NTLM";
/// <summary>
/// <para>Digest authentication scheme as defined in RFC2617. </para>
/// </summary>
/// <java-name>
/// DIGEST
/// </java-name>
[Dot42.DexImport("DIGEST", "Ljava/lang/String;", AccessFlags = 25)]
public const string DIGEST = "Digest";
/// <summary>
/// <para>Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported) </para>
/// </summary>
/// <java-name>
/// BASIC
/// </java-name>
[Dot42.DexImport("BASIC", "Ljava/lang/String;", AccessFlags = 25)]
public const string BASIC = "Basic";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal AuthPolicy() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/ClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the class name of the default org.apache.http.conn.ClientConnectionManager </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// CONNECTION_MANAGER_FACTORY_CLASS_NAME
/// </java-name>
[Dot42.DexImport("CONNECTION_MANAGER_FACTORY_CLASS_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name";
/// <summary>
/// <para>Defines the factory to create a default org.apache.http.conn.ClientConnectionManager. </para><para>This parameters expects a value of type org.apache.http.conn.ClientConnectionManagerFactory. </para>
/// </summary>
/// <java-name>
/// CONNECTION_MANAGER_FACTORY
/// </java-name>
[Dot42.DexImport("CONNECTION_MANAGER_FACTORY", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object";
/// <summary>
/// <para>Defines whether redirects should be handled automatically </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// HANDLE_REDIRECTS
/// </java-name>
[Dot42.DexImport("HANDLE_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string HANDLE_REDIRECTS = "http.protocol.handle-redirects";
/// <summary>
/// <para>Defines whether relative redirects should be rejected. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// REJECT_RELATIVE_REDIRECT
/// </java-name>
[Dot42.DexImport("REJECT_RELATIVE_REDIRECT", "Ljava/lang/String;", AccessFlags = 25)]
public const string REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect";
/// <summary>
/// <para>Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_REDIRECTS
/// </java-name>
[Dot42.DexImport("MAX_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_REDIRECTS = "http.protocol.max-redirects";
/// <summary>
/// <para>Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// ALLOW_CIRCULAR_REDIRECTS
/// </java-name>
[Dot42.DexImport("ALLOW_CIRCULAR_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
/// <summary>
/// <para>Defines whether authentication should be handled automatically. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// HANDLE_AUTHENTICATION
/// </java-name>
[Dot42.DexImport("HANDLE_AUTHENTICATION", "Ljava/lang/String;", AccessFlags = 25)]
public const string HANDLE_AUTHENTICATION = "http.protocol.handle-authentication";
/// <summary>
/// <para>Defines the name of the cookie specification to be used for HTTP state management. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// COOKIE_POLICY
/// </java-name>
[Dot42.DexImport("COOKIE_POLICY", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE_POLICY = "http.protocol.cookie-policy";
/// <summary>
/// <para>Defines the virtual host name. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// VIRTUAL_HOST
/// </java-name>
[Dot42.DexImport("VIRTUAL_HOST", "Ljava/lang/String;", AccessFlags = 25)]
public const string VIRTUAL_HOST = "http.virtual-host";
/// <summary>
/// <para>Defines the request headers to be sent per default with each request. </para><para>This parameter expects a value of type java.util.Collection. The collection is expected to contain org.apache.http.Headers. </para>
/// </summary>
/// <java-name>
/// DEFAULT_HEADERS
/// </java-name>
[Dot42.DexImport("DEFAULT_HEADERS", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_HEADERS = "http.default-headers";
/// <summary>
/// <para>Defines the default host. The default value will be used if the target host is not explicitly specified in the request URI. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// DEFAULT_HOST
/// </java-name>
[Dot42.DexImport("DEFAULT_HOST", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_HOST = "http.default-host";
}
/// <summary>
/// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/ClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537)]
public partial interface IClientPNames
/* scope: __dot42__ */
{
}
}
| |
// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
using MyLivingRoom.Cortana;
using MyLivingRoom.Events;
using MyLivingRoom.Extensions;
using MyLivingRoom.ViewModels;
using MyLivingRoom.Views;
using Prism.Events;
using Prism.Windows;
using Prism.Windows.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Media.SpeechRecognition;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace MyLivingRoom
{
sealed partial class App : PrismApplication
{
public App()
{
this.InitializeComponent();
}
public static new App Current
{
get { return (App)Application.Current; }
}
public EventAggregator EventAggregator { get; } = new EventAggregator();
public new INavigationService NavigationService
{
get { return base.NavigationService; }
}
public TopicGroupDefinitionCollection TopicGroupDefinitions
{
get { return (TopicGroupDefinitionCollection)((CollectionViewSource)this.Resources["TopicGroupDefinitions"]).Source; }
}
public object GetViewModelFromTopicId(string topicId)
{
return this.TopicGroupDefinitions
.SelectMany(tgd => tgd.TopicDefinitions)
.Where(tvm => tvm.Id.Equals(topicId, StringComparison.Ordinal))
.FirstOrDefault()?.TopicViewModel;
}
protected override Frame OnCreateRootFrame()
{
Frame frame = null;
if (_shell == null)
{
_shell = new ShellView(out frame);
}
return frame;
}
protected override UIElement CreateShell(Frame rootFrame)
{
_shell.DataContext = new ShellViewModel();
return _shell;
}
private ShellView _shell;
protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
var deviceDisplayNames = this.TopicGroupDefinitions
.SelectMany(g => g.TopicDefinitions)
.Where(t => t.TopicViewModel is BaseDeviceViewModel)
.Select(v => v.DisplayName);
VoiceCommandService.InstallVoiceCommandService(deviceDisplayNames);
this.NavigationService.ClearHistory();
this.NavigationService.Navigate(typeof(HomePageView), null);
return Task.CompletedTask;
}
protected override Task OnActivateApplicationAsync(IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.Protocol)
{
var protocolArgs = args as ProtocolActivatedEventArgs;
if (protocolArgs != null)
{
var unused = _shell.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() => this.OnActivateApplicationForProtocol(protocolArgs));
}
}
else if (args.Kind == ActivationKind.VoiceCommand)
{
// The arguments can represent many different activation types. Cast it so we can get the
// parameters we care about out.
var voiceArgs = args as VoiceCommandActivatedEventArgs;
if (voiceArgs != null)
{
var unused = _shell.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() => this.OnActivateApplicationForVoiceCommand(voiceArgs));
}
}
return base.OnActivateApplicationAsync(args);
}
protected override Type GetPageType(string pageToken)
{
return Type.GetType(pageToken, true);
}
private void OnActivateApplicationForProtocol(ProtocolActivatedEventArgs args)
{
try
{
var uri = args.Uri;
this.ProcessProtocolUri(args.Uri);
}
catch (UriFormatException formatException)
{
this.EventAggregator.GetEvent<InvalidProtocolEvent>().Publish(new InvalidProtocolEventArgs(formatException));
}
}
private void OnActivateApplicationForVoiceCommand(VoiceCommandActivatedEventArgs args)
{
SpeechRecognitionResult speechRecognitionResult = args.Result;
// Get the name of the voice command and the text spoken. See VoiceCommandService.xml for
// the <Command> tags this can be filled with.
string commandName = speechRecognitionResult.RulePath[0];
string textSpoken = speechRecognitionResult.Text;
// The commandMode is either "voice" or "text", and it indictes how the voice command
// was entered by the user. Apps should respect "text" mode by providing feedback in silent form.
string commandMode = VoiceCommandService.SemanticInterpretation("commandMode", speechRecognitionResult);
switch (commandName)
{
case "showDevice":
// Access the value of the {device} phrase in the voice command
var device = VoiceCommandService.SemanticInterpretation("device", speechRecognitionResult);
var deviceTopic = this.TopicGroupDefinitions
.SelectMany(g => g.TopicDefinitions)
.Where(t => t.DisplayName.Equals(device, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (deviceTopic != null)
{
deviceTopic.SelectTopic();
break;
}
App.Current.NavigationService.Navigate(typeof(HomePageView), null);
break;
case "showRoom":
default:
App.Current.NavigationService.Navigate(typeof(HomePageView), null);
break;
}
}
private void ProcessProtocolUri(Uri uri)
{
if (uri.Scheme.Equals(ProtocolParts.SchemeName, StringComparison.OrdinalIgnoreCase))
{
// The path segments drill down the object hiearchy
var remainingSegments = new List<string>(uri.Segments.Select(s => Uri.UnescapeDataString(s.Trim('/', '\\'))));
// Allow for both mylivingroom:topicGroupId and mylivingroom://topicGroupId
if (!string.IsNullOrEmpty(uri.Host))
{
if (remainingSegments.Count > 0 && string.IsNullOrEmpty(remainingSegments[0]))
{
remainingSegments[0] = uri.Host;
}
else
{
remainingSegments.Insert(0, uri.Host);
}
}
else if (remainingSegments.Count == 0)
{
// If no path segments specified, then activating the application was the successful URI resolution
return;
}
// The first segment is the topic group id
var currentSegment = remainingSegments[0];
var topicDefinitionGroup = App.Current.TopicGroupDefinitions
.FirstOrDefault(g => string.Equals(g.Id, currentSegment, StringComparison.OrdinalIgnoreCase));
if (topicDefinitionGroup == null)
{
this.EventAggregator.GetEvent<InvalidProtocolEvent>()
.Publish(new InvalidProtocolEventArgs(uri, remainingSegments));
return;
}
// The next segment is the topic id
remainingSegments.RemoveAt(0);
currentSegment = remainingSegments.Count > 0 ? remainingSegments[0] : null;
var topicDefinition = topicDefinitionGroup.TopicDefinitions
.Where(t => t is IProtocolProcessor || t.TopicViewModel is IProtocolProcessor)
.FirstOrDefault(t => string.Equals(t.Id, currentSegment, StringComparison.OrdinalIgnoreCase));
var topicViewModel = default(IProtocolProcessor);
if (topicDefinition != null)
{
if (topicDefinition is IProtocolProcessor)
{
topicViewModel = (IProtocolProcessor)topicDefinition;
}
else if (topicDefinition != null)
{
topicViewModel = (IProtocolProcessor)topicDefinition.TopicViewModel;
}
}
if (topicViewModel == null || !topicViewModel.ProcessProtocolUri(uri, remainingSegments))
{
this.EventAggregator.GetEvent<InvalidProtocolEvent>()
.Publish(new InvalidProtocolEventArgs(uri, remainingSegments));
return;
}
}
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Macro Usage
///<para>SObject Name: MacroUsage</para>
///<para>Custom Object: False</para>
///</summary>
public class SfMacroUsage : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "MacroUsage"; }
}
///<summary>
/// Macro Usage ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Owner ID
/// <para>Name: OwnerId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "ownerId")]
[Updateable(false), Createable(false)]
public string OwnerId { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Macro Usage Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
[Updateable(false), Createable(false)]
public string Name { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Macro ID
/// <para>Name: MacroId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "macroId")]
[Updateable(false), Createable(false)]
public string MacroId { get; set; }
///<summary>
/// ReferenceTo: Macro
/// <para>RelationshipName: Macro</para>
///</summary>
[JsonProperty(PropertyName = "macro")]
[Updateable(false), Createable(false)]
public SfMacro Macro { get; set; }
///<summary>
/// Context Record
/// <para>Name: ContextRecord</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contextRecord")]
[Updateable(false), Createable(false)]
public string ContextRecord { get; set; }
///<summary>
/// Executed Instruction Count
/// <para>Name: ExecutedInstructionCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "executedInstructionCount")]
[Updateable(false), Createable(false)]
public int? ExecutedInstructionCount { get; set; }
///<summary>
/// Instruction Count
/// <para>Name: InstructionCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "instructionCount")]
[Updateable(false), Createable(false)]
public int? InstructionCount { get; set; }
///<summary>
/// Execution End Time
/// <para>Name: ExecutionEndTime</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "executionEndTime")]
[Updateable(false), Createable(false)]
public DateTimeOffset? ExecutionEndTime { get; set; }
///<summary>
/// User ID
/// <para>Name: UserId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "userId")]
[Updateable(false), Createable(false)]
public string UserId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: User</para>
///</summary>
[JsonProperty(PropertyName = "user")]
[Updateable(false), Createable(false)]
public SfUser User { get; set; }
///<summary>
/// From Bulk Execution
/// <para>Name: IsFromBulk</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isFromBulk")]
[Updateable(false), Createable(false)]
public bool? IsFromBulk { get; set; }
///<summary>
/// App Context
/// <para>Name: AppContext</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "appContext")]
[Updateable(false), Createable(false)]
public string AppContext { get; set; }
///<summary>
/// Condition Count
/// <para>Name: ConditionCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "conditionCount")]
[Updateable(false), Createable(false)]
public int? ConditionCount { get; set; }
///<summary>
/// Execution State
/// <para>Name: ExecutionState</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "executionState")]
[Updateable(false), Createable(false)]
public string ExecutionState { get; set; }
///<summary>
/// Duration In Milliseconds
/// <para>Name: DurationInMs</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "durationInMs")]
[Updateable(false), Createable(false)]
public int? DurationInMs { get; set; }
///<summary>
/// Failure Reason
/// <para>Name: FailureReason</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "failureReason")]
[Updateable(false), Createable(false)]
public string FailureReason { get; set; }
}
}
| |
using System;
using ALinq;
using ALinq.Mapping;
namespace NorthwindDemo
{
[System.ComponentModel.DataAnnotations.ScaffoldTableAttribute(false)]
[Table(Name="Contacts")]
[InheritanceMapping(Code="Unknown", Type=typeof(Contact), IsDefault=true)]
[InheritanceMapping(Code="Shipper", Type=typeof(ShipperContact), IsDefault=false)]
[InheritanceMapping(Code="Full", Type=typeof(FullContact), IsDefault=false)]
[InheritanceMapping(Code="Customer", Type=typeof(CustomerContact), IsDefault=false)]
[InheritanceMapping(Code="Supplier", Type=typeof(SupplierContact), IsDefault=false)]
[InheritanceMapping(Code="EmployeeContact", Type=typeof(EmployeeContact), IsDefault=false)]
public partial class Contact
{
private System.Int32 _ContactID;
private System.String _ContactType;
private System.String _CompanyName;
private System.String _Phone;
private Nullable<System.Guid> _GUID;
public Contact()
{
}
[Column(CanBeNull=false, UpdateCheck=UpdateCheck.Never, IsPrimaryKey=true, AutoSync=AutoSync.OnInsert, IsDbGenerated=true, Name="ContactID")]
public System.Int32 ContactID
{
get
{
return _ContactID;
}
set
{
_ContactID = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="ContactType", DbType="VarChar(40)", IsDiscriminator=true)]
public System.String ContactType
{
get
{
return _ContactType;
}
set
{
_ContactType = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="CompanyName", DbType="VarChar(40)")]
public System.String CompanyName
{
get
{
return _CompanyName;
}
set
{
_CompanyName = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Phone", DbType="VarChar(40)")]
public System.String Phone
{
get
{
return _Phone;
}
set
{
_Phone = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="GUID")]
public Nullable<System.Guid> GUID
{
get
{
return _GUID;
}
set
{
_GUID = value;
}
}
}
public partial class FullContact : Contact
{
private System.String _ContactName;
private System.String _ContactTitle;
private System.String _Address;
private System.String _City;
private System.String _Region;
private System.String _PostalCode;
private System.String _Country;
private System.String _Fax;
public FullContact()
{
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="ContactName", DbType="VarChar(40)")]
public System.String ContactName
{
get
{
return _ContactName;
}
set
{
_ContactName = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="ContactTitle", DbType="VarChar(40)")]
public System.String ContactTitle
{
get
{
return _ContactTitle;
}
set
{
_ContactTitle = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Address", DbType="VarChar(40)")]
public System.String Address
{
get
{
return _Address;
}
set
{
_Address = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="City", DbType="VarChar(40)")]
public System.String City
{
get
{
return _City;
}
set
{
_City = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Region", DbType="VarChar(40)")]
public System.String Region
{
get
{
return _Region;
}
set
{
_Region = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="PostalCode", DbType="VarChar(40)")]
public System.String PostalCode
{
get
{
return _PostalCode;
}
set
{
_PostalCode = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Country", DbType="VarChar(40)")]
public System.String Country
{
get
{
return _Country;
}
set
{
_Country = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Fax", DbType="VarChar(40)")]
public System.String Fax
{
get
{
return _Fax;
}
set
{
_Fax = value;
}
}
}
public partial class EmployeeContact : FullContact
{
private System.String _PhotoPath;
private System.String _Photo;
private System.String _Extension;
public EmployeeContact()
{
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="PhotoPath", DbType="VarChar(40)")]
public System.String PhotoPath
{
get
{
return _PhotoPath;
}
set
{
_PhotoPath = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Photo", DbType="VarChar(40)")]
public System.String Photo
{
get
{
return _Photo;
}
set
{
_Photo = value;
}
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="Extension", DbType="VarChar(40)")]
public System.String Extension
{
get
{
return _Extension;
}
set
{
_Extension = value;
}
}
}
public partial class SupplierContact : FullContact
{
private System.String _HomePage;
public SupplierContact()
{
}
[Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never, AutoSync=AutoSync.Never, Name="HomePage", DbType="VarChar(40)")]
public System.String HomePage
{
get
{
return _HomePage;
}
set
{
_HomePage = value;
}
}
}
public partial class CustomerContact : FullContact
{
public CustomerContact()
{
}
}
public partial class ShipperContact : Contact
{
public ShipperContact()
{
}
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// 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 Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
namespace Rhino.Commons.Test.Components
{
public class Order
{
private readonly List<OrderItem> items = new List<OrderItem>();
private string countryCode;
public List<OrderItem> Items
{
get { return items; }
}
public string CountryCode
{
get { return countryCode; }
set { countryCode = value; }
}
}
public class OrderItem
{
private decimal costPerItem;
private bool isFragile;
private string name;
private int quantity;
public OrderItem(string name, int quantity, decimal costPerItem, bool isFragile)
{
this.name = name;
this.quantity = quantity;
this.costPerItem = costPerItem;
this.isFragile = isFragile;
}
public string Name
{
get { return name; }
set { name = value; }
}
public bool IsFragile
{
get { return isFragile; }
set { isFragile = value; }
}
public int Quantity
{
get { return quantity; }
set { quantity = value; }
}
public decimal CostPerItem
{
get { return costPerItem; }
set { costPerItem = value; }
}
}
public abstract class AbstractCalculator
{
public abstract decimal Calculate(decimal currentTotal, Order order);
}
public class TotalCalculator : AbstractCalculator
{
private static decimal CalculateTotal(Order order)
{
decimal total = 0;
foreach (OrderItem item in order.Items)
{
total += (item.Quantity * item.CostPerItem);
}
return total;
}
public override decimal Calculate(decimal currentTotal, Order order)
{
return currentTotal + CalculateTotal(order);
}
}
public class GstCalculator : AbstractCalculator
{
private decimal _gstRate = 1.125m;
public decimal GstRate
{
get { return _gstRate; }
set { _gstRate = value; }
}
private static bool IsNewZealand(Order order)
{
return (order.CountryCode == "NZ");
}
public override decimal Calculate(decimal currentTotal, Order order)
{
if (IsNewZealand(order))
{
return (currentTotal * _gstRate);
}
return currentTotal;
}
}
public class ShippingCalculator : AbstractCalculator
{
private decimal _fragileShippingPremium = 1.5m;
private decimal _shippingCost = 5.0m;
public decimal ShippingCost
{
get { return _shippingCost; }
set { _shippingCost = value; }
}
public decimal FragileShippingPremium
{
get { return _fragileShippingPremium; }
set { _fragileShippingPremium = value; }
}
private decimal GetShippingTotal(Order order)
{
decimal shippingTotal = 0;
foreach (OrderItem item in order.Items)
{
decimal itemShippingCost = ShippingCost * item.Quantity;
if (item.IsFragile)
{
itemShippingCost *= FragileShippingPremium;
}
shippingTotal += itemShippingCost;
}
return shippingTotal;
}
public override decimal Calculate(decimal currentTotal, Order order)
{
return currentTotal + GetShippingTotal(order);
}
}
public interface ICostCalculator
{
decimal CalculateTotal(Order order);
}
public class DefaultCostCalculator : ICostCalculator
{
private readonly AbstractCalculator[] _calculators;
public DefaultCostCalculator(AbstractCalculator[] calculators)
{
_calculators = calculators;
}
public decimal CalculateTotal(Order order)
{
decimal currentTotal = 0;
foreach (AbstractCalculator calculator in _calculators)
{
currentTotal = calculator.Calculate(currentTotal, order);
}
return currentTotal;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This class will encapsulate a short and provide an
** Object representation of it.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Int16 : IComparable, IFormattable, IConvertible
, IComparable<Int16>, IEquatable<Int16>
{
private short m_value; // Do not rename (binary serialization)
public const short MaxValue = (short)0x7FFF;
public const short MinValue = unchecked((short)0x8000);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int16, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int16)
{
return m_value - ((Int16)value).m_value;
}
throw new ArgumentException(SR.Arg_MustBeInt16);
}
public int CompareTo(Int16 value)
{
return m_value - value;
}
public override bool Equals(Object obj)
{
if (!(obj is Int16))
{
return false;
}
return m_value == ((Int16)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Int16 obj)
{
return m_value == obj;
}
// Returns a HashCode for the Int16
public override int GetHashCode()
{
return ((int)((ushort)m_value) | (((int)m_value) << 16));
}
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
private String ToString(String format, NumberFormatInfo info)
{
Contract.Ensures(Contract.Result<String>() != null);
if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x0000FFFF);
return Number.FormatUInt32(temp, format, info);
}
return Number.FormatInt32(m_value, format, info);
}
public static short Parse(String s)
{
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static short Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
public static short Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
public static short Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static short Parse(String s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
{
i = Number.ParseInt32(s, style, info);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Int16, e);
}
// We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result
// for negative numbers
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || (i > UInt16.MaxValue))
{
throw new OverflowException(SR.Overflow_Int16);
}
return (short)i;
}
if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)i;
}
public static bool TryParse(String s, out Int16 result)
{
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Int16 result)
{
result = 0;
int i;
if (!Number.TryParseInt32(s, style, info, out i))
{
return false;
}
// We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result
// for negative numbers
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > UInt16.MaxValue)
{
return false;
}
result = (Int16)i;
return true;
}
if (i < MinValue || i > MaxValue)
{
return false;
}
result = (Int16)i;
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Int16;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return m_value;
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Pixator.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace Microsoft.Language.Xml.Tests
{
public class TestIncremental
{
const string Xml =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<X reusedAttribute=""foobar"" reusedAttr=""foobar"">
<!-- Everything that is a Y node should be reused -->
<Y>Unrelated node</Y>
<foo attributeName=""attributeValue"">
<Y>&</Y>
</foo>
</X>";
const string Xml2 =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<X sameLengthAttributeName=""foobar"" sameLengthAttributeName=""foobar"">
<!-- Everything that is a Y node should be reused -->
<Y>Unrelated node</Y>
<foo sameLengthAttributeName=""attributeValue"">
<Y>&</Y>
</foo>
</X>";
const string Xml3 =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<X sameLengthAttributeName=""foobar"" sameLengthAttributeName=""foobar"">
<!-- Everything that is a Y node should be reused -->
<PotentiallyVeryLongNodeName>Unrelated node</PotentiallyVeryLongNodeName>
<foo sameLengthAttributeName=""attributeValue"">
<Y>&</Y>
</foo>
</X>";
[Theory]
[InlineData("attributeValue", "newAttributeValue")]
[InlineData("attributeValue", "smallVal")]
[InlineData("attributeValue", "")]
[InlineData("attributeValue", "value"other")]
public void IncrementalAttributeValueChange(string attrValue1, string attrValue2)
{
T(attrValue1, attrValue2);
}
[Theory]
[InlineData("attributeName", "newAttributeName")]
[InlineData("attributeName", "n")]
[InlineData("attributeName", "")]
[InlineData("attributeName", "name")]
public void IncrementalAttributeNameChange(string attrName1, string attrName2)
{
T(attrName1, attrName2);
}
void T(string originalText, string replacementText)
{
var offset = Xml.IndexOf(originalText);
var length = originalText.Length;
var newLength = replacementText.Length;
var newXml = Xml.Replace(originalText, replacementText);
var changes = new TextChangeRange[] { new TextChangeRange(new TextSpan(offset, length), newLength) };
var root = Parser.ParseText(Xml);
var newRoot = Parser.ParseIncremental(newXml, changes, root);
Assert.NotSame(root, newRoot);
Assert.Equal(newXml, newRoot.ToFullString());
AssertShareElementGreenNodesWithName("Y", 2, root.Body, newRoot.Body);
AssertShareAttributeGreenNodesWithPrefix("reused", 2, root.Body, newRoot.Body);
}
void AssertShareElementGreenNodesWithName(string elementName, int expectedCount, XmlNodeSyntax root1, XmlNodeSyntax root2)
{
var nodes1 = root1.DescendantsAndSelf();
var nodes2 = root2.DescendantsAndSelf();
var combined = nodes1.Zip(nodes2, (n1, n2) => (n1, n2))
.Where(t => t.Item1.NameNode.FullName == elementName)
.ToList();
Assert.Equal(expectedCount, combined.Count);
foreach (var node in combined)
AssertShareGreen((SyntaxNode)node.Item1, (SyntaxNode)node.Item2);
}
void AssertShareAttributeGreenNodesWithPrefix(string attributePrefix, int expectedCount, XmlNodeSyntax root1, XmlNodeSyntax root2)
{
var attributes1 = root1.DescendantsAndSelf().SelectMany(n => n.Attributes);
var attributes2 = root2.DescendantsAndSelf().SelectMany(n => n.Attributes);
var combined = attributes1.Zip(attributes2, (a1, a2) => (a1, a2))
.Where(t => t.Item1.Name.StartsWith(attributePrefix, StringComparison.Ordinal))
.ToList();
Assert.Equal(expectedCount, combined.Count);
foreach (var node in combined)
AssertShareGreen(node.Item1, node.Item2);
}
void AssertShareGreen(SyntaxNode node1, SyntaxNode node2)
{
var prop = typeof(SyntaxNode).GetProperty("GreenNode", BindingFlags.Instance | BindingFlags.NonPublic);
var gn1 = prop.GetValue(node1);
var gn2 = prop.GetValue(node2);
Assert.Same(gn1, gn2);
}
[Fact]
public void IncrementalParsingIsSameAsFullParsing ()
{
XmlDocumentSyntax previousDocument = null;
for (int i = 1; i <= Xml.Length; i++)
{
var currentText = Xml.Substring(0, i);
var full = Parser.ParseText(currentText);
var incremental = Parser.ParseIncremental(
currentText,
new[] { new TextChangeRange(new TextSpan(currentText.Length - 1, 0), 1) },
previousDocument
);
AssertSameNodes(full, incremental);
previousDocument = incremental;
}
}
[Fact]
public void IncrementalParsingIsSameAsFullParsing_MiddleEdits()
{
var lines = Xml.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var middle = string.Join(Environment.NewLine, lines.Skip(2).Take(lines.Length - 3));
var delta = lines[0].Length + lines[1].Length + 2 * Environment.NewLine.Length;
XmlDocumentSyntax previousDocument = null;
for (int i = 1; i <= middle.Length; i++)
{
var currentText =
lines[0] + Environment.NewLine
+ lines[1] + Environment.NewLine
+ middle.Substring(0, i) + Environment.NewLine
+ lines.Last ();
var full = Parser.ParseText(currentText);
var incremental = Parser.ParseIncremental(
currentText,
new[] { new TextChangeRange(new TextSpan(delta + i - 1, 0), 1) },
previousDocument
);
AssertSameNodes(full, incremental);
previousDocument = incremental;
}
}
[Fact]
public void IncrementalParsingIsSameAsFullParsing_MultipleConcurrentEdits()
{
int[] FindAllIndexes (string str, string needle)
{
var result = new List<int>();
var foundIndex = 0;
var startSearchAt = 0;
while ((foundIndex = str.IndexOf (needle, startSearchAt)) != -1)
{
result.Add(foundIndex);
startSearchAt = foundIndex + needle.Length;
}
return result.ToArray();
}
const string AttributeName = "sameLengthAttributeName";
var attrIndexes = FindAllIndexes(Xml2, AttributeName);
XmlDocumentSyntax previousDocument = null;
for (int i = 1; i <= AttributeName.Length; i++)
{
var currentText = Xml2;
var changes = new List<TextChangeRange>();
// Reconstruct the intermediary attributes
for (int j = attrIndexes.Length - 1; j >= 0; j--)
{
currentText = currentText.Remove(attrIndexes[j], AttributeName.Length);
currentText = currentText.Insert(attrIndexes[j], AttributeName.Substring(0, i));
changes.Add(new TextChangeRange(new TextSpan(attrIndexes[j] + i - 1 - j * (AttributeName.Length - i), 0), 1));
}
changes.Reverse();
// All changes should map to the same letter
Assert.All (changes, c => Assert.Equal (currentText[c.Span.Start], currentText[changes[0].Span.Start]));
var full = Parser.ParseText(currentText);
var incremental = Parser.ParseIncremental(
currentText,
changes.ToArray (),
previousDocument
);
AssertSameNodes(full, incremental);
previousDocument = incremental;
}
}
[Theory]
[InlineData(Xml)]
[InlineData(Xml2)]
[InlineData(Xml3)]
public void IncrementalParsingIsSameAsFullParsing_Paste(string xml)
{
var incremental = Parser.ParseText(xml);
string TextToChange = "Unrelated node";
string TextToPaste = $"Completely{Environment.NewLine}unrelated{Environment.NewLine}node";
var startIndex = xml.IndexOf(TextToChange);
var newXml = xml.Replace(TextToChange, TextToPaste);
incremental = Parser.ParseIncremental(
newXml,
new[] { new TextChangeRange(new TextSpan(startIndex, TextToChange.Length), TextToPaste.Length) },
incremental);
var full = Parser.ParseText(newXml);
AssertSameNodes(full, incremental);
}
[Fact]
public void IncrementalParsingIsSameAsFullParsing_LeadingTriviaEdgeCase ()
{
/* The formatting here is important,
* we are trying to force a situation
* where the spacing trivia for the leading
* indentation is stored on the "ios" prefix
* instead of the attribute name node we are
* incrementally parsing
*/
const string Full = @"<Node ios:otherAttr=""foobar""
android:attribute
ios:alpha=""1"" />";
const string IncrementalBase = @"<Node ios:otherAttr=""foobar""
a
ios:alpha=""1"" />";
var full = Parser.ParseText(Full);
var incremental = Parser.ParseText(IncrementalBase);
var additionalText = "ndroid:attribute";
// Complete the attribute one character at a time incrementally
for (int i = 1; i <= additionalText.Length; i++)
{
var insertionIndex = IncrementalBase.IndexOf(" a");
var newIncrementalText = IncrementalBase.Replace(" a", " a" + additionalText.Substring(0, i));
var change = new TextChangeRange(new TextSpan(insertionIndex + i + 1, 0), 1);
incremental = Parser.ParseIncremental(new StringBuffer(newIncrementalText), new[] { change }, incremental);
}
Assert.Equal(full.ToFullString(), incremental.ToFullString());
AssertSameNodes(full, incremental);
}
void AssertSameNodes (SyntaxNode root1, SyntaxNode root2)
{
var allNodes1 = root1.DescendantNodesAndSelf().GetEnumerator ();
var allNodes2 = root2.DescendantNodesAndSelf().GetEnumerator ();
while (true)
{
var mn1 = allNodes1.MoveNext();
var mn2 = allNodes2.MoveNext();
Assert.False(mn1 ^ mn2, "Different node collection length");
if (!mn1 && !mn2)
return;
var n1 = allNodes1.Current;
var n2 = allNodes2.Current;
Assert.Equal(n1.Kind, n2.Kind);
Assert.Equal(n1.FullSpan, n2.FullSpan);
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindRepository
{
/// <summary>
/// Strongly-typed collection for the Supplier class.
/// </summary>
[Serializable]
public partial class SupplierCollection : RepositoryList<Supplier, SupplierCollection>
{
public SupplierCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SupplierCollection</returns>
public SupplierCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Supplier o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Suppliers table.
/// </summary>
[Serializable]
public partial class Supplier : RepositoryRecord<Supplier>, IRecordBase
{
#region .ctors and Default Settings
public Supplier()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Supplier(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Suppliers", TableType.Table, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarSupplierID = new TableSchema.TableColumn(schema);
colvarSupplierID.ColumnName = "SupplierID";
colvarSupplierID.DataType = DbType.Int32;
colvarSupplierID.MaxLength = 0;
colvarSupplierID.AutoIncrement = true;
colvarSupplierID.IsNullable = false;
colvarSupplierID.IsPrimaryKey = true;
colvarSupplierID.IsForeignKey = false;
colvarSupplierID.IsReadOnly = false;
colvarSupplierID.DefaultSetting = @"";
colvarSupplierID.ForeignKeyTableName = "";
schema.Columns.Add(colvarSupplierID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
colvarCompanyName.DefaultSetting = @"";
colvarCompanyName.ForeignKeyTableName = "";
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema);
colvarContactName.ColumnName = "ContactName";
colvarContactName.DataType = DbType.String;
colvarContactName.MaxLength = 30;
colvarContactName.AutoIncrement = false;
colvarContactName.IsNullable = true;
colvarContactName.IsPrimaryKey = false;
colvarContactName.IsForeignKey = false;
colvarContactName.IsReadOnly = false;
colvarContactName.DefaultSetting = @"";
colvarContactName.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactName);
TableSchema.TableColumn colvarContactTitle = new TableSchema.TableColumn(schema);
colvarContactTitle.ColumnName = "ContactTitle";
colvarContactTitle.DataType = DbType.String;
colvarContactTitle.MaxLength = 30;
colvarContactTitle.AutoIncrement = false;
colvarContactTitle.IsNullable = true;
colvarContactTitle.IsPrimaryKey = false;
colvarContactTitle.IsForeignKey = false;
colvarContactTitle.IsReadOnly = false;
colvarContactTitle.DefaultSetting = @"";
colvarContactTitle.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactTitle);
TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema);
colvarAddress.ColumnName = "Address";
colvarAddress.DataType = DbType.String;
colvarAddress.MaxLength = 60;
colvarAddress.AutoIncrement = false;
colvarAddress.IsNullable = true;
colvarAddress.IsPrimaryKey = false;
colvarAddress.IsForeignKey = false;
colvarAddress.IsReadOnly = false;
colvarAddress.DefaultSetting = @"";
colvarAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddress);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
colvarCity.DefaultSetting = @"";
colvarCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema);
colvarRegion.ColumnName = "Region";
colvarRegion.DataType = DbType.String;
colvarRegion.MaxLength = 15;
colvarRegion.AutoIncrement = false;
colvarRegion.IsNullable = true;
colvarRegion.IsPrimaryKey = false;
colvarRegion.IsForeignKey = false;
colvarRegion.IsReadOnly = false;
colvarRegion.DefaultSetting = @"";
colvarRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRegion);
TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema);
colvarPostalCode.ColumnName = "PostalCode";
colvarPostalCode.DataType = DbType.String;
colvarPostalCode.MaxLength = 10;
colvarPostalCode.AutoIncrement = false;
colvarPostalCode.IsNullable = true;
colvarPostalCode.IsPrimaryKey = false;
colvarPostalCode.IsForeignKey = false;
colvarPostalCode.IsReadOnly = false;
colvarPostalCode.DefaultSetting = @"";
colvarPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarPostalCode);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
colvarCountry.DefaultSetting = @"";
colvarCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarCountry);
TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema);
colvarPhone.ColumnName = "Phone";
colvarPhone.DataType = DbType.String;
colvarPhone.MaxLength = 24;
colvarPhone.AutoIncrement = false;
colvarPhone.IsNullable = true;
colvarPhone.IsPrimaryKey = false;
colvarPhone.IsForeignKey = false;
colvarPhone.IsReadOnly = false;
colvarPhone.DefaultSetting = @"";
colvarPhone.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhone);
TableSchema.TableColumn colvarFax = new TableSchema.TableColumn(schema);
colvarFax.ColumnName = "Fax";
colvarFax.DataType = DbType.String;
colvarFax.MaxLength = 24;
colvarFax.AutoIncrement = false;
colvarFax.IsNullable = true;
colvarFax.IsPrimaryKey = false;
colvarFax.IsForeignKey = false;
colvarFax.IsReadOnly = false;
colvarFax.DefaultSetting = @"";
colvarFax.ForeignKeyTableName = "";
schema.Columns.Add(colvarFax);
TableSchema.TableColumn colvarHomePage = new TableSchema.TableColumn(schema);
colvarHomePage.ColumnName = "HomePage";
colvarHomePage.DataType = DbType.String;
colvarHomePage.MaxLength = 1073741823;
colvarHomePage.AutoIncrement = false;
colvarHomePage.IsNullable = true;
colvarHomePage.IsPrimaryKey = false;
colvarHomePage.IsForeignKey = false;
colvarHomePage.IsReadOnly = false;
colvarHomePage.DefaultSetting = @"";
colvarHomePage.ForeignKeyTableName = "";
schema.Columns.Add(colvarHomePage);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("Suppliers",schema);
}
}
#endregion
#region Props
[XmlAttribute("SupplierID")]
[Bindable(true)]
public int SupplierID
{
get { return GetColumnValue<int>(Columns.SupplierID); }
set { SetColumnValue(Columns.SupplierID, value); }
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get { return GetColumnValue<string>(Columns.CompanyName); }
set { SetColumnValue(Columns.CompanyName, value); }
}
[XmlAttribute("ContactName")]
[Bindable(true)]
public string ContactName
{
get { return GetColumnValue<string>(Columns.ContactName); }
set { SetColumnValue(Columns.ContactName, value); }
}
[XmlAttribute("ContactTitle")]
[Bindable(true)]
public string ContactTitle
{
get { return GetColumnValue<string>(Columns.ContactTitle); }
set { SetColumnValue(Columns.ContactTitle, value); }
}
[XmlAttribute("Address")]
[Bindable(true)]
public string Address
{
get { return GetColumnValue<string>(Columns.Address); }
set { SetColumnValue(Columns.Address, value); }
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get { return GetColumnValue<string>(Columns.City); }
set { SetColumnValue(Columns.City, value); }
}
[XmlAttribute("Region")]
[Bindable(true)]
public string Region
{
get { return GetColumnValue<string>(Columns.Region); }
set { SetColumnValue(Columns.Region, value); }
}
[XmlAttribute("PostalCode")]
[Bindable(true)]
public string PostalCode
{
get { return GetColumnValue<string>(Columns.PostalCode); }
set { SetColumnValue(Columns.PostalCode, value); }
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get { return GetColumnValue<string>(Columns.Country); }
set { SetColumnValue(Columns.Country, value); }
}
[XmlAttribute("Phone")]
[Bindable(true)]
public string Phone
{
get { return GetColumnValue<string>(Columns.Phone); }
set { SetColumnValue(Columns.Phone, value); }
}
[XmlAttribute("Fax")]
[Bindable(true)]
public string Fax
{
get { return GetColumnValue<string>(Columns.Fax); }
set { SetColumnValue(Columns.Fax, value); }
}
[XmlAttribute("HomePage")]
[Bindable(true)]
public string HomePage
{
get { return GetColumnValue<string>(Columns.HomePage); }
set { SetColumnValue(Columns.HomePage, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region Typed Columns
public static TableSchema.TableColumn SupplierIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CompanyNameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ContactNameColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ContactTitleColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn AddressColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn CityColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn RegionColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn PostalCodeColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CountryColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn PhoneColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn FaxColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn HomePageColumn
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string SupplierID = @"SupplierID";
public static string CompanyName = @"CompanyName";
public static string ContactName = @"ContactName";
public static string ContactTitle = @"ContactTitle";
public static string Address = @"Address";
public static string City = @"City";
public static string Region = @"Region";
public static string PostalCode = @"PostalCode";
public static string Country = @"Country";
public static string Phone = @"Phone";
public static string Fax = @"Fax";
public static string HomePage = @"HomePage";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using FluentMigrator.Expressions;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.Firebird;
using FluentMigrator.Runner.Processors.MySql;
using FluentMigrator.Runner.Processors.Postgres;
using FluentMigrator.Runner.Processors.SQLite;
using FluentMigrator.Runner.Processors.SqlServer;
using FluentMigrator.Tests.Integration.Migrations;
using FluentMigrator.Tests.Integration.Migrations.Tagged;
using FluentMigrator.Tests.Unit;
using FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass3;
using Moq;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Integration
{
[TestFixture]
[Category("Integration")]
public class MigrationRunnerTests : IntegrationTestBase
{
private IRunnerContext _runnerContext;
[SetUp]
public void SetUp()
{
_runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = "FluentMigrator.Tests.Integration.Migrations"
};
}
[Test]
public void CanRunMigration()
{
ExecuteWithSupportedProcessors(processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable").ShouldBeTrue();
// This is a hack until MigrationVersionRunner and MigrationRunner are refactored and merged together
//processor.CommitTransaction();
runner.Down(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable").ShouldBeFalse();
});
}
[Test]
public void CanSilentlyFail()
{
try
{
var processorOptions = new Mock<IMigrationProcessorOptions>();
processorOptions.SetupGet(x => x.PreviewOnly).Returns(false);
var processor = new Mock<IMigrationProcessor>();
processor.Setup(x => x.Process(It.IsAny<CreateForeignKeyExpression>())).Throws(new Exception("Error"));
processor.Setup(x => x.Process(It.IsAny<DeleteForeignKeyExpression>())).Throws(new Exception("Error"));
processor.Setup(x => x.Options).Returns(processorOptions.Object);
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor.Object) { SilentlyFail = true };
runner.Up(new TestForeignKeySilentFailure());
runner.CaughtExceptions.Count.ShouldBeGreaterThan(0);
runner.Down(new TestForeignKeySilentFailure());
runner.CaughtExceptions.Count.ShouldBeGreaterThan(0);
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.RollbackToVersion(0);
}, false);
}
}
[Test]
public void CanApplyForeignKeyConvention()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestForeignKeyNamingConvention());
processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue();
runner.Down(new TestForeignKeyNamingConvention());
processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeFalse();
}, false, typeof(SQLiteProcessor));
}
[Test]
public void CanApplyForeignKeyConventionWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestForeignKeyNamingConventionWithSchema());
processor.ConstraintExists("TestSchema", "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue();
runner.Down(new TestForeignKeyNamingConventionWithSchema());
}, false, new []{typeof(SQLiteProcessor), typeof(FirebirdProcessor)});
}
[Test]
public void CanApplyIndexConvention()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestIndexNamingConvention());
processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
runner.Down(new TestIndexNamingConvention());
processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeFalse();
processor.TableExists(null, "Users").ShouldBeFalse();
});
}
[Test]
public void CanApplyIndexConventionWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestIndexNamingConventionWithSchema());
processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeTrue();
processor.TableExists("TestSchema", "Users").ShouldBeTrue();
runner.Down(new TestIndexNamingConventionWithSchema());
processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeFalse();
processor.TableExists("TestSchema", "Users").ShouldBeFalse();
});
}
[Test]
public void CanCreateAndDropIndex()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Up(new TestCreateAndDropIndexMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropIndexMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
//processor.CommitTransaction();
});
}
[Test]
public void CanCreateAndDropIndexWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Up(new TestCreateAndDropIndexMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropIndexMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateSchema());
//processor.CommitTransaction();
}, false, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanRenameTable()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeTrue();
runner.Up(new TestRenameTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeFalse();
processor.TableExists(null, "TestTable'3").ShouldBeTrue();
runner.Down(new TestRenameTableMigration());
processor.TableExists(null, "TestTable'3").ShouldBeFalse();
processor.TableExists(null, "TestTable2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeFalse();
//processor.CommitTransaction();
});
}
[Test]
public void CanRenameTableWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue();
runner.Up(new TestRenameTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse();
processor.TableExists("TestSchema", "TestTable'3").ShouldBeTrue();
runner.Down(new TestRenameTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable'3").ShouldBeFalse();
processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse();
runner.Down(new TestCreateSchema());
//processor.CommitTransaction();
});
}
[Test]
public void CanRenameColumn()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue();
runner.Up(new TestRenameColumnMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse();
processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeTrue();
runner.Down(new TestRenameColumnMigration());
processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeFalse();
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse();
}, true, typeof(SQLiteProcessor));
}
[Test]
public void CanRenameColumnWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue();
runner.Up(new TestRenameColumnMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse();
processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeTrue();
runner.Down(new TestRenameColumnMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeFalse();
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse();
runner.Down(new TestCreateSchema());
}, true, typeof(SQLiteProcessor), typeof(FirebirdProcessor));
}
[Test]
public void CanLoadMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TestMigration).Namespace,
};
var runner = new MigrationRunner(typeof(MigrationRunnerTests).Assembly, runnerContext, processor);
//runner.Processor.CommitTransaction();
runner.MigrationLoader.LoadMigrations().ShouldNotBeNull();
});
}
[Test]
public void CanLoadVersion()
{
ExecuteWithSupportedProcessors(processor =>
{
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TestMigration).Namespace,
};
var runner = new MigrationRunner(typeof(TestMigration).Assembly, runnerContext, processor);
//runner.Processor.CommitTransaction();
runner.VersionLoader.VersionInfo.ShouldNotBeNull();
});
}
[Test]
public void CanRunMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(2).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(3).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(4).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(5).ShouldBeTrue();
runner.VersionLoader.VersionInfo.Latest().ShouldBe(5);
runner.RollbackToVersion(0, false);
});
}
[Test]
public void CanMigrateASpecificVersion()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
try
{
runner.MigrateUp(1, false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
}
finally
{
runner.RollbackToVersion(0, false);
}
});
}
[Test]
public void CanMigrateASpecificVersionDown()
{
try
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(1, false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.MigrateDown(0, false);
testRunner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeFalse();
processor.TableExists(null, "Users").ShouldBeFalse();
}, false, typeof(SQLiteProcessor));
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.RollbackToVersion(0, false);
}, false);
}
}
[Test]
public void RollbackAllShouldRemoveVersionInfoTable()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(2);
processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeTrue();
});
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.RollbackToVersion(0);
processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeFalse();
});
}
[Test]
public void MigrateUpWithSqlServerProcessorShouldCommitItsTransaction()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp();
try
{
processor.WasCommitted.ShouldBeTrue();
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpSpecificVersionWithSqlServerProcessorShouldCommitItsTransaction()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(1);
try
{
processor.WasCommitted.ShouldBeTrue();
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpWithTaggedMigrationsShouldOnlyApplyMatchedMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantA" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
}
finally
{
runner.RollbackToVersion(0);
}
});
}
[Test]
public void MigrateUpWithTaggedMigrationsAndUsingMultipleTagsShouldOnlyApplyMatchedMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantA", "TenantB" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
}
finally
{
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0);
}
});
}
[Test]
public void MigrateUpWithDifferentTaggedShouldIgnoreConcreteOfTagged()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantB" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeTrue();
}
finally
{
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0);
}
});
}
[Test]
public void MigrateDownWithDifferentTagsToMigrateUpShouldApplyMatchedMigrations()
{
var assembly = typeof(TenantATable).Assembly;
var migrationsNamespace = typeof(TenantATable).Namespace;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = migrationsNamespace,
};
// Excluded SqliteProcessor as it errors on DB cleanup (RollbackToVersion).
ExecuteWithSupportedProcessors(processor =>
{
try
{
runnerContext.Tags = new[] { "TenantA" };
new MigrationRunner(assembly, runnerContext, processor).MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
runnerContext.Tags = new[] { "TenantB" };
new MigrationRunner(assembly, runnerContext, processor).MigrateDown(0, false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeFalse();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeFalse();
}
finally
{
runnerContext.Tags = new[] { "TenantA" };
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0, false);
}
}, true, typeof(SQLiteProcessor));
}
[Test]
public void VersionInfoCreationScriptsOnlyGeneratedOnceInPreviewMode()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processorOptions = new ProcessorOptions { PreviewOnly = true };
var outputSql = new StringWriter();
var announcer = new TextWriterAnnouncer(outputSql){ ShowSql = true };
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), announcer, processorOptions, new SqlServerDbFactory());
try
{
var asm = typeof(MigrationRunnerTests).Assembly;
var runnerContext = new RunnerContext(announcer)
{
Namespace = "FluentMigrator.Tests.Integration.Migrations",
PreviewOnly = true
};
var runner = new MigrationRunner(asm, runnerContext, processor);
runner.MigrateUp(1, false);
processor.CommitTransaction();
string schemaName = new TestVersionTableMetaData().SchemaName;
var schemaAndTableName = string.Format("\\[{0}\\]\\.\\[{1}\\]", schemaName, TestVersionTableMetaData.TABLENAME);
var outputSqlString = outputSql.ToString();
var createSchemaMatches = new Regex(string.Format("CREATE SCHEMA \\[{0}\\]", schemaName)).Matches(outputSqlString).Count;
var createTableMatches = new Regex("CREATE TABLE " + schemaAndTableName).Matches(outputSqlString).Count;
var createIndexMatches = new Regex("CREATE UNIQUE CLUSTERED INDEX \\[" + TestVersionTableMetaData.UNIQUEINDEXNAME + "\\] ON " + schemaAndTableName).Matches(outputSqlString).Count;
var alterTableMatches = new Regex("ALTER TABLE " + schemaAndTableName).Matches(outputSqlString).Count;
System.Console.WriteLine(outputSqlString);
createSchemaMatches.ShouldBe(1);
createTableMatches.ShouldBe(1);
alterTableMatches.ShouldBe(1);
createIndexMatches.ShouldBe(1);
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpWithTaggedMigrationsShouldNotApplyAnyMigrationsIfNoTagsParameterIsPassedIntoTheRunner()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeFalse();
}
finally
{
runner.RollbackToVersion(0);
}
});
}
[Test]
public void ValidateVersionOrderShouldDoNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
// Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite.
var excludedProcessors = new[] { typeof(SQLiteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) };
var assembly = typeof(User).Assembly;
var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace };
var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace };
try
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor);
migrationRunner.MigrateUp(3);
}, false, excludedProcessors);
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
Assert.DoesNotThrow(migrationRunner.ValidateVersionOrder);
}, false, excludedProcessors);
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.RollbackToVersion(0);
}, true, excludedProcessors);
}
}
[Test]
public void ValidateVersionOrderShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanLatestAppliedMigration()
{
// Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite.
var excludedProcessors = new[] { typeof(SQLiteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) };
var assembly = typeof(User).Assembly;
var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace };
var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace };
VersionOrderInvalidException caughtException = null;
try
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor);
migrationRunner.MigrateUp();
}, false, excludedProcessors);
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.ValidateVersionOrder();
}, false, excludedProcessors);
}
catch (VersionOrderInvalidException ex)
{
caughtException = ex;
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.RollbackToVersion(0);
}, true, excludedProcessors);
}
caughtException.ShouldNotBeNull();
caughtException.InvalidMigrations.Count().ShouldBe(1);
var keyValuePair = caughtException.InvalidMigrations.First();
keyValuePair.Key.ShouldBe(200909060935);
keyValuePair.Value.Migration.ShouldBeOfType<UserEmail>();
}
[Test]
public void CanCreateSequence()
{
ExecuteWithSqlServer2012(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSequence());
processor.SequenceExists(null, "TestSequence");
runner.Down(new TestCreateSequence());
processor.SequenceExists(null, "TestSequence").ShouldBeFalse();
}, true);
}
[Test]
public void CanCreateSequenceWithSchema()
{
Action<IMigrationProcessor> action = processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateSequenceWithSchema());
processor.SequenceExists("TestSchema", "TestSequence");
runner.Down(new TestCreateSequenceWithSchema());
processor.SequenceExists("TestSchema", "TestSequence").ShouldBeFalse();
runner.Down(new TestCreateSchema());
};
ExecuteWithSqlServer2012(
action,true);
ExecuteWithPostgres(action, IntegrationTestOptions.Postgres, true);
}
[Test]
public void CanAlterColumnWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
processor.DefaultValueExists("TestSchema", "TestTable", "Name", "Anonymous").ShouldBeTrue();
runner.Up(new TestAlterColumnWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Down(new TestAlterColumnWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanAlterTableWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse();
runner.Up(new TestAlterTableWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeTrue();
runner.Down(new TestAlterTableWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanAlterTablesSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable").ShouldBeTrue();
runner.Up(new TestAlterSchema());
processor.TableExists("NewSchema", "TestTable").ShouldBeTrue();
runner.Down(new TestAlterSchema());
processor.TableExists("TestSchema", "TestTable").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanCreateUniqueConstraint()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Up(new TestCreateUniqueConstraint());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraint());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
}, true, typeof(SQLiteProcessor));
}
[Test]
public void CanCreateUniqueConstraintWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Up(new TestCreateUniqueConstraintWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanInsertData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
DataSet ds = processor.ReadTableData(null, "TestTable");
ds.Tables[0].Rows.Count.ShouldBe(1);
ds.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SQLiteProcessor) });
}
[Test]
public void CanInsertDataWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
DataSet ds = processor.ReadTableData("TestSchema", "TestTable");
ds.Tables[0].Rows.Count.ShouldBe(1);
ds.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanUpdateData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestUpdateData());
DataSet upDs = processor.ReadTableData("TestSchema", "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(1);
upDs.Tables[0].Rows[0][1].ShouldBe("Updated");
runner.Down(new TestUpdateData());
DataSet downDs = processor.ReadTableData("TestSchema", "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanDeleteData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
runner.Up(new TestDeleteData());
DataSet upDs = processor.ReadTableData(null, "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(0);
runner.Down(new TestDeleteData());
DataSet downDs = processor.ReadTableData(null, "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SQLiteProcessor) });
}
[Test]
public void CanDeleteDataWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestDeleteDataWithSchema());
DataSet upDs = processor.ReadTableData("TestSchema", "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(0);
runner.Down(new TestDeleteDataWithSchema());
DataSet downDs = processor.ReadTableData("TestSchema", "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanReverseCreateIndex()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestCreateIndexWithReversing());
processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeTrue();
runner.Down(new TestCreateIndexWithReversing());
processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor) });
}
[Test]
public void CanReverseCreateUniqueConstraint()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
runner.Up(new TestCreateUniqueConstraintWithReversing());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithReversing());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SQLiteProcessor) });
}
[Test]
public void CanReverseCreateUniqueConstraintWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestCreateUniqueConstraintWithSchemaWithReversing());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithSchemaWithReversing());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SQLiteProcessor) });
}
[Test]
public void CanExecuteSql()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestExecuteSql());
runner.Down(new TestExecuteSql());
}, true, new[] { typeof(FirebirdProcessor) });
}
private static MigrationRunner SetupMigrationRunner(IMigrationProcessor processor)
{
Assembly asm = typeof(MigrationRunnerTests).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = "FluentMigrator.Tests.Integration.Migrations"
};
return new MigrationRunner(asm, runnerContext, processor);
}
private static void CleanupTestSqlServerDatabase(SqlConnection connection, SqlServerProcessor origProcessor)
{
if (origProcessor.WasCommitted)
{
connection.Close();
var cleanupProcessor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner cleanupRunner = SetupMigrationRunner(cleanupProcessor);
cleanupRunner.RollbackToVersion(0);
}
else
{
origProcessor.RollbackTransaction();
}
}
}
internal class TestForeignKeyNamingConvention : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey().FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.Table("Users");
Delete.Table("Groups");
}
}
internal class TestIndexNamingConvention : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Index().OnTable("Users").OnColumn("GroupId").Ascending();
}
public override void Down()
{
Delete.Index("IX_Users_GroupId").OnTable("Users").OnColumn("GroupId");
Delete.Table("Users");
}
}
internal class TestForeignKeySilentFailure : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey("FK_Foo").FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.ForeignKey("FK_Foo").OnTable("Users");
Delete.Table("Users");
Delete.Table("Groups");
}
}
internal class TestCreateAndDropTableMigration : Migration
{
public override void Up()
{
Create.Table("TestTable")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
Create.Table("TestTable2")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).Nullable()
.WithColumn("TestTableId").AsInt32().NotNullable();
Create.Index("ix_Name").OnTable("TestTable2").OnColumn("Name").Ascending()
.WithOptions().NonClustered();
Create.Column("Name2").OnTable("TestTable2").AsBoolean().Nullable();
Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id")
.FromTable("TestTable2").ForeignColumn("TestTableId")
.ToTable("TestTable").PrimaryColumn("Id");
Insert.IntoTable("TestTable").Row(new { Name = "Test" });
}
public override void Down()
{
Delete.Table("TestTable2");
Delete.Table("TestTable");
}
}
internal class TestRenameTableMigration : AutoReversingMigration
{
public override void Up()
{
Rename.Table("TestTable2").To("TestTable'3");
}
}
internal class TestRenameColumnMigration : AutoReversingMigration
{
public override void Up()
{
Rename.Column("Name").OnTable("TestTable2").To("Name'3");
}
}
internal class TestCreateAndDropIndexMigration : Migration
{
public override void Up()
{
Create.Index("IX_TestTable_Name").OnTable("TestTable").OnColumn("Name");
}
public override void Down()
{
Delete.Index("IX_TestTable_Name").OnTable("TestTable");
}
}
internal class TestForeignKeyNamingConventionWithSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
Create.Table("Users")
.InSchema("TestSchema")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.InSchema("TestSchema")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey().FromTable("Users").InSchema("TestSchema").ForeignColumn("GroupId").ToTable("Groups").InSchema("TestSchema").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.Table("Users").InSchema("TestSchema");
Delete.Table("Groups").InSchema("TestSchema");
Delete.Schema("TestSchema");
}
}
internal class TestIndexNamingConventionWithSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
Create.Table("Users")
.InSchema("TestSchema")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Index().OnTable("Users").InSchema("TestSchema").OnColumn("GroupId").Ascending();
}
public override void Down()
{
Delete.Index("IX_Users_GroupId").OnTable("Users").InSchema("TestSchema").OnColumn("GroupId");
Delete.Table("Users").InSchema("TestSchema");
Delete.Schema("TestSchema");
}
}
internal class TestCreateAndDropTableMigrationWithSchema : Migration
{
public override void Up()
{
Create.Table("TestTable")
.InSchema("TestSchema")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
Create.Table("TestTable2")
.InSchema("TestSchema")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).Nullable()
.WithColumn("TestTableId").AsInt32().NotNullable();
Create.Index("ix_Name").OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name").Ascending()
.WithOptions().NonClustered();
Create.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable();
Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id")
.FromTable("TestTable2").InSchema("TestSchema").ForeignColumn("TestTableId")
.ToTable("TestTable").InSchema("TestSchema").PrimaryColumn("Id");
Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" });
}
public override void Down()
{
Delete.Table("TestTable2").InSchema("TestSchema");
Delete.Table("TestTable").InSchema("TestSchema");
}
}
internal class TestRenameTableMigrationWithSchema : AutoReversingMigration
{
public override void Up()
{
Rename.Table("TestTable2").InSchema("TestSchema").To("TestTable'3");
}
}
internal class TestRenameColumnMigrationWithSchema : AutoReversingMigration
{
public override void Up()
{
Rename.Column("Name").OnTable("TestTable2").InSchema("TestSchema").To("Name'3");
}
}
internal class TestCreateAndDropIndexMigrationWithSchema : Migration
{
public override void Up()
{
Create.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema").OnColumn("Name");
}
public override void Down()
{
Delete.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema");
}
}
internal class TestCreateSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
}
public override void Down()
{
Delete.Schema("TestSchema");
}
}
internal class TestCreateSequence : Migration
{
public override void Up()
{
Create.Sequence("TestSequence").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10);
}
public override void Down()
{
Delete.Sequence("TestSequence");
}
}
internal class TestCreateSequenceWithSchema : Migration
{
public override void Up()
{
Create.Sequence("TestSequence").InSchema("TestSchema").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10);
}
public override void Down()
{
Delete.Sequence("TestSequence").InSchema("TestSchema");
}
}
internal class TestAlterColumnWithSchema: Migration
{
public override void Up()
{
Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsAnsiString(100).Nullable();
}
public override void Down()
{
Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable();
}
}
internal class TestAlterTableWithSchema : Migration
{
public override void Up()
{
Alter.Table("TestTable2").InSchema("TestSchema").AddColumn("NewColumn").AsInt32().WithDefaultValue(1);
}
public override void Down()
{
Delete.Column("NewColumn").FromTable("TestTable2").InSchema("TestSchema");
}
}
internal class TestAlterSchema : Migration
{
public override void Up()
{
Create.Schema("NewSchema");
Alter.Table("TestTable").InSchema("TestSchema").ToSchema("NewSchema");
}
public override void Down()
{
Alter.Table("TestTable").InSchema("NewSchema").ToSchema("TestSchema");
Delete.Schema("NewSchema");
}
}
internal class TestCreateUniqueConstraint : Migration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name");
}
public override void Down()
{
Delete.UniqueConstraint("TestUnique").FromTable("TestTable2");
}
}
internal class TestCreateUniqueConstraintWithSchema : Migration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name");
}
public override void Down()
{
Delete.UniqueConstraint("TestUnique").FromTable("TestTable2").InSchema("TestSchema");
}
}
internal class TestUpdateData : Migration
{
public override void Up()
{
Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Updated" }).AllRows();
}
public override void Down()
{
Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Test" }).AllRows();
}
}
internal class TestDeleteData : Migration
{
public override void Up()
{
Delete.FromTable("TestTable").Row(new { Name = "Test" });
}
public override void Down()
{
Insert.IntoTable("TestTable").Row(new { Name = "Test" });
}
}
internal class TestDeleteDataWithSchema :Migration
{
public override void Up()
{
Delete.FromTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test"});
}
public override void Down()
{
Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" });
}
}
internal class TestCreateIndexWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.Index().OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name2").Ascending();
}
}
internal class TestCreateUniqueConstraintWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name");
}
}
internal class TestCreateUniqueConstraintWithSchemaWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name");
}
}
internal class TestExecuteSql : Migration
{
public override void Up()
{
Execute.Sql("select 1");
}
public override void Down()
{
Execute.Sql("select 2");
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using QuantConnect.Util;
namespace QuantConnect.Data.Market
{
/// <summary>
/// QuoteBar class for second and minute resolution data:
/// An OHLC implementation of the QuantConnect BaseData class with parameters for candles.
/// </summary>
public class QuoteBar : BaseData, IBar
{
// scale factor used in QC equity/forex data files
private const decimal _scaleFactor = 1 / 10000m;
/// <summary>
/// Average bid size
/// </summary>
public long LastBidSize { get; set; }
/// <summary>
/// Average ask size
/// </summary>
public long LastAskSize { get; set; }
/// <summary>
/// Bid OHLC
/// </summary>
public Bar Bid { get; set; }
/// <summary>
/// Ask OHLC
/// </summary>
public Bar Ask { get; set; }
/// <summary>
/// Opening price of the bar: Defined as the price at the start of the time period.
/// </summary>
public decimal Open
{
get
{
if (Bid != null && Ask != null)
{
return (Bid.Open + Ask.Open) / 2m;
}
if (Bid != null)
{
return Bid.Open;
}
if (Ask != null)
{
return Ask.Open;
}
return 0m;
}
}
/// <summary>
/// High price of the QuoteBar during the time period.
/// </summary>
public decimal High
{
get
{
if (Bid != null && Ask != null)
{
return (Bid.High + Ask.High) / 2m;
}
if (Bid != null)
{
return Bid.High;
}
if (Ask != null)
{
return Ask.High;
}
return 0m;
}
}
/// <summary>
/// Low price of the QuoteBar during the time period.
/// </summary>
public decimal Low
{
get
{
if (Bid != null && Ask != null)
{
return (Bid.Low + Ask.Low) / 2m;
}
if (Bid != null)
{
return Bid.Low;
}
if (Ask != null)
{
return Ask.Low;
}
return 0m;
}
}
/// <summary>
/// Closing price of the QuoteBar. Defined as the price at Start Time + TimeSpan.
/// </summary>
public decimal Close
{
get
{
if (Bid != null && Ask != null)
{
return (Bid.Close + Ask.Close) / 2m;
}
if (Bid != null)
{
return Bid.Close;
}
if (Ask != null)
{
return Ask.Close;
}
return Value;
}
}
/// <summary>
/// The closing time of this bar, computed via the Time and Period
/// </summary>
public override DateTime EndTime
{
get { return Time + Period; }
set { Period = value - Time; }
}
/// <summary>
/// The period of this quote bar, (second, minute, daily, ect...)
/// </summary>
public TimeSpan Period { get; set; }
/// <summary>
/// Default initializer to setup an empty quotebar.
/// </summary>
public QuoteBar()
{
Symbol = Symbol.Empty;
Time = new DateTime();
Bid = new Bar();
Ask = new Bar();
Value = 0;
Period = TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Initialize Quote Bar with Bid(OHLC) and Ask(OHLC) Values:
/// </summary>
/// <param name="time">DateTime Timestamp of the bar</param>
/// <param name="symbol">Market MarketType Symbol</param>
/// <param name="bid">Bid OLHC bar</param>
/// <param name="lastBidSize">Average bid size over period</param>
/// <param name="ask">Ask OLHC bar</param>
/// <param name="lastAskSize">Average ask size over period</param>
/// <param name="period">The period of this bar, specify null for default of 1 minute</param>
public QuoteBar(DateTime time, Symbol symbol, IBar bid, long lastBidSize, IBar ask, long lastAskSize, TimeSpan? period = null)
{
Symbol = symbol;
Time = time;
Bid = bid == null ? null : new Bar(bid.Open, bid.High, bid.Low, bid.Close);
Ask = ask == null ? null : new Bar(ask.Open, ask.High, ask.Low, ask.Close);
if (Bid != null) LastBidSize = lastBidSize;
if (Ask != null) LastAskSize = lastAskSize;
Value = Close;
Period = period ?? TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Update the quotebar - build the bar from this pricing information:
/// </summary>
/// <param name="lastTrade">The last trade price</param>
/// <param name="bidPrice">Current bid price</param>
/// <param name="askPrice">Current asking price</param>
/// <param name="volume">Volume of this trade</param>
/// <param name="bidSize">The size of the current bid, if available, if not, pass 0</param>
/// <param name="askSize">The size of the current ask, if available, if not, pass 0</param>
public override void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize)
{
// update our bid and ask bars - handle null values, this is to give good values for midpoint OHLC
if (Bid == null && bidPrice != 0) Bid = new Bar();
if (Bid != null) Bid.Update(bidPrice);
if (Ask == null && askPrice != 0) Ask = new Bar();
if (Ask != null) Ask.Update(askPrice);
if (bidSize > 0)
{
LastBidSize = (long) bidSize;
}
if (askSize > 0)
{
LastAskSize = (long) askSize;
}
// be prepared for updates without trades
if (lastTrade != 0) Value = lastTrade;
else if (askPrice != 0) Value = askPrice;
else if (bidPrice != 0) Value = bidPrice;
}
/// <summary>
/// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine.
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Enumerable iterator for returning each line of the required data.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(10);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
// Using custom "ToDecimal" conversion for speed on high resolution data.
quoteBar.Time = date.Date.AddMilliseconds(csv[0].ToInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
// only create the bid if it exists in the file
if (csv[1].Length != 0 || csv[2].Length != 0 || csv[3].Length != 0 || csv[4].Length != 0)
{
quoteBar.Bid = new Bar
{
Open = config.GetNormalizedPrice(csv[1].ToDecimal()*_scaleFactor),
High = config.GetNormalizedPrice(csv[2].ToDecimal()*_scaleFactor),
Low = config.GetNormalizedPrice(csv[3].ToDecimal()*_scaleFactor),
Close = config.GetNormalizedPrice(csv[4].ToDecimal()*_scaleFactor)
};
quoteBar.LastBidSize = csv[5].ToInt64();
}
else
{
quoteBar.Bid = null;
}
// only create the ask if it exists in the file
if (csv[6].Length != 0 || csv[7].Length != 0 || csv[8].Length != 0 || csv[9].Length != 0)
{
quoteBar.Ask = new Bar
{
Open = config.GetNormalizedPrice(csv[6].ToDecimal()*_scaleFactor),
High = config.GetNormalizedPrice(csv[7].ToDecimal()*_scaleFactor),
Low = config.GetNormalizedPrice(csv[8].ToDecimal()*_scaleFactor),
Close = config.GetNormalizedPrice(csv[9].ToDecimal()*_scaleFactor)
};
quoteBar.LastAskSize = csv[10].ToInt64();
}
else
{
quoteBar.Ask = null;
}
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Get Source for Custom Data File
/// >> What source file location would you prefer for each type of usage:
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source request if source spread across multiple files</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String source location of the file</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
return new SubscriptionDataSource(string.Empty, SubscriptionTransportMedium.LocalFile);
}
var source = LeanData.GenerateZipFilePath(Constants.DataFolder, config.Symbol, date, config.Resolution, config.TickType);
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
}
/// <summary>
/// Return a new instance clone of this quote bar, used in fill forward
/// </summary>
/// <returns>A clone of the current quote bar</returns>
public override BaseData Clone()
{
return new QuoteBar
{
Ask = Ask == null ? null : Ask.Clone(),
Bid = Bid == null ? null : Bid.Clone(),
LastAskSize = LastAskSize,
LastBidSize = LastBidSize,
Symbol = Symbol,
Time = Time,
Period = Period,
Value = Value,
DataType = DataType
};
}
}
}
| |
/*
* 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 Term = Lucene.Net.Index.Term;
using SmallFloat = Lucene.Net.Util.SmallFloat;
namespace Lucene.Net.Search
{
/// <summary>Expert: Scoring API.
/// <p>Subclasses implement search scoring.
///
/// <p>The score of query <code>q</code> for document <code>d</code> correlates to the
/// cosine-distance or dot-product between document and query vectors in a
/// <a href="http://en.wikipedia.org/wiki/Vector_Space_Model">
/// Vector Space Model (VSM) of Information Retrieval</a>.
/// A document whose vector is closer to the query vector in that model is scored higher.
///
/// The score is computed as follows:
///
/// <P>
/// <table cellpadding="1" cellspacing="0" border="1" align="center">
/// <tr><td>
/// <table cellpadding="1" cellspacing="0" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// score(q,d) =
/// <A HREF="#formula_coord">coord(q,d)</A> ·
/// <A HREF="#formula_queryNorm">queryNorm(q)</A> ·
/// </td>
/// <td valign="bottom" align="center" rowspan="1">
/// <big><big><big>∑</big></big></big>
/// </td>
/// <td valign="middle" align="right" rowspan="1">
/// <big><big>(</big></big>
/// <A HREF="#formula_tf">tf(t in d)</A> ·
/// <A HREF="#formula_idf">idf(t)</A><sup>2</sup> ·
/// <A HREF="#formula_termBoost">t.getBoost()</A> ·
/// <A HREF="#formula_norm">norm(t,d)</A>
/// <big><big>)</big></big>
/// </td>
/// </tr>
/// <tr valigh="top">
/// <td></td>
/// <td align="center"><small>t in q</small></td>
/// <td></td>
/// </tr>
/// </table>
/// </td></tr>
/// </table>
///
/// <p> where
/// <ol>
/// <li>
/// <A NAME="formula_tf"></A>
/// <b>tf(t in d)</b>
/// correlates to the term's <i>frequency</i>,
/// defined as the number of times term <i>t</i> appears in the currently scored document <i>d</i>.
/// Documents that have more occurrences of a given term receive a higher score.
/// The default computation for <i>tf(t in d)</i> in
/// {@link Lucene.Net.Search.DefaultSimilarity#Tf(float) DefaultSimilarity} is:
///
/// <br> <br>
/// <table cellpadding="2" cellspacing="2" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// {@link Lucene.Net.Search.DefaultSimilarity#Tf(float) tf(t in d)} =
/// </td>
/// <td valign="top" align="center" rowspan="1">
/// frequency<sup><big>½</big></sup>
/// </td>
/// </tr>
/// </table>
/// <br> <br>
/// </li>
///
/// <li>
/// <A NAME="formula_idf"></A>
/// <b>idf(t)</b> stands for Inverse Document Frequency. This value
/// correlates to the inverse of <i>docFreq</i>
/// (the number of documents in which the term <i>t</i> appears).
/// This means rarer terms give higher contribution to the total score.
/// The default computation for <i>idf(t)</i> in
/// {@link Lucene.Net.Search.DefaultSimilarity#Idf(int, int) DefaultSimilarity} is:
///
/// <br> <br>
/// <table cellpadding="2" cellspacing="2" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right">
/// {@link Lucene.Net.Search.DefaultSimilarity#Idf(int, int) idf(t)} =
/// </td>
/// <td valign="middle" align="center">
/// 1 + log <big>(</big>
/// </td>
/// <td valign="middle" align="center">
/// <table>
/// <tr><td align="center"><small>numDocs</small></td></tr>
/// <tr><td align="center">–––––––––</td></tr>
/// <tr><td align="center"><small>docFreq+1</small></td></tr>
/// </table>
/// </td>
/// <td valign="middle" align="center">
/// <big>)</big>
/// </td>
/// </tr>
/// </table>
/// <br> <br>
/// </li>
///
/// <li>
/// <A NAME="formula_coord"></A>
/// <b>coord(q,d)</b>
/// is a score factor based on how many of the query terms are found in the specified document.
/// Typically, a document that contains more of the query's terms will receive a higher score
/// than another document with fewer query terms.
/// This is a search time factor computed in
/// {@link #Coord(int, int) coord(q,d)}
/// by the Similarity in effect at search time.
/// <br> <br>
/// </li>
///
/// <li><b>
/// <A NAME="formula_queryNorm"></A>
/// queryNorm(q)
/// </b>
/// is a normalizing factor used to make scores between queries comparable.
/// This factor does not affect document ranking (since all ranked documents are multiplied by the same factor),
/// but rather just attempts to make scores from different queries (or even different indexes) comparable.
/// This is a search time factor computed by the Similarity in effect at search time.
///
/// The default computation in
/// {@link Lucene.Net.Search.DefaultSimilarity#QueryNorm(float) DefaultSimilarity}
/// is:
/// <br> <br>
/// <table cellpadding="1" cellspacing="0" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// queryNorm(q) =
/// {@link Lucene.Net.Search.DefaultSimilarity#QueryNorm(float) queryNorm(sumOfSquaredWeights)}
/// =
/// </td>
/// <td valign="middle" align="center" rowspan="1">
/// <table>
/// <tr><td align="center"><big>1</big></td></tr>
/// <tr><td align="center"><big>
/// ––––––––––––––
/// </big></td></tr>
/// <tr><td align="center">sumOfSquaredWeights<sup><big>½</big></sup></td></tr>
/// </table>
/// </td>
/// </tr>
/// </table>
/// <br> <br>
///
/// The sum of squared weights (of the query terms) is
/// computed by the query {@link Lucene.Net.Search.Weight} object.
/// For example, a {@link Lucene.Net.Search.BooleanQuery boolean query}
/// computes this value as:
///
/// <br> <br>
/// <table cellpadding="1" cellspacing="0" border="0"n align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// {@link Lucene.Net.Search.Weight#SumOfSquaredWeights() sumOfSquaredWeights} =
/// {@link Lucene.Net.Search.Query#GetBoost() q.getBoost()} <sup><big>2</big></sup>
/// ·
/// </td>
/// <td valign="bottom" align="center" rowspan="1">
/// <big><big><big>∑</big></big></big>
/// </td>
/// <td valign="middle" align="right" rowspan="1">
/// <big><big>(</big></big>
/// <A HREF="#formula_idf">idf(t)</A> ·
/// <A HREF="#formula_termBoost">t.getBoost()</A>
/// <big><big>) <sup>2</sup> </big></big>
/// </td>
/// </tr>
/// <tr valigh="top">
/// <td></td>
/// <td align="center"><small>t in q</small></td>
/// <td></td>
/// </tr>
/// </table>
/// <br> <br>
///
/// </li>
///
/// <li>
/// <A NAME="formula_termBoost"></A>
/// <b>t.getBoost()</b>
/// is a search time boost of term <i>t</i> in the query <i>q</i> as
/// specified in the query text
/// (see <A HREF="../../../../../queryparsersyntax.html#Boosting a Term">query syntax</A>),
/// or as set by application calls to
/// {@link Lucene.Net.Search.Query#SetBoost(float) setBoost()}.
/// Notice that there is really no direct API for accessing a boost of one term in a multi term query,
/// but rather multi terms are represented in a query as multi
/// {@link Lucene.Net.Search.TermQuery TermQuery} objects,
/// and so the boost of a term in the query is accessible by calling the sub-query
/// {@link Lucene.Net.Search.Query#GetBoost() getBoost()}.
/// <br> <br>
/// </li>
///
/// <li>
/// <A NAME="formula_norm"></A>
/// <b>norm(t,d)</b> encapsulates a few (indexing time) boost and length factors:
///
/// <ul>
/// <li><b>Document boost</b> - set by calling
/// {@link Lucene.Net.Documents.Document#SetBoost(float) doc.setBoost()}
/// before adding the document to the index.
/// </li>
/// <li><b>Field boost</b> - set by calling
/// {@link Lucene.Net.Documents.Fieldable#SetBoost(float) field.setBoost()}
/// before adding the field to a document.
/// </li>
/// <li>{@link #LengthNorm(String, int) <b>lengthNorm</b>(field)} - computed
/// when the document is added to the index in accordance with the number of tokens
/// of this field in the document, so that shorter fields contribute more to the score.
/// LengthNorm is computed by the Similarity class in effect at indexing.
/// </li>
/// </ul>
///
/// <p>
/// When a document is added to the index, all the above factors are multiplied.
/// If the document has multiple fields with the same name, all their boosts are multiplied together:
///
/// <br> <br>
/// <table cellpadding="1" cellspacing="0" border="0"n align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// norm(t,d) =
/// {@link Lucene.Net.Documents.Document#GetBoost() doc.getBoost()}
/// ·
/// {@link #LengthNorm(String, int) lengthNorm(field)}
/// ·
/// </td>
/// <td valign="bottom" align="center" rowspan="1">
/// <big><big><big>∏</big></big></big>
/// </td>
/// <td valign="middle" align="right" rowspan="1">
/// {@link Lucene.Net.Documents.Fieldable#GetBoost() f.getBoost}()
/// </td>
/// </tr>
/// <tr valigh="top">
/// <td></td>
/// <td align="center"><small>field <i><b>f</b></i> in <i>d</i> named as <i><b>t</b></i></small></td>
/// <td></td>
/// </tr>
/// </table>
/// <br> <br>
/// However the resulted <i>norm</i> value is {@link #EncodeNorm(float) encoded} as a single byte
/// before being stored.
/// At search time, the norm byte value is read from the index
/// {@link Lucene.Net.Store.Directory directory} and
/// {@link #DecodeNorm(byte) decoded} back to a float <i>norm</i> value.
/// This encoding/decoding, while reducing index size, comes with the price of
/// precision loss - it is not guaranteed that decode(encode(x)) = x.
/// For instance, decode(encode(0.89)) = 0.75.
/// Also notice that search time is too late to modify this <i>norm</i> part of scoring, e.g. by
/// using a different {@link Similarity} for search.
/// <br> <br>
/// </li>
/// </ol>
///
/// </summary>
/// <seealso cref="#SetDefault(Similarity)">
/// </seealso>
/// <seealso cref="IndexWriter#SetSimilarity(Similarity)">
/// </seealso>
/// <seealso cref="Searcher#SetSimilarity(Similarity)">
/// </seealso>
[Serializable]
public abstract class Similarity
{
/// <summary>The Similarity implementation used by default. </summary>
private static Similarity defaultImpl = new DefaultSimilarity();
/// <summary>Set the default Similarity implementation used by indexing and search
/// code.
///
/// </summary>
/// <seealso cref="Searcher#SetSimilarity(Similarity)">
/// </seealso>
/// <seealso cref="IndexWriter#SetSimilarity(Similarity)">
/// </seealso>
public static void SetDefault(Similarity similarity)
{
Similarity.defaultImpl = similarity;
}
/// <summary>Return the default Similarity implementation used by indexing and search
/// code.
///
/// <p>This is initially an instance of {@link DefaultSimilarity}.
///
/// </summary>
/// <seealso cref="Searcher#SetSimilarity(Similarity)">
/// </seealso>
/// <seealso cref="IndexWriter#SetSimilarity(Similarity)">
/// </seealso>
public static Similarity GetDefault()
{
return Similarity.defaultImpl;
}
/// <summary>Cache of decoded bytes. </summary>
private static readonly float[] NORM_TABLE = new float[256];
/// <summary>Decodes a normalization factor stored in an index.</summary>
/// <seealso cref="#EncodeNorm(float)">
/// </seealso>
public static float DecodeNorm(byte b)
{
return NORM_TABLE[b & 0xFF]; // & 0xFF maps negative bytes to positive above 127
}
/// <summary>Returns a table for decoding normalization bytes.</summary>
/// <seealso cref="#EncodeNorm(float)">
/// </seealso>
public static float[] GetNormDecoder()
{
return NORM_TABLE;
}
/// <summary>Computes the normalization value for a field given the total number of
/// terms contained in a field. These values, together with field boosts, are
/// stored in an index and multipled into scores for hits on each field by the
/// search code.
///
/// <p>Matches in longer fields are less precise, so implementations of this
/// method usually return smaller values when <code>numTokens</code> is large,
/// and larger values when <code>numTokens</code> is small.
///
/// <p>That these values are computed under
/// {@link Lucene.Net.Index.IndexWriter#AddDocument(Lucene.Net.Documents.Document)}
/// and stored then using
/// {@link #EncodeNorm(float)}.
/// Thus they have limited precision, and documents
/// must be re-indexed if this method is altered.
///
/// </summary>
/// <param name="fieldName">the name of the field
/// </param>
/// <param name="numTokens">the total number of tokens contained in fields named
/// <i>fieldName</i> of <i>doc</i>.
/// </param>
/// <returns> a normalization factor for hits on this field of this document
///
/// </returns>
/// <seealso cref="Lucene.Net.Documents.Field.SetBoost(float)">
/// </seealso>
public abstract float LengthNorm(System.String fieldName, int numTokens);
/// <summary>Computes the normalization value for a query given the sum of the squared
/// weights of each of the query terms. This value is then multipled into the
/// weight of each query term.
///
/// <p>This does not affect ranking, but rather just attempts to make scores
/// from different queries comparable.
///
/// </summary>
/// <param name="sumOfSquaredWeights">the sum of the squares of query term weights
/// </param>
/// <returns> a normalization factor for query weights
/// </returns>
public abstract float QueryNorm(float sumOfSquaredWeights);
/// <summary>Encodes a normalization factor for storage in an index.
///
/// <p>The encoding uses a three-bit mantissa, a five-bit exponent, and
/// the zero-exponent point at 15, thus
/// representing values from around 7x10^9 to 2x10^-9 with about one
/// significant decimal digit of accuracy. Zero is also represented.
/// Negative numbers are rounded up to zero. Values too large to represent
/// are rounded down to the largest representable value. Positive values too
/// small to represent are rounded up to the smallest positive representable
/// value.
///
/// </summary>
/// <seealso cref="Lucene.Net.Documents.Field#SetBoost(float)">
/// </seealso>
/// <seealso cref="SmallFloat">
/// </seealso>
public static byte EncodeNorm(float f)
{
return (byte) SmallFloat.FloatToByte315(f);
}
/// <summary>Computes a score factor based on a term or phrase's frequency in a
/// document. This value is multiplied by the {@link #Idf(Term, Searcher)}
/// factor for each term in the query and these products are then summed to
/// form the initial score for a document.
///
/// <p>Terms and phrases repeated in a document indicate the topic of the
/// document, so implementations of this method usually return larger values
/// when <code>freq</code> is large, and smaller values when <code>freq</code>
/// is small.
///
/// <p>The default implementation calls {@link #Tf(float)}.
///
/// </summary>
/// <param name="freq">the frequency of a term within a document
/// </param>
/// <returns> a score factor based on a term's within-document frequency
/// </returns>
public virtual float Tf(int freq)
{
return Tf((float) freq);
}
/// <summary>Computes the amount of a sloppy phrase match, based on an edit distance.
/// This value is summed for each sloppy phrase match in a document to form
/// the frequency that is passed to {@link #Tf(float)}.
///
/// <p>A phrase match with a small edit distance to a document passage more
/// closely matches the document, so implementations of this method usually
/// return larger values when the edit distance is small and smaller values
/// when it is large.
///
/// </summary>
/// <seealso cref="PhraseQuery.SetSlop(int)">
/// </seealso>
/// <param name="distance">the edit distance of this sloppy phrase match
/// </param>
/// <returns> the frequency increment for this match
/// </returns>
public abstract float SloppyFreq(int distance);
/// <summary>Computes a score factor based on a term or phrase's frequency in a
/// document. This value is multiplied by the {@link #Idf(Term, Searcher)}
/// factor for each term in the query and these products are then summed to
/// form the initial score for a document.
///
/// <p>Terms and phrases repeated in a document indicate the topic of the
/// document, so implementations of this method usually return larger values
/// when <code>freq</code> is large, and smaller values when <code>freq</code>
/// is small.
///
/// </summary>
/// <param name="freq">the frequency of a term within a document
/// </param>
/// <returns> a score factor based on a term's within-document frequency
/// </returns>
public abstract float Tf(float freq);
/// <summary>Computes a score factor for a simple term.
///
/// <p>The default implementation is:<pre>
/// return idf(searcher.docFreq(term), searcher.maxDoc());
/// </pre>
///
/// Note that {@link Searcher#MaxDoc()} is used instead of
/// {@link IndexReader#NumDocs()} because it is proportional to
/// {@link Searcher#DocFreq(Term)} , i.e., when one is inaccurate,
/// so is the other, and in the same direction.
///
/// </summary>
/// <param name="term">the term in question
/// </param>
/// <param name="searcher">the document collection being searched
/// </param>
/// <returns> a score factor for the term
/// </returns>
public virtual float Idf(Term term, Searcher searcher)
{
return Idf(searcher.DocFreq(term), searcher.MaxDoc());
}
/// <summary>Computes a score factor for a phrase.
///
/// <p>The default implementation sums the {@link #Idf(Term,Searcher)} factor
/// for each term in the phrase.
///
/// </summary>
/// <param name="terms">the terms in the phrase
/// </param>
/// <param name="searcher">the document collection being searched
/// </param>
/// <returns> a score factor for the phrase
/// </returns>
public virtual float Idf(System.Collections.ICollection terms, Searcher searcher)
{
float idf = 0.0f;
System.Collections.IEnumerator i = terms.GetEnumerator();
while (i.MoveNext())
{
idf += Idf((Term) i.Current, searcher);
}
return idf;
}
/// <summary>Computes a score factor based on a term's document frequency (the number
/// of documents which contain the term). This value is multiplied by the
/// {@link #Tf(int)} factor for each term in the query and these products are
/// then summed to form the initial score for a document.
///
/// <p>Terms that occur in fewer documents are better indicators of topic, so
/// implementations of this method usually return larger values for rare terms,
/// and smaller values for common terms.
///
/// </summary>
/// <param name="docFreq">the number of documents which contain the term
/// </param>
/// <param name="numDocs">the total number of documents in the collection
/// </param>
/// <returns> a score factor based on the term's document frequency
/// </returns>
public abstract float Idf(int docFreq, int numDocs);
/// <summary>Computes a score factor based on the fraction of all query terms that a
/// document contains. This value is multiplied into scores.
///
/// <p>The presence of a large portion of the query terms indicates a better
/// match with the query, so implementations of this method usually return
/// larger values when the ratio between these parameters is large and smaller
/// values when the ratio between them is small.
///
/// </summary>
/// <param name="overlap">the number of query terms matched in the document
/// </param>
/// <param name="maxOverlap">the total number of terms in the query
/// </param>
/// <returns> a score factor based on term overlap with the query
/// </returns>
public abstract float Coord(int overlap, int maxOverlap);
/// <summary> Calculate a scoring factor based on the data in the payload. Overriding implementations
/// are responsible for interpreting what is in the payload. Lucene makes no assumptions about
/// what is in the byte array.
/// <p>
/// The default implementation returns 1.
///
/// </summary>
/// <param name="fieldName">The fieldName of the term this payload belongs to
/// </param>
/// <param name="payload">The payload byte array to be scored
/// </param>
/// <param name="offset">The offset into the payload array
/// </param>
/// <param name="length">The length in the array
/// </param>
/// <returns> An implementation dependent float to be used as a scoring factor
/// </returns>
public virtual float ScorePayload(System.String fieldName, byte[] payload, int offset, int length)
{
//Do nothing
return 1;
}
static Similarity()
{
{
for (int i = 0; i < 256; i++)
NORM_TABLE[i] = SmallFloat.Byte315ToFloat((byte) i);
}
}
}
}
| |
/*
'===============================================================================
' Generated From - CSharp_dOOdads_BusinessEntity.vbgen
'
' ** IMPORTANT **
' How to Generate your stored procedures:
'
' SQL = SQL_StoredProcs.vbgen
' ACCESS = Access_StoredProcs.vbgen
' ORACLE = Oracle_StoredProcs.vbgen
' FIREBIRD = FirebirdStoredProcs.vbgen
' POSTGRESQL = PostgreSQL_StoredProcs.vbgen
'
' The supporting base class PostgreSqlEntity is in the Architecture directory in "dOOdads".
'
' This object is 'abstract' which means you need to inherit from it to be able
' to instantiate it. This is very easilly done. You can override properties and
' methods in your derived class, this allows you to regenerate this class at any
' time and not worry about overwriting custom code.
'
' NEVER EDIT THIS FILE.
'
' public class YourObject : _YourObject
' {
'
' }
'
'===============================================================================
*/
// Generated by MyGeneration Version # (1.1.0.0)
using System;
using System.Data;
using Npgsql;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace CSharp.POSTGRESQL
{
public abstract class _tblCustomers1 : PostgreSqlEntity
{
public _tblCustomers1()
{
this.QuerySource = "tblCustomers1";
this.MappingName = "tblCustomers1";
}
//=================================================================
// public Overrides void AddNew()
//=================================================================
//
//=================================================================
public override void AddNew()
{
base.AddNew();
}
public override void FlushData()
{
this._whereClause = null;
base.FlushData();
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
ListDictionary parameters = null;
return base.LoadFromSql(this.SchemaStoredProcedure + "tblCustomers1_load_all", parameters);
}
//=================================================================
// public Overridable Function LoadByPrimaryKey() As Boolean
//=================================================================
// Loads a single row of via the primary key
//=================================================================
public virtual bool LoadByPrimaryKey(int ICustomerId)
{
ListDictionary parameters = new ListDictionary();
parameters.Add(Parameters.ICustomerId, ICustomerId);
return base.LoadFromSql(this.SchemaStoredProcedure + "tblCustomers1_load_by_primarykey", parameters);
}
#region Parameters
protected class Parameters
{
public static NpgsqlParameter ICustomerId
{
get
{
return new NpgsqlParameter("ICustomerId", NpgsqlTypes.NpgsqlDbType.Integer, 0);
}
}
public static NpgsqlParameter SCustomerName
{
get
{
return new NpgsqlParameter("SCustomerName", NpgsqlTypes.NpgsqlDbType.Varchar, 50);
}
}
public static NpgsqlParameter SCustomerEmail
{
get
{
return new NpgsqlParameter("SCustomerEmail", NpgsqlTypes.NpgsqlDbType.Varchar, 50);
}
}
public static NpgsqlParameter SCustomerPhone1
{
get
{
return new NpgsqlParameter("SCustomerPhone1", NpgsqlTypes.NpgsqlDbType.Varchar, 50);
}
}
public static NpgsqlParameter SCustomerHistory
{
get
{
return new NpgsqlParameter("SCustomerHistory", NpgsqlTypes.NpgsqlDbType.Text, 0);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string ICustomerId = "iCustomerId";
public const string SCustomerName = "sCustomerName";
public const string SCustomerEmail = "sCustomerEmail";
public const string SCustomerPhone1 = "sCustomerPhone1";
public const string SCustomerHistory = "sCustomerHistory";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ICustomerId] = _tblCustomers1.PropertyNames.ICustomerId;
ht[SCustomerName] = _tblCustomers1.PropertyNames.SCustomerName;
ht[SCustomerEmail] = _tblCustomers1.PropertyNames.SCustomerEmail;
ht[SCustomerPhone1] = _tblCustomers1.PropertyNames.SCustomerPhone1;
ht[SCustomerHistory] = _tblCustomers1.PropertyNames.SCustomerHistory;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string ICustomerId = "ICustomerId";
public const string SCustomerName = "SCustomerName";
public const string SCustomerEmail = "SCustomerEmail";
public const string SCustomerPhone1 = "SCustomerPhone1";
public const string SCustomerHistory = "SCustomerHistory";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ICustomerId] = _tblCustomers1.ColumnNames.ICustomerId;
ht[SCustomerName] = _tblCustomers1.ColumnNames.SCustomerName;
ht[SCustomerEmail] = _tblCustomers1.ColumnNames.SCustomerEmail;
ht[SCustomerPhone1] = _tblCustomers1.ColumnNames.SCustomerPhone1;
ht[SCustomerHistory] = _tblCustomers1.ColumnNames.SCustomerHistory;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string ICustomerId = "s_ICustomerId";
public const string SCustomerName = "s_SCustomerName";
public const string SCustomerEmail = "s_SCustomerEmail";
public const string SCustomerPhone1 = "s_SCustomerPhone1";
public const string SCustomerHistory = "s_SCustomerHistory";
}
#endregion
#region Properties
public virtual int ICustomerId
{
get
{
return base.Getint(ColumnNames.ICustomerId);
}
set
{
base.Setint(ColumnNames.ICustomerId, value);
}
}
public virtual string SCustomerName
{
get
{
return base.Getstring(ColumnNames.SCustomerName);
}
set
{
base.Setstring(ColumnNames.SCustomerName, value);
}
}
public virtual string SCustomerEmail
{
get
{
return base.Getstring(ColumnNames.SCustomerEmail);
}
set
{
base.Setstring(ColumnNames.SCustomerEmail, value);
}
}
public virtual string SCustomerPhone1
{
get
{
return base.Getstring(ColumnNames.SCustomerPhone1);
}
set
{
base.Setstring(ColumnNames.SCustomerPhone1, value);
}
}
public virtual string SCustomerHistory
{
get
{
return base.Getstring(ColumnNames.SCustomerHistory);
}
set
{
base.Setstring(ColumnNames.SCustomerHistory, value);
}
}
#endregion
#region String Properties
public virtual string s_ICustomerId
{
get
{
return this.IsColumnNull(ColumnNames.ICustomerId) ? string.Empty : base.GetintAsString(ColumnNames.ICustomerId);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ICustomerId);
else
this.ICustomerId = base.SetintAsString(ColumnNames.ICustomerId, value);
}
}
public virtual string s_SCustomerName
{
get
{
return this.IsColumnNull(ColumnNames.SCustomerName) ? string.Empty : base.GetstringAsString(ColumnNames.SCustomerName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.SCustomerName);
else
this.SCustomerName = base.SetstringAsString(ColumnNames.SCustomerName, value);
}
}
public virtual string s_SCustomerEmail
{
get
{
return this.IsColumnNull(ColumnNames.SCustomerEmail) ? string.Empty : base.GetstringAsString(ColumnNames.SCustomerEmail);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.SCustomerEmail);
else
this.SCustomerEmail = base.SetstringAsString(ColumnNames.SCustomerEmail, value);
}
}
public virtual string s_SCustomerPhone1
{
get
{
return this.IsColumnNull(ColumnNames.SCustomerPhone1) ? string.Empty : base.GetstringAsString(ColumnNames.SCustomerPhone1);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.SCustomerPhone1);
else
this.SCustomerPhone1 = base.SetstringAsString(ColumnNames.SCustomerPhone1, value);
}
}
public virtual string s_SCustomerHistory
{
get
{
return this.IsColumnNull(ColumnNames.SCustomerHistory) ? string.Empty : base.GetstringAsString(ColumnNames.SCustomerHistory);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.SCustomerHistory);
else
this.SCustomerHistory = base.SetstringAsString(ColumnNames.SCustomerHistory, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter ICustomerId
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ICustomerId, Parameters.ICustomerId);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter SCustomerName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.SCustomerName, Parameters.SCustomerName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter SCustomerEmail
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.SCustomerEmail, Parameters.SCustomerEmail);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter SCustomerPhone1
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.SCustomerPhone1, Parameters.SCustomerPhone1);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter SCustomerHistory
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.SCustomerHistory, Parameters.SCustomerHistory);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter ICustomerId
{
get
{
if(_ICustomerId_W == null)
{
_ICustomerId_W = TearOff.ICustomerId;
}
return _ICustomerId_W;
}
}
public WhereParameter SCustomerName
{
get
{
if(_SCustomerName_W == null)
{
_SCustomerName_W = TearOff.SCustomerName;
}
return _SCustomerName_W;
}
}
public WhereParameter SCustomerEmail
{
get
{
if(_SCustomerEmail_W == null)
{
_SCustomerEmail_W = TearOff.SCustomerEmail;
}
return _SCustomerEmail_W;
}
}
public WhereParameter SCustomerPhone1
{
get
{
if(_SCustomerPhone1_W == null)
{
_SCustomerPhone1_W = TearOff.SCustomerPhone1;
}
return _SCustomerPhone1_W;
}
}
public WhereParameter SCustomerHistory
{
get
{
if(_SCustomerHistory_W == null)
{
_SCustomerHistory_W = TearOff.SCustomerHistory;
}
return _SCustomerHistory_W;
}
}
private WhereParameter _ICustomerId_W = null;
private WhereParameter _SCustomerName_W = null;
private WhereParameter _SCustomerEmail_W = null;
private WhereParameter _SCustomerPhone1_W = null;
private WhereParameter _SCustomerHistory_W = null;
public void WhereClauseReset()
{
_ICustomerId_W = null;
_SCustomerName_W = null;
_SCustomerEmail_W = null;
_SCustomerPhone1_W = null;
_SCustomerHistory_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = this.SchemaStoredProcedure + "tblCustomers1_insert";
CreateParameters(cmd);
NpgsqlParameter p;
p = cmd.Parameters[Parameters.ICustomerId.ParameterName];
p.Direction = ParameterDirection.Output;
return cmd;
}
protected override IDbCommand GetUpdateCommand()
{
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = this.SchemaStoredProcedure + "tblCustomers1_update";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetDeleteCommand()
{
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = this.SchemaStoredProcedure + "tblCustomers1_delete";
NpgsqlParameter p;
p = cmd.Parameters.Add(Parameters.ICustomerId);
p.SourceColumn = ColumnNames.ICustomerId;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
private IDbCommand CreateParameters(NpgsqlCommand cmd)
{
NpgsqlParameter p;
p = cmd.Parameters.Add(Parameters.ICustomerId);
p.SourceColumn = ColumnNames.ICustomerId;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.SCustomerName);
p.SourceColumn = ColumnNames.SCustomerName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.SCustomerEmail);
p.SourceColumn = ColumnNames.SCustomerEmail;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.SCustomerPhone1);
p.SourceColumn = ColumnNames.SCustomerPhone1;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.SCustomerHistory);
p.SourceColumn = ColumnNames.SCustomerHistory;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Brushes;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Numerics;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Input;
using Windows.UI.Xaml.Controls;
namespace ExampleGallery
{
public sealed partial class CustomFonts : UserControl
{
struct Entry
{
public int Code;
public string Label;
public Entry(int code, string label)
{
Code = code;
Label = label;
}
}
public CustomFonts()
{
this.InitializeComponent();
}
static CanvasTextFormat labelText = new CanvasTextFormat()
{
FontSize = 24,
HorizontalAlignment = CanvasHorizontalAlignment.Left,
VerticalAlignment = CanvasVerticalAlignment.Center
};
static CanvasTextFormat symbolText = new CanvasTextFormat()
{
FontSize = 24,
FontFamily = "Symbols.ttf#Symbols",
HorizontalAlignment = CanvasHorizontalAlignment.Right,
VerticalAlignment = CanvasVerticalAlignment.Center
};
static float lineHeight = symbolText.FontSize * 1.5f;
CanvasLinearGradientBrush textOpacityBrush;
CanvasLinearGradientBrush blurOpacityBrush;
CoreIndependentInputSource inputSource;
GestureRecognizer gestureRecognizer;
private void OnGameLoopStarting(ICanvasAnimatedControl sender, object args)
{
//
// The GestureRecognizer needs to be created and accessed from the
// same thread -- in this case the game loop thread, so we use the GameLoopStarting event
// for this.
//
gestureRecognizer = new GestureRecognizer();
gestureRecognizer.GestureSettings = GestureSettings.ManipulationTranslateInertia | GestureSettings.ManipulationTranslateY;
gestureRecognizer.ManipulationStarted += gestureRecognizer_ManipulationStarted;
gestureRecognizer.ManipulationUpdated += gestureRecognizer_ManipulationUpdated;
gestureRecognizer.ManipulationCompleted += gestureRecognizer_ManipulationCompleted;
gestureRecognizer.InertiaTranslationDeceleration = -0.05f;
//
// When the GestureRecognizer goes into intertia mode (ie after the pointer is released)
// we want it to generate ManipulationUpdated events in sync with the game loop's Update.
// We do this by disabling AutoProcessIntertia and explicitly calling ProcessInertia()
// from the Update.
//
gestureRecognizer.AutoProcessInertia = false;
inputSource = animatedControl.CreateCoreIndependentInputSource(CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch);
inputSource.PointerPressed += Input_PointerPressed;
inputSource.PointerMoved += Input_PointerMoved;
inputSource.PointerReleased += Input_PointerReleased;
}
private void OnGameLoopStopped(ICanvasAnimatedControl sender, object args)
{
// Unregister the various input / gesture events. Since these have strong thread affinity
// this needs to be done on the game loop thread.
inputSource.PointerPressed -= Input_PointerPressed;
inputSource.PointerMoved -= Input_PointerMoved;
inputSource.PointerReleased -= Input_PointerReleased;
gestureRecognizer.ManipulationStarted -= gestureRecognizer_ManipulationStarted;
gestureRecognizer.ManipulationUpdated -= gestureRecognizer_ManipulationUpdated;
gestureRecognizer.ManipulationCompleted -= gestureRecognizer_ManipulationCompleted;
}
private void OnCreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
{
var stops = new CanvasGradientStop[]
{
new CanvasGradientStop() { Color=Colors.Transparent, Position=0.1f },
new CanvasGradientStop() { Color=Colors.White, Position = 0.3f },
new CanvasGradientStop() { Color=Colors.White, Position = 0.7f },
new CanvasGradientStop() { Color=Colors.Transparent, Position = 0.9f },
};
textOpacityBrush = new CanvasLinearGradientBrush(sender, stops, CanvasEdgeBehavior.Clamp, CanvasAlphaMode.Premultiplied);
stops = new CanvasGradientStop[]
{
new CanvasGradientStop() { Color=Colors.White, Position=0.0f },
new CanvasGradientStop() { Color=Colors.Transparent, Position = 0.3f },
new CanvasGradientStop() { Color=Colors.Transparent, Position = 0.7f },
new CanvasGradientStop() { Color=Colors.White, Position = 1.0f },
};
blurOpacityBrush = new CanvasLinearGradientBrush(sender, stops, CanvasEdgeBehavior.Clamp, CanvasAlphaMode.Premultiplied);
}
//
// The various Pointer events just forward to the GestureRecognizer
//
private void Input_PointerPressed(object sender, PointerEventArgs args)
{
gestureRecognizer.ProcessDownEvent(args.CurrentPoint);
args.Handled = true;
}
private void Input_PointerMoved(object sender, PointerEventArgs args)
{
gestureRecognizer.ProcessMoveEvents(args.GetIntermediatePoints());
args.Handled = true;
}
private void Input_PointerReleased(object sender, PointerEventArgs args)
{
gestureRecognizer.ProcessUpEvent(args.CurrentPoint);
args.Handled = true;
}
float offset = 0;
float velocity = 0;
const float targetSpeed = 2;
float targetVelocity = targetSpeed;
bool inManipulation;
void gestureRecognizer_ManipulationStarted(GestureRecognizer sender, ManipulationStartedEventArgs args)
{
velocity = 0;
inManipulation = true;
}
void gestureRecognizer_ManipulationUpdated(GestureRecognizer sender, ManipulationUpdatedEventArgs args)
{
offset = offset - (float)args.Delta.Translation.Y;
targetVelocity = -Math.Sign(args.Velocities.Linear.Y) * targetSpeed;
}
void gestureRecognizer_ManipulationCompleted(GestureRecognizer sender, ManipulationCompletedEventArgs args)
{
inManipulation = false;
}
int firstLine;
int lastLine;
private void OnUpdate(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args)
{
float height = (float)sender.Size.Height;
float totalHeight = characters.Length * lineHeight + height;
if (inManipulation)
{
if (gestureRecognizer != null)
gestureRecognizer.ProcessInertia();
}
else
{
velocity = velocity * 0.90f + targetVelocity * 0.10f;
offset = offset + velocity;
}
offset = offset % totalHeight;
while (offset < 0)
offset += totalHeight;
float top = height - offset;
firstLine = Math.Max(0, (int)(-top / lineHeight));
lastLine = Math.Min(characters.Length, (int)((height + lineHeight - top) / lineHeight));
}
private CanvasCommandList GenerateTextDisplay(ICanvasResourceCreator resourceCreator, float width, float height)
{
var cl = new CanvasCommandList(resourceCreator);
using (var ds = cl.CreateDrawingSession())
{
float top = height - offset;
float center = width / 4.0f;
float symbolPos = center - 5.0f;
float labelPos = center + 5.0f;
for (int i = firstLine; i < lastLine; ++i)
{
float y = top + lineHeight * i;
int index = i;
if (index < characters.Length)
{
ds.DrawText(string.Format("{0}", (char)characters[index].Code), symbolPos, y, Colors.White, symbolText);
ds.DrawText(string.Format("0x{0:X} - {1}", characters[index].Code, characters[index].Label), labelPos, y, Colors.White, labelText);
}
}
}
return cl;
}
private void OnDraw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
{
var textDisplay = GenerateTextDisplay(sender, (float)sender.Size.Width, (float)sender.Size.Height);
var blurEffect = new GaussianBlurEffect()
{
Source = textDisplay,
BlurAmount = 10
};
textOpacityBrush.StartPoint = blurOpacityBrush.StartPoint = new Vector2(0,0);
textOpacityBrush.EndPoint = blurOpacityBrush.EndPoint = new Vector2(0, (float)sender.Size.Height);
var ds = args.DrawingSession;
using (ds.CreateLayer(blurOpacityBrush))
{
ds.DrawImage(blurEffect);
}
using (ds.CreateLayer(textOpacityBrush))
{
ds.DrawImage(textDisplay);
}
}
private void UserControl_Unloaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// Explicitly remove references to allow the Win2D controls to get
// garbage collected
animatedControl.RemoveFromVisualTree();
animatedControl = null;
}
static Entry[] characters = new Entry[]
{
new Entry(0xE018, "Scrollbar arrow"),
new Entry(0xE019, "Scrollbar arrow"),
new Entry(0xE081, "Check box"),
new Entry(0xE082, "Ratings star"),
new Entry(0xE094, "Magnifier"),
new Entry(0xE0B8, "Used by magnifier tool"),
new Entry(0xE0D5, "Back arrow"),
new Entry(0xE0AE, "Mirrored version of U+E0D4"),
new Entry(0xE0E2, "Arrow used in FlipView"),
new Entry(0xE0E3, "Arrow used in FlipView"),
new Entry(0xE0E4, "Arrow used in FlipView"),
new Entry(0xE0E5, "Arrow used in FlipView"),
new Entry(0xE0E7, "AppBar menu checkmark"),
new Entry(0xE224, "Outline ratings star"),
new Entry(0xE26B, "Arrow used in group headers"),
new Entry(0xE26C, "Arrow used in group headers"),
new Entry(0xE100, "Previous"),
new Entry(0xE168, "Accounts"),
new Entry(0xE101, "Next"),
new Entry(0xE169, "Show bcc"),
new Entry(0xE102, "Play"),
new Entry(0xE16A, "Bcc"),
new Entry(0xE103, "Pause"),
new Entry(0xE16B, "Cut"),
new Entry(0xE104, "Edit"),
new Entry(0xE16C, "Attach"),
new Entry(0xE105, "Save"),
new Entry(0xE16D, "Paste"),
new Entry(0xE106, "Clear"),
new Entry(0xE16E, "Filter"),
new Entry(0xE107, "Trash"),
new Entry(0xE16F, "Copy"),
new Entry(0xE108, "Remove"),
new Entry(0xE170, "Emoji2"),
new Entry(0xE109, "Add"),
new Entry(0xE171, "High priority"),
new Entry(0xE10A, "Cancel"),
new Entry(0xE172, "Reply (mirrored at U+E1AF)"),
new Entry(0xE10B, "Accept"),
new Entry(0xE173, "Slideshow"),
new Entry(0xE10C, "More"),
new Entry(0xE174, "Sort"),
new Entry(0xE10D, "Redo"),
new Entry(0xE178, "Manage"),
new Entry(0xE10E, "Undo"),
new Entry(0xE179, "All applications (mirrored at U+E1EC)"),
new Entry(0xE10F, "Home"),
new Entry(0xE17A, "Disconnect network drive"),
new Entry(0xE110, "Up"),
new Entry(0xE17B, "Map network drive"),
new Entry(0xE111, "Forward"),
new Entry(0xE17C, "Open new windows"),
new Entry(0xE112, "Back"),
new Entry(0xE17D, "Open with (mirrored at U+E1ED)"),
new Entry(0xE113, "Favorite"),
new Entry(0xE181, "Contact presence"),
new Entry(0xE114, "Camera"),
new Entry(0xE182, "Options"),
new Entry(0xE115, "Settings"),
new Entry(0xE183, "Upload"),
new Entry(0xE116, "Video"),
new Entry(0xE184, "Calendar"),
new Entry(0xE117, "Sync"),
new Entry(0xE185, "Font"),
new Entry(0xE118, "Download"),
new Entry(0xE186, "Font color"),
new Entry(0xE119, "Mail"),
new Entry(0xE187, "Contact 2"),
new Entry(0xE11A, "Find"),
new Entry(0xE188, "Browse by album (mirrored at U+E1C1)"),
new Entry(0xE11B, "Help (mirrored at U+E1F3)"),
new Entry(0xE189, "Alternate audio track"),
new Entry(0xE11C, "Upload"),
new Entry(0xE18A, "Placeholder"),
new Entry(0xE11D, "Emoticon"),
new Entry(0xE18B, "View"),
new Entry(0xE11E, "Layout"),
new Entry(0xE18C, "Set as lock screen image"),
new Entry(0xE11F, "Leave multiple party conversation"),
new Entry(0xE18D, "Set as tile image"),
new Entry(0xE120, "Forward (mirrored at U+E1A8)"),
new Entry(0xE190, "Closed caption"),
new Entry(0xE121, "Timer"),
new Entry(0xE191, "Autoplay stop"),
new Entry(0xE122, "Send/Send calendar event (mirrored at U+E1A9)"),
new Entry(0xE192, "Permissions"),
new Entry(0xE123, "Crop"),
new Entry(0xE193, "Highlight"),
new Entry(0xE124, "Rotate camera"),
new Entry(0xE194, "Disable updates"),
new Entry(0xE125, "People"),
new Entry(0xE195, "Unfavorite"),
new Entry(0xE126, "Close metadata (mirrored at U+E1BF)"),
new Entry(0xE196, "Unpin"),
new Entry(0xE127, "Open metadata (mirrored at U+E1C0)"),
new Entry(0xE197, "Open file location"),
new Entry(0xE128, "Open in web"),
new Entry(0xE198, "Volume mute"),
new Entry(0xE129, "View notifications"),
new Entry(0xE199, "Italic"),
new Entry(0xE12A, "Preview link"),
new Entry(0xE19A, "Underline"),
new Entry(0xE12B, "Category not in A-Z"),
new Entry(0xE19B, "Bold"),
new Entry(0xE12C, "Trim"),
new Entry(0xE19C, "Move to folder"),
new Entry(0xE12D, "Attach camera"),
new Entry(0xE19D, "Choose like or dislike"),
new Entry(0xE12E, "Zoom"),
new Entry(0xE19E, "Dislike"),
new Entry(0xE12F, "Bookmarks (mirrored at U+E1EE)"),
new Entry(0xE19F, "Like"),
new Entry(0xE130, "PDF"),
new Entry(0xE1A0, "Align right"),
new Entry(0xE131, "Password protected PDF"),
new Entry(0xE1A1, "Align center"),
new Entry(0xE132, "Page"),
new Entry(0xE1A2, "Align left"),
new Entry(0xE133, "More options (mirrored at U+E1EF)"),
new Entry(0xE1A3, "Zoom neutral"),
new Entry(0xE134, "Post"),
new Entry(0xE1A4, "Zoom out"),
new Entry(0xE135, "Mail2"),
new Entry(0xE1A5, "Open file"),
new Entry(0xE136, "Contact info"),
new Entry(0xE1A6, "Other user"),
new Entry(0xE137, "Hang up"),
new Entry(0xE1A7, "Run as admin"),
new Entry(0xE138, "View all albums"),
new Entry(0xE1C3, "Street"),
new Entry(0xE139, "Map address"),
new Entry(0xE1C4, "Map"),
new Entry(0xE13A, "Phone"),
new Entry(0xE1C5, "Clear selection (mirrored at U+E1F4)"),
new Entry(0xE13B, "Video chat"),
new Entry(0xE1C6, "Font size decrease"),
new Entry(0xE13C, "Switch"),
new Entry(0xE1C7, "Font size increase"),
new Entry(0xE13D, "Contact"),
new Entry(0xE1C8, "Font size"),
new Entry(0xE13E, "Rename"),
new Entry(0xE1C9, "Cell phone"),
new Entry(0xE141, "Pin"),
new Entry(0xE1CA, "Retweet (full size)"),
new Entry(0xE142, "View all info"),
new Entry(0xE1CB, "Tag"),
new Entry(0xE143, "Go (mirrored at U+E1AA)"),
new Entry(0xE1CC, "Repeat once"),
new Entry(0xE144, "Keyboard"),
new Entry(0xE1CD, "Repeat/Loop"),
new Entry(0xE145, "Dock left"),
new Entry(0xE1CE, "Favorite star empty"),
new Entry(0xE146, "Dock right"),
new Entry(0xE1CF, "Add to favorite"),
new Entry(0xE147, "Dock bottom"),
new Entry(0xE1D0, "Calculator"),
new Entry(0xE148, "Remote desktop home"),
new Entry(0xE1D1, "Direction"),
new Entry(0xE149, "Refresh"),
new Entry(0xE1D2, "Current location/GPS"),
new Entry(0xE14A, "Rotate"),
new Entry(0xE1D3, "Library"),
new Entry(0xE14B, "Shuffle"),
new Entry(0xE1D4, "Address book"),
new Entry(0xE14C, "Details (mirrored at U+E175)"),
new Entry(0xE1D5, "Voicemail/Memo"),
new Entry(0xE14D, "Shop"),
new Entry(0xE1D6, "Microphone"),
new Entry(0xE14E, "Select all"),
new Entry(0xE1D7, "Post update"),
new Entry(0xE14F, "Rotate"),
new Entry(0xE1D8, "Back to window"),
new Entry(0xE150, "Import (mirrored at U+E1AD)"),
new Entry(0xE1D9, "Full screen"),
new Entry(0xE151, "Import all files (mirrored at U+E1AE)"),
new Entry(0xE1DA, "Add new folder"),
new Entry(0xE155, "Browse photos"),
new Entry(0xE1DB, "Calendar reply"),
new Entry(0xE156, "Webcam"),
new Entry(0xE1DD, "Unsync folder"),
new Entry(0xE158, "Picture library"),
new Entry(0xE1DE, "Report hacked"),
new Entry(0xE159, "Save local"),
new Entry(0xE1DF, "Sync folder"),
new Entry(0xE15A, "Caption"),
new Entry(0xE1E0, "Block contact"),
new Entry(0xE15B, "Stop"),
new Entry(0xE1E1, "RD switch apps"),
new Entry(0xE15C, "Results (find) (mirrored at U+E1F1)"),
new Entry(0xE1E2, "Add friend"),
new Entry(0xE15D, "Volume"),
new Entry(0xE1E3, "RD touch pointer"),
new Entry(0xE15E, "Tools"),
new Entry(0xE1E4, "RD go to start"),
new Entry(0xE15F, "Start chat"),
new Entry(0xE1E5, "RD zero bars"),
new Entry(0xE160, "Document"),
new Entry(0xE1E6, "RD one bar"),
new Entry(0xE161, "Day"),
new Entry(0xE1E7, "RD two bars"),
new Entry(0xE162, "Week"),
new Entry(0xE1E8, "RD three bars"),
new Entry(0xE163, "Month (mirrored at U+E1DC)"),
new Entry(0xE1E9, "RD four bars"),
new Entry(0xE164, "Match options"),
new Entry(0xE294, "Scan"),
new Entry(0xE165, "Reply all"),
new Entry(0xE295, "Preview"),
new Entry(0xE166, "Read"),
new Entry(0xE167, "Link"),
};
}
}
| |
// 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.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Text.Tests
{
public partial class StringBuilderTests : RemoteExecutorTestBase
{
[Fact]
public static void AppendJoin_NullValues_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (object[])null));
AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (IEnumerable<object>)null));
AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (string[])null));
AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (object[])null));
AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (IEnumerable<object>)null));
AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (string[])null));
}
[Theory]
[InlineData(new object[0], "")]
[InlineData(new object[] { null }, "")]
[InlineData(new object[] { 10 }, "10")]
[InlineData(new object[] { null, null }, "|")]
[InlineData(new object[] { null, 20 }, "|20")]
[InlineData(new object[] { 10, null }, "10|")]
[InlineData(new object[] { 10, 20 }, "10|20")]
[InlineData(new object[] { null, null, null }, "||")]
[InlineData(new object[] { null, null, 30 }, "||30")]
[InlineData(new object[] { null, 20, null }, "|20|")]
[InlineData(new object[] { null, 20, 30 }, "|20|30")]
[InlineData(new object[] { 10, null, null }, "10||")]
[InlineData(new object[] { 10, null, 30 }, "10||30")]
[InlineData(new object[] { 10, 20, null }, "10|20|")]
[InlineData(new object[] { 10, 20, 30 }, "10|20|30")]
[InlineData(new object[] { "" }, "")]
[InlineData(new object[] { "", "" }, "|")]
public static void AppendJoin_TestValues(object[] values, string expected)
{
var stringValues = Array.ConvertAll(values, _ => _?.ToString());
var enumerable = values.Select(_ => _);
Assert.Equal(expected, new StringBuilder().AppendJoin('|', values).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin('|', enumerable).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin('|', stringValues).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin("|", values).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin("|", enumerable).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin("|", stringValues).ToString());
}
[Fact]
public static void AppendJoin_NullToStringValues()
{
AppendJoin_TestValues(new object[] { new NullToStringObject() }, "");
AppendJoin_TestValues(new object[] { new NullToStringObject(), new NullToStringObject() }, "|");
}
private sealed class NullToStringObject
{
public override string ToString() => null;
}
[Theory]
[InlineData(null, "123")]
[InlineData("", "123")]
[InlineData(" ", "1 2 3")]
[InlineData(", ", "1, 2, 3")]
public static void AppendJoin_TestStringSeparators(string separator, string expected)
{
Assert.Equal(expected, new StringBuilder().AppendJoin(separator, new object[] { 1, 2, 3 }).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin(separator, Enumerable.Range(1, 3)).ToString());
Assert.Equal(expected, new StringBuilder().AppendJoin(separator, new string[] { "1", "2", "3" }).ToString());
}
private static StringBuilder CreateBuilderWithNoSpareCapacity()
{
return new StringBuilder(0, 5).Append("Hello");
}
[Theory]
[InlineData(null, new object[] { null, null })]
[InlineData("", new object[] { "", "" })]
[InlineData(" ", new object[] { })]
[InlineData(", ", new object[] { "" })]
public static void AppendJoin_NoValues_NoSpareCapacity_DoesNotThrow(string separator, object[] values)
{
var stringValues = Array.ConvertAll(values, _ => _?.ToString());
var enumerable = values.Select(_ => _);
if (separator?.Length == 1)
{
CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], values);
CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], enumerable);
CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], stringValues);
}
CreateBuilderWithNoSpareCapacity().AppendJoin(separator, values);
CreateBuilderWithNoSpareCapacity().AppendJoin(separator, enumerable);
CreateBuilderWithNoSpareCapacity().AppendJoin(separator, stringValues);
}
[Theory]
[InlineData(null, new object[] { " " })]
[InlineData(" ", new object[] { " " })]
[InlineData(" ", new object[] { null, null })]
[InlineData(" ", new object[] { "", "" })]
public static void AppendJoin_NoSpareCapacity_ThrowsArgumentOutOfRangeException(string separator, object[] values)
{
var builder = new StringBuilder(0, 5);
builder.Append("Hello");
var stringValues = Array.ConvertAll(values, _ => _?.ToString());
var enumerable = values.Select(_ => _);
if (separator?.Length == 1)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], values));
AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], enumerable));
AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], stringValues));
}
AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, values));
AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, enumerable));
AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, stringValues));
}
[Theory]
[InlineData("Hello", new char[] { 'a' }, "Helloa")]
[InlineData("Hello", new char[] { 'b', 'c', 'd' }, "Hellobcd")]
[InlineData("Hello", new char[] { 'b', '\0', 'd' }, "Hellob\0d")]
[InlineData("", new char[] { 'e', 'f', 'g' }, "efg")]
[InlineData("Hello", new char[0], "Hello")]
public static void Append_CharSpan(string original, char[] value, string expected)
{
var builder = new StringBuilder(original);
builder.Append(new ReadOnlySpan<char>(value));
Assert.Equal(expected, builder.ToString());
}
[Theory]
[InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0', '\0' }, 5, new char[] { 'H', 'e', 'l', 'l', 'o' })]
[InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0' }, 4, new char[] { 'H', 'e', 'l', 'l' })]
[InlineData("Hello", 1, new char[] { '\0', '\0', '\0', '\0', '\0' }, 4, new char[] { 'e', 'l', 'l', 'o', '\0' })]
public static void CopyTo_CharSpan(string value, int sourceIndex, char[] destination, int count, char[] expected)
{
var builder = new StringBuilder(value);
builder.CopyTo(sourceIndex, new Span<char>(destination), count);
Assert.Equal(expected, destination);
}
[Fact]
public static void CopyTo_CharSpan_StringBuilderWithMultipleChunks()
{
StringBuilder builder = StringBuilderWithMultipleChunks();
char[] destination = new char[builder.Length];
builder.CopyTo(0, new Span<char>(destination), destination.Length);
Assert.Equal(s_chunkSplitSource.ToCharArray(), destination);
}
[Fact]
public static void CopyTo_CharSpan_Invalid()
{
var builder = new StringBuilder("Hello");
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(-1, new Span<char>(new char[10]), 0)); // Source index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(6, new Span<char>(new char[10]), 0)); // Source index > builder.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.CopyTo(0, new Span<char>(new char[10]), -1)); // Count < 0
AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(5, new Span<char>(new char[10]), 1)); // Source index + count > builder.Length
AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(4, new Span<char>(new char[10]), 2)); // Source index + count > builder.Length
AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(0, new Span<char>(new char[10]), 11)); // count > destinationArray.Length
}
[Theory]
[InlineData("Hello", 0, new char[] { '\0' }, "\0Hello")]
[InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, "Helabclo")]
[InlineData("Hello", 5, new char[] { 'd', 'e', 'f' }, "Hellodef")]
[InlineData("Hello", 0, new char[0], "Hello")]
public static void Insert_CharSpan(string original, int index, char[] value, string expected)
{
var builder = new StringBuilder(original);
builder.Insert(index, new ReadOnlySpan<char>(value));
Assert.Equal(expected, builder.ToString());
}
[Fact]
public static void Insert_CharSpan_Invalid()
{
var builder = new StringBuilder(0, 5);
builder.Append("Hello");
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, new ReadOnlySpan<char>(new char[0]))); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, new ReadOnlySpan<char>(new char[0]))); // Index > builder.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, new ReadOnlySpan<char>(new char[1]))); // New length > builder.MaxCapacity
}
private static IEnumerable<object[]> Append_StringBuilder_TestData()
{
string mediumString = new string('a', 30);
string largeString = new string('b', 1000);
var sb1 = new StringBuilder("Hello");
var sb2 = new StringBuilder("one");
var sb3 = new StringBuilder(20).Append(mediumString);
yield return new object[] { new StringBuilder("Hello"), sb1, "HelloHello" };
yield return new object[] { new StringBuilder("Hello"), sb2, "Helloone" };
yield return new object[] { new StringBuilder("Hello"), new StringBuilder(), "Hello" };
yield return new object[] { new StringBuilder("one"), sb3, "one" + mediumString };
yield return new object[] { new StringBuilder(20).Append(mediumString), sb3, mediumString + mediumString };
yield return new object[] { new StringBuilder(10).Append(mediumString), sb3, mediumString + mediumString };
yield return new object[] { new StringBuilder(20).Append(largeString), sb3, largeString + mediumString };
yield return new object[] { new StringBuilder(10).Append(largeString), sb3, largeString + mediumString };
yield return new object[] { new StringBuilder(10), sb3, mediumString };
yield return new object[] { new StringBuilder(30), sb3, mediumString };
yield return new object[] { new StringBuilder(10), new StringBuilder(20), string.Empty};
yield return new object[] { sb1, null, "Hello" };
yield return new object[] { sb1, sb1, "HelloHello" };
}
[Theory]
[MemberData(nameof(Append_StringBuilder_TestData))]
public static void Append_StringBuilder(StringBuilder s1, StringBuilder s2, string s)
{
Assert.Equal(s, s1.Append(s2).ToString());
}
private static IEnumerable<object[]> Append_StringBuilder_Substring_TestData()
{
string mediumString = new string('a', 30);
string largeString = new string('b', 1000);
var sb1 = new StringBuilder("Hello");
var sb2 = new StringBuilder("one");
var sb3 = new StringBuilder(20).Append(mediumString);
yield return new object[] { new StringBuilder("Hello"), sb1, 0, 5, "HelloHello" };
yield return new object[] { new StringBuilder("Hello"), sb1, 0, 0, "Hello" };
yield return new object[] { new StringBuilder("Hello"), sb1, 2, 3, "Hellollo" };
yield return new object[] { new StringBuilder("Hello"), sb1, 2, 2, "Helloll" };
yield return new object[] { new StringBuilder("Hello"), sb1, 2, 0, "Hello" };
yield return new object[] { new StringBuilder("Hello"), new StringBuilder(), 0, 0, "Hello" };
yield return new object[] { new StringBuilder("Hello"), null, 0, 0, "Hello" };
yield return new object[] { new StringBuilder(), new StringBuilder("Hello"), 2, 3, "llo" };
yield return new object[] { new StringBuilder("Hello"), sb2, 0, 3, "Helloone" };
yield return new object[] { new StringBuilder("one"), sb3, 5, 25, "one" + new string('a', 25) };
yield return new object[] { new StringBuilder("one"), sb3, 5, 20, "one" + new string('a', 20) };
yield return new object[] { new StringBuilder("one"), sb3, 10, 10, "one" + new string('a', 10) };
yield return new object[] { new StringBuilder(20).Append(mediumString), sb3, 20, 10, new string('a', 40) };
yield return new object[] { new StringBuilder(10).Append(mediumString), sb3, 10, 10, new string('a', 40) };
yield return new object[] { new StringBuilder(20).Append(largeString), new StringBuilder(20).Append(largeString), 100, 50, largeString + new string('b', 50) };
yield return new object[] { new StringBuilder(10).Append(mediumString), new StringBuilder(20).Append(largeString), 20, 10, mediumString + new string('b', 10) };
yield return new object[] { new StringBuilder(10).Append(mediumString), new StringBuilder(20).Append(largeString), 100, 50, mediumString + new string('b', 50) };
yield return new object[] { sb1, sb1, 2, 3, "Hellollo" };
yield return new object[] { sb2, sb2, 2, 0, "one" };
}
[Theory]
[MemberData(nameof(Append_StringBuilder_Substring_TestData))]
public static void Append_StringBuilder_Substring(StringBuilder s1, StringBuilder s2, int startIndex, int count, string s)
{
Assert.Equal(s, s1.Append(s2, startIndex, count).ToString());
}
[Fact]
public static void Append_StringBuilder_InvalidInput()
{
StringBuilder sb = new StringBuilder(5, 5).Append("Hello");
Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, 4, 5));
Assert.Throws<ArgumentNullException>(() => sb.Append( (StringBuilder)null, 2, 2));
Assert.Throws<ArgumentNullException>(() => sb.Append((StringBuilder)null, 2, 3));
Assert.Throws<ArgumentOutOfRangeException>(() => new StringBuilder(3, 6).Append("Hello").Append(sb));
Assert.Throws<ArgumentOutOfRangeException>(() => new StringBuilder(3, 6).Append("Hello").Append("Hello"));
Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb));
}
public static IEnumerable<object[]> Equals_String_TestData()
{
string mediumString = new string('a', 30);
string largeString = new string('a', 1000);
string extraLargeString = new string('a', 41000); // 8000 is the maximum chunk size
var sb1 = new StringBuilder("Hello");
var sb2 = new StringBuilder(20).Append(mediumString);
var sb3 = new StringBuilder(20).Append(largeString);
var sb4 = new StringBuilder(20).Append(extraLargeString);
yield return new object[] { sb1, "Hello", true };
yield return new object[] { sb1, "Hel", false };
yield return new object[] { sb1, "Hellz", false };
yield return new object[] { sb1, "Helloz", false };
yield return new object[] { sb1, "", false };
yield return new object[] { new StringBuilder(), "", true };
yield return new object[] { new StringBuilder(), "Hello", false };
yield return new object[] { sb2, mediumString, true };
yield return new object[] { sb2, "H", false };
yield return new object[] { sb3, largeString, true };
yield return new object[] { sb3, "H", false };
yield return new object[] { sb3, new string('a', 999) + 'b', false };
yield return new object[] { sb4, extraLargeString, true };
yield return new object[] { sb4, "H", false };
}
[Theory]
[MemberData(nameof(Equals_String_TestData))]
public static void Equals(StringBuilder sb1, string value, bool expected)
{
Assert.Equal(expected, sb1.Equals(value.AsSpan()));
}
}
}
| |
/************************************************************************************
Filename : OSPManager.cs
Content : Interface into the Oculus Spatializer Plugin
Created : Novemnber 4, 2014
Authors : Peter Giokaris
Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 UnityEngine;
using System;
using System.Runtime.InteropServices;
//-------------------------------------------------------------------------------------
// ***** OSPManager
//
/// <summary>
/// OSPManager interfaces into the Oculus Spatializer. This component should be added
/// into the scene once.
///
/// </summary>
public class OSPManager : MonoBehaviour
{
public const string strOSP = "OculusSpatializerPlugin";
// * * * * * * * * * * * * *
// RoomModel - Used to enable and define simple box room for early reflections
[StructLayout(LayoutKind.Sequential)]
public struct RoomModel
{
public bool Enable;
public int ReflectionOrder;
public float DimensionX;
public float DimensionY;
public float DimensionZ;
public float Reflection_K0;
public float Reflection_K1;
public float Reflection_K2;
public float Reflection_K3;
public float Reflection_K4;
public float Reflection_K5;
public bool ReverbOn;
}
// * * * * * * * * * * * * *
// Import functions
[DllImport(strOSP)]
private static extern bool OSP_Init(int sample_rate, int buffer_size);
[DllImport(strOSP)]
private static extern bool OSP_Exit();
[DllImport(strOSP)]
private static extern bool OSP_UpdateRoomModel(ref RoomModel rm);
[DllImport(strOSP)]
private static extern void OSP_SetReflectionsRangeMax(float range);
[DllImport(strOSP)]
private static extern int OSP_AquireContext();
[DllImport(strOSP)]
private static extern void OSP_ReturnContext(int context);
[DllImport(strOSP)]
private static extern bool OSP_GetBypass();
[DllImport(strOSP)]
private static extern void OSP_SetBypass(bool bypass);
[DllImport(strOSP)]
private static extern bool OSP_GetUseSimple();
[DllImport(strOSP)]
private static extern void OSP_SetUseSimple(bool useSimple);
[DllImport(strOSP)]
private static extern void OSP_SetGlobalScale(float globalScale);
[DllImport(strOSP)]
private static extern void OSP_SetGain(float gain);
[DllImport(strOSP)]
private static extern void OSP_SetFrequencyHint(int context, int hint);
[DllImport(strOSP)]
private static extern float OSP_GetDrainTime(int context);
[DllImport(strOSP)]
private static extern void OSP_SetPositonRelXYZ(int context, float x, float y, float z);
[DllImport(strOSP)]
private static extern void OSP_Spatialize(int context, float[] ioBuf);
// * * * * * * * * * * * * *
// Public members
private int bufferSize = 512; // Do not expose at this time
public int BufferSize
{
get{return bufferSize; }
set{bufferSize = value;}
}
private int sampleRate = 48000; // Do not expose at this time
public int SampleRate
{
get{return sampleRate; }
set{sampleRate = value;}
}
[SerializeField]
private bool bypass = false;
public bool Bypass
{
get{return OSP_GetBypass(); }
set{bypass = value;
OSP_SetBypass(bypass);}
}
[SerializeField]
private bool useSimple = false;
public bool UseSimple
{
get{ return useSimple; }
set{useSimple = value;
OSP_SetUseSimple(useSimple);}
}
[SerializeField]
private float globalScale = 1.0f;
public float GlobalScale
{
get{return globalScale; }
set{globalScale = Mathf.Clamp (value, 0.00001f, 10000.0f);
OSP_SetGlobalScale(globalScale);}
}
[SerializeField]
private float gain = 0.0f;
public float Gain
{
get{return gain; }
set{gain = Mathf.Clamp(value, -24.0f, 24.0f);
OSP_SetGain(gain);}
}
//----------------------
// Reflection parameters
private bool dirtyReflection;
[SerializeField]
private bool enableReflections = false;
public bool EnableReflections
{
get{return enableReflections; }
set{enableReflections = value; dirtyReflection = true;}
}
[SerializeField]
private bool enableReverb = false;
public bool EnableReverb
{
get{return enableReverb; }
set{enableReverb = value; dirtyReflection = true;}
}
[SerializeField]
private Vector3 dimensions = new Vector3 (0.0f, 0.0f, 0.0f);
public Vector3 Dimensions
{
get{return dimensions; }
set{dimensions = value;
dimensions.x = Mathf.Clamp (dimensions.x, 1.0f, 200.0f);
dimensions.y = Mathf.Clamp (dimensions.y, 1.0f, 200.0f);
dimensions.z = Mathf.Clamp (dimensions.z, 1.0f, 200.0f);
dirtyReflection = true;}
}
[SerializeField]
private Vector2 rK01 = new Vector2(0.0f, 0.0f);
public Vector2 RK01
{
get{return rK01; }
set{rK01 = value;
rK01.x = Mathf.Clamp (rK01.x, 0.0f, 0.97f);
rK01.y = Mathf.Clamp (rK01.y, 0.0f, 0.97f);
dirtyReflection = true;}
}
[SerializeField]
private Vector2 rK23 = new Vector2(0.0f, 0.0f);
public Vector2 RK23
{
get{return rK23; }
set{rK23 = value;
rK23.x = Mathf.Clamp (rK23.x, 0.0f, 0.95f);
rK23.y = Mathf.Clamp (rK23.y, 0.0f, 0.95f);
dirtyReflection = true;}
}
[SerializeField]
private Vector2 rK45 = new Vector2(0.0f, 0.0f);
public Vector2 RK45
{
get{return rK45; }
set{rK45 = value;
rK45.x = Mathf.Clamp (rK45.x, 0.0f, 0.95f);
rK45.y = Mathf.Clamp (rK45.y, 0.0f, 0.95f);
dirtyReflection = true;}
}
// reflection range max does not need to have a dirty update
[SerializeField]
private float reflRangeMax = 10000.0f;
public float ReflRangeMax
{
get{return reflRangeMax; }
set{reflRangeMax = Mathf.Clamp(value, 100.0f, 100000.0f);
OSP_SetReflectionsRangeMax(reflRangeMax);}
}
// * * * * * * * * * * * * *
// Private members
// * * * * * * * * * * * * *
// Static members
private static bool sOSPInit = false;
// * * * * * * * * * * * * *
// MonoBehaviour overrides
/// <summary>
/// Awake this instance.
/// </summary>
void Awake ()
{
int samplerate;
int bufsize;
int numbuf;
#if (!UNITY_5_0)
// Used to override samplerate and buffer size with optimal values
bool setvalues = true;
// OSX is picky with samplerate and buffer sizes, so leave it alone
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
setvalues = false;
#endif
#endif
// Get the current sample rate
samplerate = AudioSettings.outputSampleRate;
// Get the current buffer size and number of buffers
AudioSettings.GetDSPBufferSize (out bufsize, out numbuf);
Debug.LogWarning (System.String.Format ("OSP: Queried SampleRate: {0:F0} BufferSize: {1:F0}", samplerate, bufsize));
#if (UNITY_ANDROID && !UNITY_EDITOR)
if((samplerate == 48000) && (bufsize == 960))
{
Debug.LogWarning("OSP: Native OpenSL ENABLED");
#if (!UNITY_5_0)
setvalues = false;
#endif
}
else
{
Debug.LogWarning("OSP: Native OpenSL DISABLED");
}
#endif
// We will only set values IF we are not Unity 5 (the ability to set DSP settings does not exist)
// NOTE: Unity 4 does not switch DSP buffer sizes using ProjectSettings->Audio, but Unity 5 does.
// At some point along Unity 5 maturity, the functionality to set DSP values directly might be removed.
#if (!UNITY_5_0)
if(setvalues == true)
{
// NOTE: When setting DSP values in Unity 4, there may be a situation where using PlayOnAwake on
// non-spatitalized audio objects will fail to play.
// Uncomment this code for achieving the best possibly latency with spatialized audio, but
// USE AT YOUR OWN RISK!
/*
// Set the ideal sample rate
AudioSettings.outputSampleRate = SampleRate;
// Get the sample rate again (it may not take, depending on platform)
samplerate = AudioSettings.outputSampleRate;
// Set the ideal buffer size
AudioSettings.SetDSPBufferSize (BufferSize, numbuf);
// Get the current buffer size and number of buffers again
AudioSettings.GetDSPBufferSize (out bufsize, out numbuf);
*/
}
#endif
Debug.LogWarning (System.String.Format ("OSP: sample rate: {0:F0}", samplerate));
Debug.LogWarning (System.String.Format ("OSP: buffer size: {0:F0}", bufsize));
Debug.LogWarning (System.String.Format ("OSP: num buffers: {0:F0}", numbuf));
sOSPInit = OSP_Init(samplerate, bufsize);
// Set global variables not set to dirty updates
OSP_SetBypass (bypass);
OSP_SetUseSimple (useSimple);
OSP_SetGlobalScale (globalScale);
OSP_SetGain (gain);
OSP_SetReflectionsRangeMax(reflRangeMax);
// Update reflections for the first time
dirtyReflection = true;
}
/// <summary>
/// Start this instance.
/// Note: make sure to always have a Start function for classes that have editor scripts.
/// </summary>
void Start()
{
}
/// <summary>
/// Run processes that need to be updated in our game thread
/// </summary>
void Update()
{
// Update reflections
if (dirtyReflection == true)
{
UpdateEarlyReflections();
dirtyReflection = false;
}
}
/// <summary>
/// Raises the destroy event.
/// </summary>
void OnDestroy()
{
sOSPInit = false;
// PGG Do not call, faster (but stuck with initial buffer resolution)
//OSP_Exit();
}
// * * * * * * * * * * * * *
// Public Functions
/// <summary>
/// Inited - Check to see if system has been initialized
/// </summary>
/// <returns><c>true</c> if is initialized; otherwise, <c>false</c>.</returns>
public static bool IsInitialized()
{
return sOSPInit;
}
/// <summary>
/// Gets a spatializer context for a sound.
/// </summary>
/// <returns>The context.</returns>
public static int AquireContext ()
{
return OSP_AquireContext();
}
/// <summary>
/// Releases the context for a sound.
/// </summary>
/// <param name="context">Context.</param>
public static void ReleaseContext(int context)
{
// Drop back into OSP
OSP_ReturnContext (context);
}
/// <summary>
/// Gets the bypass. Used by OSPAudioSource (cannot be written to; used for
/// getting global bypass state).
/// </summary>
/// <returns><c>true</c>, if bypass was gotten, <c>false</c> otherwise.</returns>
public static bool GetBypass()
{
return OSP_GetBypass ();
}
/// <summary>
/// Gets the sinple override.
/// </summary>
/// <returns><c>true</c>, if fast override was used, <c>false</c> otherwise.</returns>
/// <param name="useSimple">If set to <c>true</c> use simple.</param>
public static bool GetUseSimple()
{
return OSP_GetUseSimple();
}
/// <summary>
/// Sets the use simple.
/// </summary>
/// <returns><c>true</c>, if use simple was gotten, <c>false</c> otherwise.</returns>
public static void SetUseSimple(bool use)
{
OSP_SetUseSimple(use);
}
/// <summary>
/// Sets the frequency hint.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="hint">Hint.</param>
public static void SetFrequencyHint(int context, int hint)
{
OSP_SetFrequencyHint (context, hint);
}
/// <summary>
/// Gets the drain time, based on reflection room size.
/// </summary>
/// <returns>The drain time.</returns>
public static float GetDrainTime(int context)
{
return OSP_GetDrainTime (context);
}
/// <summary>
/// Sets the position of the sound relative to the listener.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <param name="z">The z coordinate.</param>
public static void SetPositionRel(int context, float x, float y, float z)
{
if (sOSPInit == false) return;
OSP_SetPositonRelXYZ (context, x, y, z);
}
/// <summary>
/// Spatialize the specified ioBuf using context.
/// </summary>
/// <param name="ioBuf">Io buffer.</param>
/// <param name="context">Context.</param>
public static void Spatialize (int context, float[] ioBuf)
{
if (sOSPInit == false) return;
OSP_Spatialize (context, ioBuf);
}
// * * * * * * * * * * * * *
// Private Functions
/// <summary>
/// Updates the early reflections.
/// </summary>
void UpdateEarlyReflections()
{
RoomModel rm;
rm.Enable = enableReflections;
rm.ReverbOn = enableReverb;
rm.ReflectionOrder = 0; // Unused
rm.DimensionX = dimensions.x;
rm.DimensionY = dimensions.y;
rm.DimensionZ = dimensions.z;
rm.Reflection_K0 = rK01.x;
rm.Reflection_K1 = rK01.y;
rm.Reflection_K2 = rK23.x;
rm.Reflection_K3 = rK23.y;
rm.Reflection_K4 = rK45.x;
rm.Reflection_K5 = rK45.y;
OSP_UpdateRoomModel (ref rm);
}
}
| |
// 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.Globalization;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class EnumWithFlagsAttributeTests
{
private static string GetCSharpCode_EnumWithFlagsAttributes(string code, bool hasFlags)
{
string stringToReplace = hasFlags ? "[System.Flags]" : "";
return string.Format(CultureInfo.CurrentCulture, code, stringToReplace);
}
private static string GetBasicCode_EnumWithFlagsAttributes(string code, bool hasFlags)
{
string stringToReplace = hasFlags ? "<System.Flags>" : "";
return string.Format(CultureInfo.CurrentCulture, code, stringToReplace);
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_SimpleCase()
{
var code = @"{0}
public enum SimpleFlagsEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4
}}
{0}
public enum HexFlagsEnumClass
{{
One = 0x1,
Two = 0x2,
Four = 0x4,
All = 0x7
}}";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027CSharpResultAt(2, 13, "SimpleFlagsEnumClass"),
GetCA1027CSharpResultAt(11, 13, "HexFlagsEnumClass"));
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CSharp_EnumWithFlagsAttributes_SimpleCase_Internal()
{
var code = @"{0}
internal enum SimpleFlagsEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4
}}
internal class OuterClass
{{
{0}
public enum HexFlagsEnumClass
{{
One = 0x1,
Two = 0x2,
Four = 0x4,
All = 0x7
}}
}}";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_SimpleCaseWithScope()
{
var code = @"{0}
public enum {{|CA1027:SimpleFlagsEnumClass|}}
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4
}}
{0}
public enum HexFlagsEnumClass
{{
One = 0x1,
Two = 0x2,
Four = 0x4,
All = 0x7
}}";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027CSharpResultAt(11, 13, "HexFlagsEnumClass"));
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_SimpleCase()
{
var code = @"{0}
Public Enum SimpleFlagsEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
End Enum
{0}
Public Enum HexFlagsEnumClass
One = &H1
Two = &H2
Four = &H4
All = &H7
End Enum";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027BasicResultAt(2, 13, "SimpleFlagsEnumClass"),
GetCA1027BasicResultAt(10, 13, "HexFlagsEnumClass"));
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task VisualBasic_EnumWithFlagsAttributes_SimpleCase_Internal()
{
var code = @"{0}
Friend Enum SimpleFlagsEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
End Enum
Friend Class OuterClass
{0}
Public Enum HexFlagsEnumClass
One = &H1
Two = &H2
Four = &H4
All = &H7
End Enum
End Class";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_SimpleCaseWithScope()
{
var code = @"{0}
Public Enum {{|CA1027:SimpleFlagsEnumClass|}}
Zero = 0
One = 1
Two = 2
Four = 4
End Enum
{0}
Public Enum HexFlagsEnumClass
One = &H1
Two = &H2
Four = &H4
All = &H7
End Enum";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027BasicResultAt(10, 13, "HexFlagsEnumClass"));
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_DuplicateValues()
{
string code = @"{0}
public enum DuplicateValuesEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
AnotherFour = 4,
ThreePlusOne = Two + One + One
}}
";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027CSharpResultAt(2, 13, "DuplicateValuesEnumClass"));
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_DuplicateValues()
{
string code = @"{0}
Public Enum DuplicateValuesEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
AnotherFour = 4
ThreePlusOne = Two + One + One
End Enum
";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027BasicResultAt(2, 13, "DuplicateValuesEnumClass"));
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_MissingPowerOfTwo()
{
string code = @"
{0}
public enum MissingPowerOfTwoEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
Sixteen = 16
}}
{0}
public enum MultipleMissingPowerOfTwoEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
ThirtyTwo = 32
}}";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027CSharpResultAt(3, 13, "MissingPowerOfTwoEnumClass"),
GetCA1027CSharpResultAt(13, 13, "MultipleMissingPowerOfTwoEnumClass"));
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_IncorrectNumbers()
{
string code = @"
{0}
public enum AnotherTestValue
{{
Value1 = 0,
Value2 = 1,
Value3 = 1,
Value4 = 3
}}";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags,
GetCA2217CSharpResultAt(3, 13, "AnotherTestValue", "2"));
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_MissingPowerOfTwo()
{
string code = @"
{0}
Public Enum MissingPowerOfTwoEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
Sixteen = 16
End Enum
{0}
Public Enum MultipleMissingPowerOfTwoEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
ThirtyTwo = 32
End Enum
";
// Verify CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags,
GetCA1027BasicResultAt(3, 13, "MissingPowerOfTwoEnumClass"),
GetCA1027BasicResultAt(12, 13, "MultipleMissingPowerOfTwoEnumClass"));
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_IncorrectNumbers()
{
string code = @"
{0}
Public Enum AnotherTestValue
Value1 = 0
Value2 = 1
Value3 = 1
Value4 = 3
End Enum
";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags,
GetCA2217BasicResultAt(3, 13, "AnotherTestValue", "2"));
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_ContiguousValues()
{
var code = @"
{0}
public enum ContiguousEnumClass
{{
Zero = 0,
One = 1,
Two = 2
}}
{0}
public enum ContiguousEnumClass2
{{
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5
}}
{0}
public enum ValuesNotDeclaredEnumClass
{{
Zero,
One,
Two,
Three,
Four,
Five
}}
{0}
public enum ShortUnderlyingType: short
{{
Zero = 0,
One,
Two,
Three,
Four,
Five
}}";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_ContiguousValues()
{
var code = @"
{0}
Public Enum ContiguousEnumClass
Zero = 0
One = 1
Two = 2
End Enum
{0}
Public Enum ContiguousEnumClass2
Zero = 0
One = 1
Two = 2
Three = 3
Four = 4
Five = 5
End Enum
{0}
Public Enum ValuesNotDeclaredEnumClass
Zero
One
Two
Three
Four
Five
End Enum
{0}
Public Enum ShortUnderlyingType As Short
Zero = 0
One
Two
Three
Four
Five
End Enum
";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify no CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags);
}
[Fact]
public async Task CSharp_EnumWithFlagsAttributes_NonSimpleFlags()
{
var code = @"
{0}
public enum NonSimpleFlagEnumClass
{{
Zero = 0x0, // 0000
One = 0x1, // 0001
Two = 0x2, // 0010
Eight = 0x8, // 1000
Twelve = 0xC, // 1100
HighValue = -1 // will be cast to UInt32.MaxValue, then zero-extended to UInt64
}}
{0}
public enum BitValuesClass
{{
None = 0x0,
One = 0x1, // 0001
Two = 0x2, // 0010
Eight = 0x8, // 1000
Twelve = 0xC, // 1100
}}
{0}
public enum LabelsClass
{{
None = 0,
One = 1,
Four = 4,
Six = 6,
Seven = 7
}}";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyCS.VerifyAnalyzerAsync(codeWithFlags,
GetCA2217CSharpResultAt(3, 13, "NonSimpleFlagEnumClass", "4, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296, 8589934592, 17179869184, 34359738368, 68719476736, 137438953472, 274877906944, 549755813888, 1099511627776, 2199023255552, 4398046511104, 8796093022208, 17592186044416, 35184372088832, 70368744177664, 140737488355328, 281474976710656, 562949953421312, 1125899906842624, 2251799813685248, 4503599627370496, 9007199254740992, 18014398509481984, 36028797018963968, 72057594037927936, 144115188075855872, 288230376151711744, 576460752303423488, 1152921504606846976, 2305843009213693952, 4611686018427387904, 9223372036854775808"),
GetCA2217CSharpResultAt(14, 13, "BitValuesClass", "4"),
GetCA2217CSharpResultAt(24, 13, "LabelsClass", "2"));
}
[Fact]
public async Task VisualBasic_EnumWithFlagsAttributes_NonSimpleFlags()
{
var code = @"
{0}
Public Enum NonSimpleFlagEnumClass
Zero = &H0 ' 0000
One = &H1 ' 0001
Two = &H2 ' 0010
Eight = &H8 ' 1000
Twelve = &Hc ' 1100
HighValue = -1 ' will be cast to UInt32.MaxValue, then zero-extended to UInt64
End Enum
{0}
Public Enum BitValuesClass
None = &H0
One = &H1 ' 0001
Two = &H2 ' 0010
Eight = &H8 ' 1000
Twelve = &Hc ' 1100
End Enum
{0}
Public Enum LabelsClass
None = 0
One = 1
Four = 4
Six = 6
Seven = 7
End Enum
";
// Verify no CA1027: Mark enums with FlagsAttribute
string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags);
// Verify CA2217: Do not mark enums with FlagsAttribute
string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
await VerifyVB.VerifyAnalyzerAsync(codeWithFlags,
GetCA2217BasicResultAt(3, 13, "NonSimpleFlagEnumClass", "4, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296, 8589934592, 17179869184, 34359738368, 68719476736, 137438953472, 274877906944, 549755813888, 1099511627776, 2199023255552, 4398046511104, 8796093022208, 17592186044416, 35184372088832, 70368744177664, 140737488355328, 281474976710656, 562949953421312, 1125899906842624, 2251799813685248, 4503599627370496, 9007199254740992, 18014398509481984, 36028797018963968, 72057594037927936, 144115188075855872, 288230376151711744, 576460752303423488, 1152921504606846976, 2305843009213693952, 4611686018427387904, 9223372036854775808"),
GetCA2217BasicResultAt(13, 13, "BitValuesClass", "4"),
GetCA2217BasicResultAt(22, 13, "LabelsClass", "2"));
}
private static DiagnosticResult GetCA1027CSharpResultAt(int line, int column, string enumTypeName)
=> VerifyCS.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule1027)
.WithLocation(line, column)
.WithArguments(enumTypeName);
private static DiagnosticResult GetCA1027BasicResultAt(int line, int column, string enumTypeName)
=> VerifyVB.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule1027)
.WithLocation(line, column)
.WithArguments(enumTypeName);
private static DiagnosticResult GetCA2217CSharpResultAt(int line, int column, string enumTypeName, string missingValuesString)
=> VerifyCS.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule2217)
.WithLocation(line, column)
.WithArguments(enumTypeName, missingValuesString);
private static DiagnosticResult GetCA2217BasicResultAt(int line, int column, string enumTypeName, string missingValuesString)
=> VerifyVB.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule2217)
.WithLocation(line, column)
.WithArguments(enumTypeName, missingValuesString);
}
}
| |
#if !(NET20 || NET35)
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <param name="hDev">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.
/// To retrieve a device handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which
/// to perform it.
/// </param>
/// <param name="inputBuffer">The input buffer required to perform the operation. Can be null if unnecessary.</param>
/// <param name="outputBuffer">The output buffer that is to receive the data returned by the operation. Can be null if unnecessary.</param>
/// <returns>An asynchronous empty result.</returns>
/// <remarks>
/// <para>
/// To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the
/// driver associated with a device. To specify a device name, use the following format:
/// </para>
/// <para>\\.\DeviceName</para>
/// <para>
/// DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive
/// A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to
/// open handles to the physical drives on a system.
/// </para>
/// <para>
/// You should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when calling CreateFile to open a handle to a device
/// driver. However, when you open a communications resource, such as a serial port, you must specify exclusive access. Use the other
/// CreateFile parameters as follows when opening a device handle:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The fdwCreate parameter must specify OPEN_EXISTING.</description>
/// </item>
/// <item>
/// <description>The hTemplateFile parameter must be NULL.</description>
/// </item>
/// <item>
/// <description>
/// The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped
/// (asynchronous) I/O operations.
/// </description>
/// </item>
/// </list>
/// </remarks>
public static async Task DeviceIoControlAsync(HFILE hDev, uint ioControlCode, byte[] inputBuffer, byte[] outputBuffer)
{
var buf = Pack(inputBuffer, outputBuffer);
var outputBytes = await Task.Factory.FromAsync(BeginDeviceIoControl, EndDeviceIoControl, hDev, ioControlCode, buf, null);
outputBytes.CopyTo(outputBuffer, 0);
}
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <typeparam name="TIn">The type of the <paramref name="inVal"/>.</typeparam>
/// <param name="hDev">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.
/// To retrieve a device handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which
/// to perform it.
/// </param>
/// <param name="inVal">
/// The input value required to perform the operation. The type of this data depends on the value of the <paramref
/// name="ioControlCode"/> parameter.
/// </param>
/// <returns>An asynchronous empty result.</returns>
/// <remarks>
/// <para>
/// To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the
/// driver associated with a device. To specify a device name, use the following format:
/// </para>
/// <para>\\.\DeviceName</para>
/// <para>
/// DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive
/// A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to
/// open handles to the physical drives on a system.
/// </para>
/// <para>
/// You should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when calling CreateFile to open a handle to a device
/// driver. However, when you open a communications resource, such as a serial port, you must specify exclusive access. Use the other
/// CreateFile parameters as follows when opening a device handle:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The fdwCreate parameter must specify OPEN_EXISTING.</description>
/// </item>
/// <item>
/// <description>The hTemplateFile parameter must be NULL.</description>
/// </item>
/// <item>
/// <description>
/// The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped
/// (asynchronous) I/O operations.
/// </description>
/// </item>
/// </list>
/// </remarks>
public static Task DeviceIoControlAsync<TIn>(HFILE hDev, uint ioControlCode, TIn inVal) where TIn : struct =>
DeviceIoControlAsync<TIn, int>(hDev, ioControlCode, inVal);
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <typeparam name="TOut">The type of the return value.</typeparam>
/// <param name="hDev">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.
/// To retrieve a device handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which
/// to perform it.
/// </param>
/// <returns>An asynchronous result containing the resulting value of type <typeparamref name="TOut"/>.</returns>
/// <remarks>
/// <para>
/// To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the
/// driver associated with a device. To specify a device name, use the following format:
/// </para>
/// <para>\\.\DeviceName</para>
/// <para>
/// DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive
/// A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to
/// open handles to the physical drives on a system.
/// </para>
/// <para>
/// You should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when calling CreateFile to open a handle to a device
/// driver. However, when you open a communications resource, such as a serial port, you must specify exclusive access. Use the other
/// CreateFile parameters as follows when opening a device handle:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The fdwCreate parameter must specify OPEN_EXISTING.</description>
/// </item>
/// <item>
/// <description>The hTemplateFile parameter must be NULL.</description>
/// </item>
/// <item>
/// <description>
/// The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped
/// (asynchronous) I/O operations.
/// </description>
/// </item>
/// </list>
/// </remarks>
public static Task<TOut?> DeviceIoControlAsync<TOut>(HFILE hDev, uint ioControlCode) where TOut : struct => DeviceIoControlAsync<int, TOut>(hDev, ioControlCode, null);
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <typeparam name="TIn">The type of the <paramref name="inVal"/>.</typeparam>
/// <typeparam name="TOut">The type of the <paramref name="outVal"/>.</typeparam>
/// <param name="hDevice">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.
/// To retrieve a device handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which
/// to perform it.
/// </param>
/// <param name="inVal">
/// The input value required to perform the operation. The type of this data depends on the value of the <paramref
/// name="ioControlCode"/> parameter.
/// </param>
/// <param name="outVal">
/// The output value that is to receive the data returned by the operation. The type of this data depends on the value of the
/// dwIoControlCode parameter.
/// </param>
/// <returns>An asynchronous result containing the populated data supplied by <paramref name="outVal"/>.</returns>
/// <remarks>
/// <para>
/// To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the
/// driver associated with a device. To specify a device name, use the following format:
/// </para>
/// <para>\\.\DeviceName</para>
/// <para>
/// DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive
/// A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to
/// open handles to the physical drives on a system.
/// </para>
/// <para>
/// You should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when calling CreateFile to open a handle to a device
/// driver. However, when you open a communications resource, such as a serial port, you must specify exclusive access. Use the other
/// CreateFile parameters as follows when opening a device handle:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The fdwCreate parameter must specify OPEN_EXISTING.</description>
/// </item>
/// <item>
/// <description>The hTemplateFile parameter must be NULL.</description>
/// </item>
/// <item>
/// <description>
/// The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped
/// (asynchronous) I/O operations.
/// </description>
/// </item>
/// </list>
/// </remarks>
[Obsolete("Use 'Task<TOut?> DeviceIoControlAsync<TIn, TOut>(HFILE hDevice, uint ioControlCode, TIn? inVal)' instead.")]
public static Task<TOut?> DeviceIoControlAsync<TIn, TOut>(HFILE hDevice, uint ioControlCode, TIn? inVal, TOut? outVal) where TIn : struct where TOut : struct =>
new TaskFactory().FromAsync(BeginDeviceIoControl<TIn, TOut>, EndDeviceIoControl<TIn, TOut>, hDevice, ioControlCode, Pack(inVal, outVal), null);
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <typeparam name="TIn">The type of the <paramref name="inVal"/>.</typeparam>
/// <typeparam name="TOut">The type of the return value.</typeparam>
/// <param name="hDevice">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.
/// To retrieve a device handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which
/// to perform it.
/// </param>
/// <param name="inVal">
/// The input value required to perform the operation. The type of this data depends on the value of the <paramref
/// name="ioControlCode"/> parameter.
/// </param>
/// <returns>An asynchronous result containing the populated data supplied by <typeparamref name="TOut"/>.</returns>
/// <remarks>
/// <para>
/// To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the
/// driver associated with a device. To specify a device name, use the following format:
/// </para>
/// <para>\\.\DeviceName</para>
/// <para>
/// DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive
/// A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to
/// open handles to the physical drives on a system.
/// </para>
/// <para>
/// You should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when calling CreateFile to open a handle to a device
/// driver. However, when you open a communications resource, such as a serial port, you must specify exclusive access. Use the other
/// CreateFile parameters as follows when opening a device handle:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The fdwCreate parameter must specify OPEN_EXISTING.</description>
/// </item>
/// <item>
/// <description>The hTemplateFile parameter must be NULL.</description>
/// </item>
/// <item>
/// <description>
/// The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped
/// (asynchronous) I/O operations.
/// </description>
/// </item>
/// </list>
/// </remarks>
public static Task<TOut?> DeviceIoControlAsync<TIn, TOut>(HFILE hDevice, uint ioControlCode, TIn? inVal) where TIn : struct where TOut : struct
{
TOut? outValue = default(TOut);
var buf = Pack(inVal, outValue);
return Task.Factory.FromAsync(BeginDeviceIoControl<TIn, TOut>, EndDeviceIoControl<TIn, TOut>, hDevice, ioControlCode, buf, null);
}
/// <summary>Explicits the device io control asynchronous.</summary>
/// <typeparam name="TIn">The type of the in.</typeparam>
/// <typeparam name="TOut">The type of the out.</typeparam>
/// <param name="hDevice">The h device.</param>
/// <param name="ioControlCode">The io control code.</param>
/// <param name="inVal">The in value.</param>
/// <param name="outVal">The out value.</param>
/// <returns></returns>
/// <exception cref="Win32Exception"></exception>
private static unsafe Task<TOut?> ExplicitDeviceIoControlAsync<TIn, TOut>(HFILE hDevice, uint ioControlCode, TIn? inVal, TOut? outVal) where TIn : struct where TOut : struct
{
#pragma warning disable CS0618 // Type or member is obsolete
ThreadPool.BindHandle((IntPtr)hDevice);
#pragma warning restore CS0618 // Type or member is obsolete
var tcs = new TaskCompletionSource<TOut?>();
var buffer = Pack(inVal, outVal);
var nativeOverlapped = new Overlapped().Pack((code, bytes, overlap) =>
{
try
{
switch (code)
{
case Win32Error.ERROR_SUCCESS:
outVal = Unpack<TIn, TOut>(buffer).Item2;
tcs.TrySetResult(outVal);
break;
case Win32Error.ERROR_OPERATION_ABORTED:
tcs.TrySetCanceled();
break;
default:
tcs.TrySetException(new Win32Exception((int)code));
break;
}
}
finally
{
Overlapped.Unpack(overlap);
Overlapped.Free(overlap);
}
}, buffer);
var unpack = true;
try
{
var inSz = Marshal.SizeOf(typeof(TIn));
fixed (byte* pIn = buffer, pOut = &buffer[inSz])
{
var ret = DeviceIoControl(hDevice, ioControlCode, pIn, (uint)inSz, pOut, (uint)(buffer.Length - inSz), out var bRet,
nativeOverlapped);
if (ret)
{
outVal = Unpack<TIn, TOut>(buffer).Item2;
tcs.SetResult(outVal);
return tcs.Task;
}
}
var lastWin32Error = Marshal.GetLastWin32Error();
if (lastWin32Error != Win32Error.ERROR_IO_PENDING && lastWin32Error != Win32Error.ERROR_SUCCESS)
throw new Win32Exception(lastWin32Error);
unpack = false;
return tcs.Task;
}
finally
{
if (unpack)
{
Overlapped.Unpack(nativeOverlapped);
Overlapped.Free(nativeOverlapped);
}
}
}
}
}
#endif
| |
using J2N.Text;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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 FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// This stores a monotonically increasing set of <c>Term, TermInfo</c> pairs in a
/// Directory. Pairs are accessed either by <see cref="Term"/> or by ordinal position the
/// set.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("(4.0) this class has been replaced by FormatPostingsTermsDictReader, except for reading old segments.")]
internal sealed class TermInfosReader : IDisposable
{
private readonly Directory directory;
private readonly string segment;
private readonly FieldInfos fieldInfos;
#pragma warning disable CA2213 // Disposable fields should be disposed
private readonly DisposableThreadLocal<ThreadResources> threadResources = new DisposableThreadLocal<ThreadResources>();
private readonly SegmentTermEnum origEnum;
#pragma warning restore CA2213 // Disposable fields should be disposed
private readonly long size;
private readonly TermInfosReaderIndex index;
private readonly int indexLength;
private readonly int totalIndexInterval;
private const int DEFAULT_CACHE_SIZE = 1024;
// Just adds term's ord to TermInfo
public sealed class TermInfoAndOrd : TermInfo
{
internal readonly long termOrd;
public TermInfoAndOrd(TermInfo ti, long termOrd)
: base(ti)
{
if (Debugging.AssertsEnabled) Debugging.Assert(termOrd >= 0);
this.termOrd = termOrd;
}
}
private class CloneableTerm : DoubleBarrelLRUCache.CloneableKey
{
internal Term term;
public CloneableTerm(Term t)
{
this.term = t;
}
public override bool Equals(object other)
{
CloneableTerm t = (CloneableTerm)other;
return this.term.Equals(t.term);
}
public override int GetHashCode()
{
return term.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override object Clone()
{
return new CloneableTerm(term);
}
}
private readonly DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd> termsCache = new DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd>(DEFAULT_CACHE_SIZE);
/// <summary>
/// Per-thread resources managed by ThreadLocal.
/// </summary>
private sealed class ThreadResources
{
internal SegmentTermEnum termEnum;
}
internal TermInfosReader(Directory dir, string seg, FieldInfos fis, IOContext context, int indexDivisor)
{
bool success = false;
if (indexDivisor < 1 && indexDivisor != -1)
{
throw new ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try
{
directory = dir;
segment = seg;
fieldInfos = fis;
origEnum = new SegmentTermEnum(directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), context), fieldInfos, false);
size = origEnum.size;
if (indexDivisor != -1)
{
// Load terms index
totalIndexInterval = origEnum.indexInterval * indexDivisor;
string indexFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
SegmentTermEnum indexEnum = new SegmentTermEnum(directory.OpenInput(indexFileName, context), fieldInfos, true);
try
{
index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.FileLength(indexFileName), totalIndexInterval);
indexLength = index.Length;
}
finally
{
indexEnum.Dispose();
}
}
else
{
// Do not load terms index:
totalIndexInterval = -1;
index = null;
indexLength = -1;
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
Dispose();
}
}
}
public int SkipInterval => origEnum.skipInterval;
public int MaxSkipLevels => origEnum.maxSkipLevels;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
IOUtils.Dispose(origEnum, threadResources);
}
/// <summary>
/// Returns the number of term/value pairs in the set.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
internal long Count => size;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ThreadResources GetThreadResources()
{
ThreadResources resources = threadResources.Value;
if (resources == null)
{
resources = new ThreadResources();
resources.termEnum = Terms();
threadResources.Value = resources;
}
return resources;
}
private static readonly IComparer<BytesRef> legacyComparer = BytesRef.UTF8SortedAsUTF16Comparer;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CompareAsUTF16(Term term1, Term term2) // LUCENENET: CA1822: Mark members as static
{
if (term1.Field.Equals(term2.Field, StringComparison.Ordinal))
{
return legacyComparer.Compare(term1.Bytes, term2.Bytes);
}
else
{
return term1.Field.CompareToOrdinal(term2.Field);
}
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal TermInfo Get(Term term)
{
return Get(term, false);
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
private TermInfo Get(Term term, bool mustSeekEnum)
{
if (size == 0)
{
return null;
}
EnsureIndexIsRead();
TermInfoAndOrd tiOrd = termsCache.Get(new CloneableTerm(term));
ThreadResources resources = GetThreadResources();
if (!mustSeekEnum && tiOrd != null)
{
return tiOrd;
}
return SeekEnum(resources.termEnum, term, tiOrd, true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CacheCurrentTerm(SegmentTermEnum enumerator)
{
termsCache.Put(new CloneableTerm(enumerator.Term()), new TermInfoAndOrd(enumerator.termInfo, enumerator.position));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Term DeepCopyOf(Term other)
{
return new Term(other.Field, BytesRef.DeepCopyOf(other.Bytes));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, bool useCache)
{
if (useCache)
{
return SeekEnum(enumerator, term, termsCache.Get(new CloneableTerm(DeepCopyOf(term))), useCache);
}
else
{
return SeekEnum(enumerator, term, null, useCache);
}
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, bool useCache)
{
if (size == 0)
{
return null;
}
// optimize sequential access: first try scanning cached enum w/o seeking
if (enumerator.Term() != null && ((enumerator.Prev() != null && CompareAsUTF16(term, enumerator.Prev()) > 0) || CompareAsUTF16(term, enumerator.Term()) >= 0)) // term is at or past current
{
int enumOffset = (int)(enumerator.position / totalIndexInterval) + 1;
if (indexLength == enumOffset || index.CompareTo(term, enumOffset) < 0) // but before end of block
{
// no need to seek
TermInfo ti;
int numScans = enumerator.ScanTo(term);
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti = enumerator.termInfo;
if (numScans > 1)
{
// we only want to put this TermInfo into the cache if
// scanEnum skipped more than one dictionary entry.
// this prevents RangeQueries or WildcardQueries to
// wipe out the cache when they iterate over a large numbers
// of terms in order
if (tiOrd == null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti, enumerator.position));
}
}
else if (Debugging.AssertsEnabled)
{
Debugging.Assert(SameTermInfo(ti, tiOrd, enumerator));
Debugging.Assert((int)enumerator.position == tiOrd.termOrd);
}
}
}
else
{
ti = null;
}
return ti;
}
}
// random-access: must seek
int indexPos;
if (tiOrd != null)
{
indexPos = (int)(tiOrd.termOrd / totalIndexInterval);
}
else
{
// Must do binary search:
indexPos = index.GetIndexOffset(term);
}
index.SeekEnum(enumerator, indexPos);
enumerator.ScanTo(term);
TermInfo ti_;
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti_ = enumerator.termInfo;
if (tiOrd == null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti_, enumerator.position));
}
}
else if (Debugging.AssertsEnabled)
{
Debugging.Assert(SameTermInfo(ti_, tiOrd, enumerator));
Debugging.Assert(enumerator.position == tiOrd.termOrd);
}
}
else
{
ti_ = null;
}
return ti_;
}
// called only from asserts
private static bool SameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator) // LUCENENET: CA1822: Mark members as static
{
if (ti1.DocFreq != ti2.DocFreq)
{
return false;
}
if (ti1.FreqPointer != ti2.FreqPointer)
{
return false;
}
if (ti1.ProxPointer != ti2.ProxPointer)
{
return false;
}
// skipOffset is only valid when docFreq >= skipInterval:
if (ti1.DocFreq >= enumerator.skipInterval && ti1.SkipOffset != ti2.SkipOffset)
{
return false;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureIndexIsRead()
{
if (index == null)
{
throw IllegalStateException.Create("terms index was not loaded when this reader was created");
}
}
/// <summary>
/// Returns the position of a <see cref="Term"/> in the set or -1. </summary>
internal long GetPosition(Term term)
{
if (size == 0)
{
return -1;
}
EnsureIndexIsRead();
int indexOffset = index.GetIndexOffset(term);
SegmentTermEnum enumerator = GetThreadResources().termEnum;
index.SeekEnum(enumerator, indexOffset);
while (CompareAsUTF16(term, enumerator.Term()) > 0 && enumerator.Next())
{
}
if (CompareAsUTF16(term, enumerator.Term()) == 0)
{
return enumerator.position;
}
else
{
return -1;
}
}
/// <summary>
/// Returns an enumeration of all the <see cref="Term"/>s and <see cref="TermInfo"/>s in the set. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SegmentTermEnum Terms()
{
return (SegmentTermEnum)origEnum.Clone();
}
/// <summary>
/// Returns an enumeration of terms starting at or after the named term. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SegmentTermEnum Terms(Term term)
{
Get(term, true);
return (SegmentTermEnum)GetThreadResources().termEnum.Clone();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal long RamBytesUsed()
{
return index == null ? 0 : index.RamBytesUsed();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LoadImageURLModule")]
public class LoadImageURLModule : ISharedRegionModule, IDynamicTextureRender
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "LoadImageURL";
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
#region IDynamicTextureRender Members
public string GetName()
{
return m_name;
}
public string GetContentType()
{
return ("image");
}
public bool SupportsAsynchronous()
{
return true;
}
// public bool AlwaysIdenticalConversion(string bodyData, string extraParams)
// {
// // We don't support conversion of body data.
// return false;
// }
public IDynamicTexture ConvertUrl(string url, string extraParams)
{
return null;
}
public IDynamicTexture ConvertData(string bodyData, string extraParams)
{
return null;
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
MakeHttpRequest(url, id);
return true;
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
return false;
}
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
m_scene = scene;
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (m_textureManager == null && m_scene == scene)
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private void MakeHttpRequest(string url, UUID requestID)
{
ServicePointManagerTimeoutSupport.ResetHosts();
WebRequest request = HttpWebRequest.Create(url);
if (!string.IsNullOrEmpty(m_proxyurl))
{
if (!string.IsNullOrEmpty(m_proxyexcepts))
{
string[] elist = m_proxyexcepts.Split(';');
request.Proxy = new WebProxy(m_proxyurl, true, elist);
}
else
{
request.Proxy = new WebProxy(m_proxyurl, true);
}
}
RequestState state = new RequestState((HttpWebRequest) request, requestID);
// IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
state.TimeOfRequest = (int) t.TotalSeconds;
}
private void HttpRequestReturn(IAsyncResult result)
{
if (m_textureManager == null)
{
m_log.WarnFormat("[LOADIMAGEURLMODULE]: No texture manager. Can't function.");
return;
}
RequestState state = (RequestState) result.AsyncState;
WebRequest request = (WebRequest) state.Request;
Stream stream = null;
byte[] imageJ2000 = new byte[0];
Size newSize = new Size(0, 0);
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
if (stream != null)
{
try
{
Bitmap image = new Bitmap(stream);
// TODO: make this a bit less hard coded
if ((image.Height < 64) && (image.Width < 64))
{
newSize.Width = 32;
newSize.Height = 32;
}
else if ((image.Height < 128) && (image.Width < 128))
{
newSize.Width = 64;
newSize.Height = 64;
}
else if ((image.Height < 256) && (image.Width < 256))
{
newSize.Width = 128;
newSize.Height = 128;
}
else if ((image.Height < 512 && image.Width < 512))
{
newSize.Width = 256;
newSize.Height = 256;
}
else if ((image.Height < 1024 && image.Width < 1024))
{
newSize.Width = 512;
newSize.Height = 512;
}
else
{
newSize.Width = 1024;
newSize.Height = 1024;
}
using (Bitmap resize = new Bitmap(image, newSize))
{
imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
}
}
catch (Exception)
{
m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed. Empty byte data returned!");
}
}
else
{
m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
}
}
}
catch (WebException)
{
}
finally
{
if (stream != null)
{
stream.Close();
}
}
m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
imageJ2000.Length, state.RequestID);
m_textureManager.ReturnData(
state.RequestID,
new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
request.RequestUri, null, imageJ2000, newSize, false));
}
#region Nested type: RequestState
public class RequestState
{
public HttpWebRequest Request = null;
public UUID RequestID = UUID.Zero;
public int TimeOfRequest = 0;
public RequestState(HttpWebRequest request, UUID requestID)
{
Request = request;
RequestID = requestID;
}
}
#endregion
}
}
| |
// <copyright file="MainWindowForm.Designer.cs" company="Public Domain">
// Released into the public domain
// </copyright>
// This file is part of the C# Finder application. It is free and
// unencumbered software released into the public domain as detailed
// in the UNLICENSE file in the top level directory of this distribution
namespace Finder
{
/// <summary>
/// This class provides the main window form
/// </summary>
public partial class MainWindowForm
{
/// <summary>
/// Required designer variable
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// The main split container which contains the:
/// 1) "Controls" group box
/// 2) The panel that contains the list box that displays the files and the rich text box that displays the instances of the search term text
/// </summary>
private System.Windows.Forms.SplitContainer theMainSplitContainer;
//// "Controls" group box
/// <summary>
/// The group box that contains items related to controls
/// </summary>
private System.Windows.Forms.GroupBox theControlsGroupBox;
/// <summary>
/// The "Select Directory" button
/// </summary>
private System.Windows.Forms.Button theSelectDirectoryButton;
/// <summary>
/// The text box that displays the selected directory
/// </summary>
private System.Windows.Forms.TextBox theSelectedDirectoryTextBox;
/// <summary>
/// The label for the text box in which to enter the search term
/// </summary>
private System.Windows.Forms.Label theSearchTermTextBoxLabel;
/// <summary>
/// The text box in which to enter the search term
/// </summary>
private System.Windows.Forms.TextBox theSearchTermTextBox;
/// <summary>
/// The label for the progress bar that shows progress during the search
/// </summary>
private System.Windows.Forms.Label thePerformSearchProgressBarLabel;
/// <summary>
/// The progress bar that shows progress during the search
/// </summary>
private System.Windows.Forms.ProgressBar thePerformSearchProgressBar;
/// <summary>
/// The "Search" button
/// </summary>
private System.Windows.Forms.Button theSearchButton;
//// "Inclusions" group box
/// <summary>
/// The group box that contains items related to inclusions
/// </summary>
private System.Windows.Forms.GroupBox theInclusionsGroupBox;
/// <summary>
/// The check box that indicates whether to search recursively in the selected directory
/// </summary>
private System.Windows.Forms.CheckBox theSearchRecursivelyCheckBox;
//// "Exclusions" group box
/// <summary>
/// The group box that contains items related to exclusions
/// </summary>
private System.Windows.Forms.GroupBox theExclusionsGroupBox;
/// <summary>
/// The check box that indicates whether to ignore comments while searching
/// </summary>
private System.Windows.Forms.CheckBox theIgnoreCommentsCheckBox;
/// <summary>
/// The check box that indicates whether to be case sensitive while searching
/// </summary>
private System.Windows.Forms.CheckBox theCaseSensitiveCheckBox;
//// "File Types" group box
/// <summary>
/// The group box that contains items related to file types
/// </summary>
private System.Windows.Forms.GroupBox theFileTypeGroupBox;
/// <summary>
/// The check box that indicates whether to include all files while searching
/// </summary>
private System.Windows.Forms.CheckBox theAllCheckBox;
/// <summary>
/// The check box that indicates whether to include C++ source files while searching
/// </summary>
private System.Windows.Forms.CheckBox theCPlusPlusSourceCheckBox;
/// <summary>
/// The check box that indicates whether to include C++/C header files while searching
/// </summary>
private System.Windows.Forms.CheckBox theCPlusPlusCHeaderCheckBox;
/// <summary>
/// The check box that indicates whether to include C source files while searching
/// </summary>
private System.Windows.Forms.CheckBox theCSourceCheckBox;
/// <summary>
/// The check box that indicates whether to include C# files while searching
/// </summary>
private System.Windows.Forms.CheckBox theCSharpCheckBox;
/// <summary>
/// The "Reset" button
/// </summary>
private System.Windows.Forms.Button theResetButton;
/// <summary>
/// The "Exit" button
/// </summary>
private System.Windows.Forms.Button theExitButton;
/// <summary>
/// The panel that contains the:
/// 1) list box that displays the files
/// 2) rich text box that displays the instances of the search term text
/// </summary>
private System.Windows.Forms.Panel theResultsPanel;
/// <summary>
/// The split container which contains the:
/// 1) list box that displays the files
/// 2) rich text box that displays the instances of the search term text
/// </summary>
private System.Windows.Forms.SplitContainer theResultsSplitContainer;
/// <summary>
/// The rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
private System.Windows.Forms.RichTextBox theFoundSearchTermRichTextBox;
/// <summary>
/// The list box that displays the files in which instances of the search term text was found
/// </summary>
private System.Windows.Forms.ListBox theFoundFilesListBox;
/// <summary>
/// The dialog used to select a directory
/// </summary>
private System.Windows.Forms.FolderBrowserDialog theSelectDirectoryFolderBrowserDialog;
//// Properties
/// <summary>
/// Gets the label for the text box in which to enter the search term
/// </summary>
public System.Windows.Forms.Label TheSearchTermTextBoxLabel
{
get
{
return this.theSearchTermTextBoxLabel;
}
}
/// <summary>
/// Gets the text of the text box in which to enter the search term
/// </summary>
public System.Windows.Forms.TextBox TheSearchTermTextBox
{
get
{
return this.theSearchTermTextBox;
}
}
/// <summary>
/// Gets the text of the rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
public System.Windows.Forms.RichTextBox TheFoundSearchTermRichTextBox
{
get
{
return this.theFoundSearchTermRichTextBox;
}
}
/// <summary>
/// Gets the list box that displays the files in which instances of the search term text was found
/// </summary>
public System.Windows.Forms.ListBox TheFoundFilesListBox
{
get
{
return this.theFoundFilesListBox;
}
}
/// <summary>
/// Gets the label for the progress bar that shows progress during the search
/// </summary>
public System.Windows.Forms.Label ThePerformSearchProgressBarLabel
{
get
{
return this.thePerformSearchProgressBarLabel;
}
}
/// <summary>
/// Gets the progress bar that shows progress during the search
/// </summary>
public System.Windows.Forms.ProgressBar ThePerformSearchProgressBar
{
get
{
return this.thePerformSearchProgressBar;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to search recursively in the selected directory is checked
/// </summary>
public bool TheSearchRecursivelyCheckBox
{
get
{
return this.theSearchRecursivelyCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to ignore comments while searching is checked
/// </summary>
public bool TheIgnoreCommentsCheckBox
{
get
{
return this.theIgnoreCommentsCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to be case sensitive while searching is checked
/// </summary>
public bool TheCaseSensitiveCheckBox
{
get
{
return this.theCaseSensitiveCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to include all files while searching is checked
/// </summary>
public bool TheAllCheckBox
{
get
{
return this.theAllCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to include C++ source files while searching is checked
/// </summary>
public bool TheCPlusPlusSourceCheckBox
{
get
{
return this.theCPlusPlusSourceCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to include C++/C header files while searching is checked
/// </summary>
public bool TheCPlusPlusCHeaderCheckBox
{
get
{
return this.theCPlusPlusCHeaderCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to include C source files while searching is checked
/// </summary>
public bool TheCSourceCheckBox
{
get
{
return this.theCSourceCheckBox.Checked;
}
}
/// <summary>
/// Gets a value indicating whether the check box that indicates whether to include C# files while searching is checked
/// </summary>
public bool TheCSharpCheckBox
{
get
{
return this.theCSharpCheckBox.Checked;
}
}
/// <summary>
/// Clean up any resources used by the main window form
/// </summary>
/// <param name="disposing">Boolean flag that indicates whether the method call comes from a Dispose method (its value is true) or from the garbage collector (its value is false)</param>
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.theSearchButton = new System.Windows.Forms.Button();
this.theSearchTermTextBox = new System.Windows.Forms.TextBox();
this.theFoundSearchTermRichTextBox = new System.Windows.Forms.RichTextBox();
this.theCaseSensitiveCheckBox = new System.Windows.Forms.CheckBox();
this.theIgnoreCommentsCheckBox = new System.Windows.Forms.CheckBox();
this.theFoundFilesListBox = new System.Windows.Forms.ListBox();
this.theExitButton = new System.Windows.Forms.Button();
this.theSelectDirectoryButton = new System.Windows.Forms.Button();
this.theSelectedDirectoryTextBox = new System.Windows.Forms.TextBox();
this.theExclusionsGroupBox = new System.Windows.Forms.GroupBox();
this.theFileTypeGroupBox = new System.Windows.Forms.GroupBox();
this.theAllCheckBox = new System.Windows.Forms.CheckBox();
this.theCSharpCheckBox = new System.Windows.Forms.CheckBox();
this.theCSourceCheckBox = new System.Windows.Forms.CheckBox();
this.theCPlusPlusCHeaderCheckBox = new System.Windows.Forms.CheckBox();
this.theCPlusPlusSourceCheckBox = new System.Windows.Forms.CheckBox();
this.theSelectDirectoryFolderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.theResetButton = new System.Windows.Forms.Button();
this.thePerformSearchProgressBar = new System.Windows.Forms.ProgressBar();
this.theInclusionsGroupBox = new System.Windows.Forms.GroupBox();
this.theSearchRecursivelyCheckBox = new System.Windows.Forms.CheckBox();
this.theControlsGroupBox = new System.Windows.Forms.GroupBox();
this.thePerformSearchProgressBarLabel = new System.Windows.Forms.Label();
this.theSearchTermTextBoxLabel = new System.Windows.Forms.Label();
this.theResultsPanel = new System.Windows.Forms.Panel();
this.theResultsSplitContainer = new System.Windows.Forms.SplitContainer();
this.theMainSplitContainer = new System.Windows.Forms.SplitContainer();
this.theExclusionsGroupBox.SuspendLayout();
this.theFileTypeGroupBox.SuspendLayout();
this.theInclusionsGroupBox.SuspendLayout();
this.theControlsGroupBox.SuspendLayout();
this.theResultsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.theResultsSplitContainer)).BeginInit();
this.theResultsSplitContainer.Panel1.SuspendLayout();
this.theResultsSplitContainer.Panel2.SuspendLayout();
this.theResultsSplitContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.theMainSplitContainer)).BeginInit();
this.theMainSplitContainer.Panel1.SuspendLayout();
this.theMainSplitContainer.Panel2.SuspendLayout();
this.theMainSplitContainer.SuspendLayout();
this.SuspendLayout();
//
// theSearchButton
//
this.theSearchButton.Enabled = false;
this.theSearchButton.Location = new System.Drawing.Point(1001, 102);
this.theSearchButton.Name = "theSearchButton";
this.theSearchButton.Size = new System.Drawing.Size(74, 23);
this.theSearchButton.TabIndex = 11;
this.theSearchButton.Text = global::Finder.Properties.Resources.SearchButtonText;
this.theSearchButton.UseVisualStyleBackColor = true;
this.theSearchButton.Click += new System.EventHandler(this.SearchButton_Click);
//
// theSearchTermTextBox
//
this.theSearchTermTextBox.Location = new System.Drawing.Point(8, 105);
this.theSearchTermTextBox.MaxLength = 70;
this.theSearchTermTextBox.Name = "theSearchTermTextBox";
this.theSearchTermTextBox.Size = new System.Drawing.Size(983, 20);
this.theSearchTermTextBox.TabIndex = 9;
this.theSearchTermTextBox.TextChanged += new System.EventHandler(this.SearchTermTextBox_TextChanged);
this.theSearchTermTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.SearchTermTextBox_KeyDown);
//
// theFoundSearchTermRichTextBox
//
this.theFoundSearchTermRichTextBox.Cursor = System.Windows.Forms.Cursors.Default;
this.theFoundSearchTermRichTextBox.DetectUrls = false;
this.theFoundSearchTermRichTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.theFoundSearchTermRichTextBox.Enabled = false;
this.theFoundSearchTermRichTextBox.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.theFoundSearchTermRichTextBox.Location = new System.Drawing.Point(0, 0);
this.theFoundSearchTermRichTextBox.Name = "theFoundSearchTermRichTextBox";
this.theFoundSearchTermRichTextBox.ReadOnly = true;
this.theFoundSearchTermRichTextBox.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.theFoundSearchTermRichTextBox.Size = new System.Drawing.Size(1084, 294);
this.theFoundSearchTermRichTextBox.TabIndex = 13;
this.theFoundSearchTermRichTextBox.Text = global::Finder.Properties.Resources.Empty;
this.theFoundSearchTermRichTextBox.WordWrap = false;
this.theFoundSearchTermRichTextBox.Click += new System.EventHandler(this.FoundSearchTermRichTextBox_Click);
this.theFoundSearchTermRichTextBox.DoubleClick += new System.EventHandler(this.FoundSearchTermRichTextBox_DoubleClick);
this.theFoundSearchTermRichTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FoundSearchTermRichTextBox_KeyDown);
this.theFoundSearchTermRichTextBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.FoundSearchTermRichTextBox_KeyUp);
this.theFoundSearchTermRichTextBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.FoundSearchTermRichTextBox_MouseUp);
//
// theCaseSensitiveCheckBox
//
this.theCaseSensitiveCheckBox.AutoSize = true;
this.theCaseSensitiveCheckBox.Location = new System.Drawing.Point(126, 17);
this.theCaseSensitiveCheckBox.Name = "theCaseSensitiveCheckBox";
this.theCaseSensitiveCheckBox.Size = new System.Drawing.Size(102, 17);
this.theCaseSensitiveCheckBox.TabIndex = 1;
this.theCaseSensitiveCheckBox.Text = global::Finder.Properties.Resources.CaseSensitiveCheckboxText;
this.theCaseSensitiveCheckBox.UseVisualStyleBackColor = true;
//
// theIgnoreCommentsCheckBox
//
this.theIgnoreCommentsCheckBox.AutoSize = true;
this.theIgnoreCommentsCheckBox.Location = new System.Drawing.Point(6, 17);
this.theIgnoreCommentsCheckBox.Name = "theIgnoreCommentsCheckBox";
this.theIgnoreCommentsCheckBox.Size = new System.Drawing.Size(114, 17);
this.theIgnoreCommentsCheckBox.TabIndex = 0;
this.theIgnoreCommentsCheckBox.Text = global::Finder.Properties.Resources.IgnoreCommentsCheckboxText;
this.theIgnoreCommentsCheckBox.UseVisualStyleBackColor = true;
//
// theFoundFilesListBox
//
this.theFoundFilesListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.theFoundFilesListBox.Enabled = false;
this.theFoundFilesListBox.FormattingEnabled = true;
this.theFoundFilesListBox.IntegralHeight = false;
this.theFoundFilesListBox.Location = new System.Drawing.Point(0, 0);
this.theFoundFilesListBox.Name = "theFoundFilesListBox";
this.theFoundFilesListBox.Size = new System.Drawing.Size(1084, 130);
this.theFoundFilesListBox.TabIndex = 12;
this.theFoundFilesListBox.SelectedIndexChanged += new System.EventHandler(this.FoundFilesListBox_SelectedIndexChanged);
this.theFoundFilesListBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FoundFilesListBox_KeyDown);
this.theFoundFilesListBox.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.FoundFilesListBox_MouseDoubleClick);
//
// theExitButton
//
this.theExitButton.Location = new System.Drawing.Point(1001, 57);
this.theExitButton.Name = "theExitButton";
this.theExitButton.Size = new System.Drawing.Size(74, 23);
this.theExitButton.TabIndex = 6;
this.theExitButton.Text = global::Finder.Properties.Resources.ExitButtonText;
this.theExitButton.UseVisualStyleBackColor = true;
this.theExitButton.Click += new System.EventHandler(this.ExitButton_Click);
//
// theSelectDirectoryButton
//
this.theSelectDirectoryButton.Location = new System.Drawing.Point(8, 14);
this.theSelectDirectoryButton.Name = "theSelectDirectoryButton";
this.theSelectDirectoryButton.Size = new System.Drawing.Size(100, 23);
this.theSelectDirectoryButton.TabIndex = 0;
this.theSelectDirectoryButton.Text = global::Finder.Properties.Resources.SelectDirectoryButton;
this.theSelectDirectoryButton.UseVisualStyleBackColor = true;
this.theSelectDirectoryButton.Click += new System.EventHandler(this.SelectDirectoryButton_Click);
//
// theSelectedDirectoryTextBox
//
this.theSelectedDirectoryTextBox.Location = new System.Drawing.Point(114, 16);
this.theSelectedDirectoryTextBox.Name = "theSelectedDirectoryTextBox";
this.theSelectedDirectoryTextBox.ReadOnly = true;
this.theSelectedDirectoryTextBox.Size = new System.Drawing.Size(877, 20);
this.theSelectedDirectoryTextBox.TabIndex = 1;
//
// theExclusionsGroupBox
//
this.theExclusionsGroupBox.Controls.Add(this.theIgnoreCommentsCheckBox);
this.theExclusionsGroupBox.Controls.Add(this.theCaseSensitiveCheckBox);
this.theExclusionsGroupBox.Location = new System.Drawing.Point(146, 43);
this.theExclusionsGroupBox.Name = "theExclusionsGroupBox";
this.theExclusionsGroupBox.Size = new System.Drawing.Size(229, 40);
this.theExclusionsGroupBox.TabIndex = 4;
this.theExclusionsGroupBox.TabStop = false;
this.theExclusionsGroupBox.Text = global::Finder.Properties.Resources.ExclusionsGroupBoxText;
//
// theFileTypeGroupBox
//
this.theFileTypeGroupBox.Controls.Add(this.theAllCheckBox);
this.theFileTypeGroupBox.Controls.Add(this.theCSharpCheckBox);
this.theFileTypeGroupBox.Controls.Add(this.theCSourceCheckBox);
this.theFileTypeGroupBox.Controls.Add(this.theCPlusPlusCHeaderCheckBox);
this.theFileTypeGroupBox.Controls.Add(this.theCPlusPlusSourceCheckBox);
this.theFileTypeGroupBox.Location = new System.Drawing.Point(381, 43);
this.theFileTypeGroupBox.Name = "theFileTypeGroupBox";
this.theFileTypeGroupBox.Size = new System.Drawing.Size(358, 40);
this.theFileTypeGroupBox.TabIndex = 5;
this.theFileTypeGroupBox.TabStop = false;
this.theFileTypeGroupBox.Text = global::Finder.Properties.Resources.FileTypesGroupBoxText;
//
// theAllCheckBox
//
this.theAllCheckBox.AutoSize = true;
this.theAllCheckBox.Location = new System.Drawing.Point(7, 17);
this.theAllCheckBox.Name = "theAllCheckBox";
this.theAllCheckBox.Size = new System.Drawing.Size(37, 17);
this.theAllCheckBox.TabIndex = 0;
this.theAllCheckBox.Text = global::Finder.Properties.Resources.AllCheckboxText;
this.theAllCheckBox.UseVisualStyleBackColor = true;
this.theAllCheckBox.CheckedChanged += new System.EventHandler(this.AllCheckBox_CheckedChanged);
//
// theCSharpCheckBox
//
this.theCSharpCheckBox.AutoSize = true;
this.theCSharpCheckBox.Checked = true;
this.theCSharpCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.theCSharpCheckBox.Location = new System.Drawing.Point(315, 17);
this.theCSharpCheckBox.Name = "theCSharpCheckBox";
this.theCSharpCheckBox.Size = new System.Drawing.Size(40, 17);
this.theCSharpCheckBox.TabIndex = 4;
this.theCSharpCheckBox.Text = global::Finder.Properties.Resources.CSharpCheckboxText;
this.theCSharpCheckBox.UseVisualStyleBackColor = true;
//
// theCSourceCheckBox
//
this.theCSourceCheckBox.AutoSize = true;
this.theCSourceCheckBox.Checked = true;
this.theCSourceCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.theCSourceCheckBox.Location = new System.Drawing.Point(239, 17);
this.theCSourceCheckBox.Name = "theCSourceCheckBox";
this.theCSourceCheckBox.Size = new System.Drawing.Size(70, 17);
this.theCSourceCheckBox.TabIndex = 3;
this.theCSourceCheckBox.Text = global::Finder.Properties.Resources.CSourceCheckboxText;
this.theCSourceCheckBox.UseVisualStyleBackColor = true;
//
// theCPlusPlusCHeaderCheckBox
//
this.theCPlusPlusCHeaderCheckBox.AutoSize = true;
this.theCPlusPlusCHeaderCheckBox.Checked = true;
this.theCPlusPlusCHeaderCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.theCPlusPlusCHeaderCheckBox.Location = new System.Drawing.Point(138, 17);
this.theCPlusPlusCHeaderCheckBox.Name = "theCPlusPlusCHeaderCheckBox";
this.theCPlusPlusCHeaderCheckBox.Size = new System.Drawing.Size(95, 17);
this.theCPlusPlusCHeaderCheckBox.TabIndex = 2;
this.theCPlusPlusCHeaderCheckBox.Text = global::Finder.Properties.Resources.CPlusPlusCHeaderCheckboxText;
this.theCPlusPlusCHeaderCheckBox.UseVisualStyleBackColor = true;
//
// theCPlusPlusSourceCheckBox
//
this.theCPlusPlusSourceCheckBox.AutoSize = true;
this.theCPlusPlusSourceCheckBox.Checked = true;
this.theCPlusPlusSourceCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.theCPlusPlusSourceCheckBox.Location = new System.Drawing.Point(50, 17);
this.theCPlusPlusSourceCheckBox.Name = "theCPlusPlusSourceCheckBox";
this.theCPlusPlusSourceCheckBox.Size = new System.Drawing.Size(82, 17);
this.theCPlusPlusSourceCheckBox.TabIndex = 1;
this.theCPlusPlusSourceCheckBox.Text = global::Finder.Properties.Resources.CPlusPlusSourceCheckboxText;
this.theCPlusPlusSourceCheckBox.UseVisualStyleBackColor = true;
//
// theResetButton
//
this.theResetButton.Location = new System.Drawing.Point(1000, 14);
this.theResetButton.Name = "theResetButton";
this.theResetButton.Size = new System.Drawing.Size(75, 23);
this.theResetButton.TabIndex = 2;
this.theResetButton.Text = global::Finder.Properties.Resources.ResetButtonText;
this.theResetButton.UseVisualStyleBackColor = true;
this.theResetButton.Click += new System.EventHandler(this.ResetButton_Click);
//
// thePerformSearchProgressBar
//
this.thePerformSearchProgressBar.Location = new System.Drawing.Point(8, 102);
this.thePerformSearchProgressBar.Name = "thePerformSearchProgressBar";
this.thePerformSearchProgressBar.Size = new System.Drawing.Size(983, 23);
this.thePerformSearchProgressBar.TabIndex = 10;
this.thePerformSearchProgressBar.Visible = false;
//
// theInclusionsGroupBox
//
this.theInclusionsGroupBox.Controls.Add(this.theSearchRecursivelyCheckBox);
this.theInclusionsGroupBox.Location = new System.Drawing.Point(8, 43);
this.theInclusionsGroupBox.Name = "theInclusionsGroupBox";
this.theInclusionsGroupBox.Size = new System.Drawing.Size(134, 40);
this.theInclusionsGroupBox.TabIndex = 3;
this.theInclusionsGroupBox.TabStop = false;
this.theInclusionsGroupBox.Text = global::Finder.Properties.Resources.InclusionsGroupBoxText;
//
// theSearchRecursivelyCheckBox
//
this.theSearchRecursivelyCheckBox.AutoSize = true;
this.theSearchRecursivelyCheckBox.Checked = true;
this.theSearchRecursivelyCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.theSearchRecursivelyCheckBox.Location = new System.Drawing.Point(4, 17);
this.theSearchRecursivelyCheckBox.Name = "theSearchRecursivelyCheckBox";
this.theSearchRecursivelyCheckBox.Size = new System.Drawing.Size(124, 17);
this.theSearchRecursivelyCheckBox.TabIndex = 0;
this.theSearchRecursivelyCheckBox.Text = global::Finder.Properties.Resources.SearchRecursivelyCheckboxText;
this.theSearchRecursivelyCheckBox.UseVisualStyleBackColor = true;
//
// theControlsGroupBox
//
this.theControlsGroupBox.Controls.Add(this.thePerformSearchProgressBarLabel);
this.theControlsGroupBox.Controls.Add(this.theSearchTermTextBoxLabel);
this.theControlsGroupBox.Controls.Add(this.theSelectedDirectoryTextBox);
this.theControlsGroupBox.Controls.Add(this.theSelectDirectoryButton);
this.theControlsGroupBox.Controls.Add(this.thePerformSearchProgressBar);
this.theControlsGroupBox.Controls.Add(this.theInclusionsGroupBox);
this.theControlsGroupBox.Controls.Add(this.theResetButton);
this.theControlsGroupBox.Controls.Add(this.theSearchTermTextBox);
this.theControlsGroupBox.Controls.Add(this.theExitButton);
this.theControlsGroupBox.Controls.Add(this.theFileTypeGroupBox);
this.theControlsGroupBox.Controls.Add(this.theSearchButton);
this.theControlsGroupBox.Controls.Add(this.theExclusionsGroupBox);
this.theControlsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.theControlsGroupBox.Location = new System.Drawing.Point(0, 0);
this.theControlsGroupBox.Name = "theControlsGroupBox";
this.theControlsGroupBox.Size = new System.Drawing.Size(1084, 130);
this.theControlsGroupBox.TabIndex = 0;
this.theControlsGroupBox.TabStop = false;
//
// thePerformSearchProgressBarLabel
//
this.thePerformSearchProgressBarLabel.AutoSize = true;
this.thePerformSearchProgressBarLabel.Location = new System.Drawing.Point(7, 86);
this.thePerformSearchProgressBarLabel.Name = "thePerformSearchProgressBarLabel";
this.thePerformSearchProgressBarLabel.Size = new System.Drawing.Size(48, 13);
this.thePerformSearchProgressBarLabel.TabIndex = 8;
this.thePerformSearchProgressBarLabel.Text = global::Finder.Properties.Resources.Progress;
this.thePerformSearchProgressBarLabel.Visible = false;
//
// theSearchTermTextBoxLabel
//
this.theSearchTermTextBoxLabel.AutoSize = true;
this.theSearchTermTextBoxLabel.Location = new System.Drawing.Point(6, 86);
this.theSearchTermTextBoxLabel.Name = "theSearchTermTextBoxLabel";
this.theSearchTermTextBoxLabel.Size = new System.Drawing.Size(68, 13);
this.theSearchTermTextBoxLabel.TabIndex = 7;
this.theSearchTermTextBoxLabel.Text = global::Finder.Properties.Resources.SearchTerm;
//
// theResultsPanel
//
this.theResultsPanel.Controls.Add(this.theResultsSplitContainer);
this.theResultsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.theResultsPanel.Location = new System.Drawing.Point(0, 0);
this.theResultsPanel.Name = "theResultsPanel";
this.theResultsPanel.Size = new System.Drawing.Size(1084, 428);
this.theResultsPanel.TabIndex = 15;
//
// theResultsSplitContainer
//
this.theResultsSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.theResultsSplitContainer.Location = new System.Drawing.Point(0, 0);
this.theResultsSplitContainer.Name = "theResultsSplitContainer";
this.theResultsSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// theResultsSplitContainer.Panel1
//
this.theResultsSplitContainer.Panel1.Controls.Add(this.theFoundFilesListBox);
this.theResultsSplitContainer.Panel1MinSize = 0;
//
// theResultsSplitContainer.Panel2
//
this.theResultsSplitContainer.Panel2.Controls.Add(this.theFoundSearchTermRichTextBox);
this.theResultsSplitContainer.Panel2MinSize = 0;
this.theResultsSplitContainer.Size = new System.Drawing.Size(1084, 428);
this.theResultsSplitContainer.SplitterDistance = 130;
this.theResultsSplitContainer.TabIndex = 0;
//
// theMainSplitContainer
//
this.theMainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.theMainSplitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.theMainSplitContainer.IsSplitterFixed = true;
this.theMainSplitContainer.Location = new System.Drawing.Point(0, 0);
this.theMainSplitContainer.Name = "theMainSplitContainer";
this.theMainSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// theMainSplitContainer.Panel1
//
this.theMainSplitContainer.Panel1.Controls.Add(this.theControlsGroupBox);
this.theMainSplitContainer.Panel1MinSize = 0;
//
// theMainSplitContainer.Panel2
//
this.theMainSplitContainer.Panel2.Controls.Add(this.theResultsPanel);
this.theMainSplitContainer.Panel2MinSize = 0;
this.theMainSplitContainer.Size = new System.Drawing.Size(1084, 562);
this.theMainSplitContainer.SplitterDistance = 130;
this.theMainSplitContainer.TabIndex = 16;
//
// MainWindowForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1084, 562);
this.Controls.Add(this.theMainSplitContainer);
this.MinimumSize = new System.Drawing.Size(1100, 300);
this.Name = "MainWindowForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = global::Finder.Properties.Resources.Finder;
this.theExclusionsGroupBox.ResumeLayout(false);
this.theExclusionsGroupBox.PerformLayout();
this.theFileTypeGroupBox.ResumeLayout(false);
this.theFileTypeGroupBox.PerformLayout();
this.theInclusionsGroupBox.ResumeLayout(false);
this.theInclusionsGroupBox.PerformLayout();
this.theControlsGroupBox.ResumeLayout(false);
this.theControlsGroupBox.PerformLayout();
this.theResultsPanel.ResumeLayout(false);
this.theResultsSplitContainer.Panel1.ResumeLayout(false);
this.theResultsSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.theResultsSplitContainer)).EndInit();
this.theResultsSplitContainer.ResumeLayout(false);
this.theMainSplitContainer.Panel1.ResumeLayout(false);
this.theMainSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.theMainSplitContainer)).EndInit();
this.theMainSplitContainer.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Sql.Database.Model;
using Microsoft.Azure.Commands.Sql.Database.Services;
using Microsoft.Azure.Commands.Sql.ElasticPool.Model;
using Microsoft.Azure.Commands.Sql.Server.Adapter;
using Microsoft.Azure.Commands.Sql.Services;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
namespace Microsoft.Azure.Commands.Sql.ElasticPool.Services
{
/// <summary>
/// Adapter for ElasticPool operations
/// </summary>
public class AzureSqlElasticPoolAdapter
{
/// <summary>
/// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients
/// </summary>
private AzureSqlElasticPoolCommunicator Communicator { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public AzureContext Context { get; set; }
/// <summary>
/// Gets or sets the Azure Subscription
/// </summary>
private AzureSubscription _subscription { get; set; }
/// <summary>
/// Constructs a database adapter
/// </summary>
/// <param name="profile">The current azure profile</param>
/// <param name="subscription">The current azure subscription</param>
public AzureSqlElasticPoolAdapter(AzureContext context)
{
_subscription = context.Subscription;
Context = context;
Communicator = new AzureSqlElasticPoolCommunicator(Context);
}
/// <summary>
/// Gets an Azure Sql Database ElasticPool by name.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="poolName">The name of the Azure Sql Database ElasticPool</param>
/// <returns>The Azure Sql Database ElasticPool object</returns>
internal AzureSqlElasticPoolModel GetElasticPool(string resourceGroupName, string serverName, string poolName)
{
var resp = Communicator.Get(resourceGroupName, serverName, poolName, Util.GenerateTracingId());
return CreateElasticPoolModelFromResponse(resourceGroupName, serverName, resp);
}
/// <summary>
/// Gets a list of Azure Sql Databases ElasticPool.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <returns>A list of database objects</returns>
internal ICollection<AzureSqlElasticPoolModel> ListElasticPools(string resourceGroupName, string serverName)
{
var resp = Communicator.List(resourceGroupName, serverName, Util.GenerateTracingId());
return resp.Select((db) =>
{
return CreateElasticPoolModelFromResponse(resourceGroupName, serverName, db);
}).ToList();
}
/// <summary>
/// Creates or updates an Azure Sql Database ElasticPool.
/// </summary>
/// <param name="resourceGroup">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="model">The input parameters for the create/update operation</param>
/// <returns>The upserted Azure Sql Database ElasticPool</returns>
internal AzureSqlElasticPoolModel UpsertElasticPool(AzureSqlElasticPoolModel model)
{
var resp = Communicator.CreateOrUpdate(model.ResourceGroupName, model.ServerName, model.ElasticPoolName, Util.GenerateTracingId(), new ElasticPoolCreateOrUpdateParameters()
{
Location = model.Location,
Tags = model.Tags,
Properties = new ElasticPoolCreateOrUpdateProperties()
{
DatabaseDtuMax = model.DatabaseDtuMax,
DatabaseDtuMin = model.DatabaseDtuMin,
Edition = model.Edition.ToString(),
Dtu = model.Dtu,
StorageMB = model.StorageMB
}
});
return CreateElasticPoolModelFromResponse(model.ResourceGroupName, model.ServerName, resp);
}
/// <summary>
/// Deletes a database
/// </summary>
/// <param name="resourceGroupName">The resource group the server is in</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="databaseName">The name of the Azure Sql Database to delete</param>
public void RemoveElasticPool(string resourceGroupName, string serverName, string databaseName)
{
Communicator.Remove(resourceGroupName, serverName, databaseName, Util.GenerateTracingId());
}
/// <summary>
/// Gets a database in an elastic pool
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="poolName">The name of the Azure Sql Database ElasticPool</param>
/// <param name="databaseName">The name of the database</param>
/// <returns></returns>
public AzureSqlDatabaseModel GetElasticPoolDatabase(string resourceGroupName, string serverName, string poolName, string databaseName)
{
var resp = Communicator.GetDatabase(resourceGroupName, serverName, poolName, databaseName, Util.GenerateTracingId());
return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, resp);
}
/// <summary>
/// Gets a list of Azure Sql Databases in an ElasticPool.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="poolName">The name of the elastic pool the database are in</param>
/// <returns>A list of database objects</returns>
internal ICollection<AzureSqlDatabaseModel> ListElasticPoolDatabases(string resourceGroupName, string serverName, string poolName)
{
var resp = Communicator.ListDatabases(resourceGroupName, serverName, poolName, Util.GenerateTracingId());
return resp.Select((db) =>
{
return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, db);
}).ToList();
}
/// <summary>
/// Gets a list of Elastic Pool Activity
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="poolName">The name of the elastic pool</param>
/// <returns>A list of Elastic Pool Activities</returns>
internal IList<AzureSqlElasticPoolActivityModel> GetElasticPoolActivity(string resourceGroupName, string serverName, string poolName)
{
var resp = Communicator.ListActivity(resourceGroupName, serverName, poolName, Util.GenerateTracingId());
return resp.Select((activity) =>
{
return CreateActivityModelFromResponse(activity);
}).ToList();
}
/// <summary>
/// Gets a list of Elastic Pool Database Activity
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="poolName">The name of the elastic pool</param>
/// <returns>A list of Elastic Pool Database Activities</returns>
internal IList<AzureSqlDatabaseActivityModel> ListElasticPoolDatabaseActivity(string resourceGroupName, string serverName, string poolName)
{
var resp = Communicator.ListDatabaseActivity(resourceGroupName, serverName, poolName, Util.GenerateTracingId());
return resp.Select((activity) =>
{
return CreateDatabaseActivityModelFromResponse(activity);
}).ToList();
}
/// <summary>
/// Converts a model received from the server to a powershell model
/// </summary>
/// <param name="model">The model to transform</param>
/// <returns>The transformed model</returns>
private AzureSqlDatabaseActivityModel CreateDatabaseActivityModelFromResponse(ElasticPoolDatabaseActivity model)
{
AzureSqlDatabaseActivityModel activity = new AzureSqlDatabaseActivityModel();
//activity.CurrentElasticPoolName = model.Properties.CurrentElasticPoolName;
//activity.CurrentServiceObjectiveName = model.Properties.CurrentServiceObjectiveName;
//activity.DatabaseName = model.Properties.DatabaseName;
//activity.EndTime = model.Properties.EndTime;
//activity.ErrorCode = model.Properties.ErrorCode;
//activity.ErrorMessage = model.Properties.ErrorMessage;
//activity.ErrorSeverity = model.Properties.ErrorSeverity;
//activity.Operation = model.Properties.Operation;
//activity.OperationId = model.Properties.OperationId;
//activity.PercentComplete = model.Properties.PercentComplete;
//activity.RequestedElasticPoolName = model.Properties.RequestedElasticPoolName;
//activity.RequestedServiceObjectiveName = model.Properties.RequestedServiceObjectiveName;
//activity.ServerName = model.Properties.ServerName;
//activity.StartTime = model.Properties.StartTime;
//activity.State = model.Properties.State;
return activity;
}
/// <summary>
/// Converts a ElascitPoolAcitivy model to the powershell model.
/// </summary>
/// <param name="model">The model from the service</param>
/// <returns>The converted model</returns>
private AzureSqlElasticPoolActivityModel CreateActivityModelFromResponse(ElasticPoolActivity model)
{
AzureSqlElasticPoolActivityModel activity = new AzureSqlElasticPoolActivityModel();
activity.ElasticPoolName = model.Properties.ElasticPoolName;
activity.EndTime = model.Properties.EndTime;
activity.ErrorCode = model.Properties.ErrorCode;
activity.ErrorMessage = model.Properties.ErrorMessage;
activity.ErrorSeverity = model.Properties.ErrorSeverity;
activity.Operation = model.Properties.Operation;
activity.OperationId = model.Properties.OperationId;
activity.PercentComplete = model.Properties.PercentComplete;
activity.RequestedDatabaseDtuMax = model.Properties.RequestedDatabaseDtuMax;
activity.RequestedDatabaseDtuMin = model.Properties.RequestedDatabaseDtuMin;
activity.RequestedDtu = model.Properties.RequestedDtu;
activity.RequestedElasticPoolName = model.Properties.RequestedElasticPoolName;
activity.RequestedStorageLimitInGB = model.Properties.RequestedStorageLimitInGB;
activity.ServerName = model.Properties.ServerName;
activity.StartTime = model.Properties.StartTime;
activity.State = model.Properties.State;
return activity;
}
/// <summary>
/// Gets the Location of the server.
/// </summary>
/// <param name="resourceGroupName">The resource group the server is in</param>
/// <param name="serverName">The name of the server</param>
/// <returns></returns>
public string GetServerLocation(string resourceGroupName, string serverName)
{
AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context);
var server = serverAdapter.GetServer(resourceGroupName, serverName);
return server.Location;
}
/// <summary>
/// Converts the response from the service to a powershell database object
/// </summary>
/// <param name="resourceGroupName">The resource group the server is in</param>
/// <param name="serverName">The name of the Azure Sql Database Server</param>
/// <param name="pool">The service response</param>
/// <returns>The converted model</returns>
private AzureSqlElasticPoolModel CreateElasticPoolModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.ElasticPool pool)
{
AzureSqlElasticPoolModel model = new AzureSqlElasticPoolModel();
model.ResourceId = pool.Id;
model.ResourceGroupName = resourceGroup;
model.ServerName = serverName;
model.ElasticPoolName = pool.Name;
model.CreationDate = pool.Properties.CreationDate ?? DateTime.MinValue;
model.DatabaseDtuMax = (int)pool.Properties.DatabaseDtuMax;
model.DatabaseDtuMin = (int)pool.Properties.DatabaseDtuMin;
model.Dtu = (int)pool.Properties.Dtu;
model.State = pool.Properties.State;
model.StorageMB = pool.Properties.StorageMB;
model.Tags = TagsConversionHelper.CreateTagDictionary(TagsConversionHelper.CreateTagHashtable(pool.Tags), false);
model.Location = pool.Location;
DatabaseEdition edition = DatabaseEdition.None;
Enum.TryParse<DatabaseEdition>(pool.Properties.Edition, out edition);
model.Edition = edition;
return model;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
/// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
/// a remote call so in general you should reuse a single channel for as many calls as possible.
/// </summary>
public class Channel
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
readonly object myLock = new object();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly string target;
readonly GrpcEnvironment environment;
readonly ChannelSafeHandle handle;
readonly Dictionary<string, ChannelOption> options;
bool shutdownRequested;
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null)
{
this.target = GrpcPreconditions.CheckNotNull(target, "target");
this.options = CreateOptionsDictionary(options);
EnsureUserAgentChannelOption(this.options);
this.environment = GrpcEnvironment.AddRef();
using (var nativeCredentials = credentials.ToNativeCredentials())
using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
{
if (nativeCredentials != null)
{
this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
}
else
{
this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
}
}
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null) :
this(string.Format("{0}:{1}", host, port), credentials, options)
{
}
/// <summary>
/// Gets current connectivity state of this channel.
/// </summary>
public ChannelState State
{
get
{
return handle.CheckConnectivityState(false);
}
}
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState.
/// If deadline is reached or and error occurs, returned task is cancelled.
/// </summary>
public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
"FatalFailure is a terminal state. No further state changes can occur.");
var tcs = new TaskCompletionSource<object>();
var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
var handler = new BatchCompletionDelegate((success, ctx) =>
{
if (success)
{
tcs.SetResult(null);
}
else
{
tcs.SetCanceled();
}
});
handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
return tcs.Task;
}
/// <summary>Resolved address of the remote endpoint in URI format.</summary>
public string ResolvedTarget
{
get
{
return handle.GetTarget();
}
}
/// <summary>The original target used to create the channel.</summary>
public string Target
{
get
{
return this.target;
}
}
/// <summary>
/// Allows explicitly requesting channel to connect without starting an RPC.
/// Returned task completes once state Ready was seen. If the deadline is reached,
/// or channel enters the FatalFailure state, the task is cancelled.
/// There is no need to call this explicitly unless your use case requires that.
/// Starting an RPC on a new channel will request connection implicitly.
/// </summary>
/// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
public async Task ConnectAsync(DateTime? deadline = null)
{
var currentState = handle.CheckConnectivityState(true);
while (currentState != ChannelState.Ready)
{
if (currentState == ChannelState.FatalFailure)
{
throw new OperationCanceledException("Channel has reached FatalFailure state.");
}
await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
currentState = handle.CheckConnectivityState(false);
}
}
/// <summary>
/// Waits until there are no more active calls for this channel and then cleans up
/// resources used by this channel.
/// </summary>
public async Task ShutdownAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
}
handle.Dispose();
await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false);
}
internal ChannelSafeHandle Handle
{
get
{
return this.handle;
}
}
internal GrpcEnvironment Environment
{
get
{
return this.environment;
}
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
{
var key = ChannelOptions.PrimaryUserAgentString;
var userAgentString = "";
ChannelOption option;
if (options.TryGetValue(key, out option))
{
// user-provided userAgentString needs to be at the beginning
userAgentString = option.StringValue + " ";
};
// TODO(jtattermusch): it would be useful to also provide .NET/mono version.
userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
}
private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
{
var dict = new Dictionary<string, ChannelOption>();
if (options == null)
{
return dict;
}
foreach (var option in options)
{
dict.Add(option.Name, option);
}
return dict;
}
}
}
| |
/*
* 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 dynamodb-2012-08-10.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.DynamoDBv2
{
/// <summary>
/// Constants used for properties of type AttributeAction.
/// </summary>
public class AttributeAction : ConstantClass
{
/// <summary>
/// Constant ADD for AttributeAction
/// </summary>
public static readonly AttributeAction ADD = new AttributeAction("ADD");
/// <summary>
/// Constant DELETE for AttributeAction
/// </summary>
public static readonly AttributeAction DELETE = new AttributeAction("DELETE");
/// <summary>
/// Constant PUT for AttributeAction
/// </summary>
public static readonly AttributeAction PUT = new AttributeAction("PUT");
/// <summary>
/// Default Constructor
/// </summary>
public AttributeAction(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static AttributeAction FindValue(string value)
{
return FindValue<AttributeAction>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator AttributeAction(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ComparisonOperator.
/// </summary>
public class ComparisonOperator : ConstantClass
{
/// <summary>
/// Constant BEGINS_WITH for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator BEGINS_WITH = new ComparisonOperator("BEGINS_WITH");
/// <summary>
/// Constant BETWEEN for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator BETWEEN = new ComparisonOperator("BETWEEN");
/// <summary>
/// Constant CONTAINS for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator CONTAINS = new ComparisonOperator("CONTAINS");
/// <summary>
/// Constant EQ for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator EQ = new ComparisonOperator("EQ");
/// <summary>
/// Constant GE for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator GE = new ComparisonOperator("GE");
/// <summary>
/// Constant GT for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator GT = new ComparisonOperator("GT");
/// <summary>
/// Constant IN for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator IN = new ComparisonOperator("IN");
/// <summary>
/// Constant LE for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator LE = new ComparisonOperator("LE");
/// <summary>
/// Constant LT for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator LT = new ComparisonOperator("LT");
/// <summary>
/// Constant NE for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator NE = new ComparisonOperator("NE");
/// <summary>
/// Constant NOT_CONTAINS for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator NOT_CONTAINS = new ComparisonOperator("NOT_CONTAINS");
/// <summary>
/// Constant NOT_NULL for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator NOT_NULL = new ComparisonOperator("NOT_NULL");
/// <summary>
/// Constant NULL for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator NULL = new ComparisonOperator("NULL");
/// <summary>
/// Default Constructor
/// </summary>
public ComparisonOperator(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ComparisonOperator FindValue(string value)
{
return FindValue<ComparisonOperator>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ComparisonOperator(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ConditionalOperator.
/// </summary>
public class ConditionalOperator : ConstantClass
{
/// <summary>
/// Constant AND for ConditionalOperator
/// </summary>
public static readonly ConditionalOperator AND = new ConditionalOperator("AND");
/// <summary>
/// Constant OR for ConditionalOperator
/// </summary>
public static readonly ConditionalOperator OR = new ConditionalOperator("OR");
/// <summary>
/// Default Constructor
/// </summary>
public ConditionalOperator(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ConditionalOperator FindValue(string value)
{
return FindValue<ConditionalOperator>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ConditionalOperator(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type IndexStatus.
/// </summary>
public class IndexStatus : ConstantClass
{
/// <summary>
/// Constant ACTIVE for IndexStatus
/// </summary>
public static readonly IndexStatus ACTIVE = new IndexStatus("ACTIVE");
/// <summary>
/// Constant CREATING for IndexStatus
/// </summary>
public static readonly IndexStatus CREATING = new IndexStatus("CREATING");
/// <summary>
/// Constant DELETING for IndexStatus
/// </summary>
public static readonly IndexStatus DELETING = new IndexStatus("DELETING");
/// <summary>
/// Constant UPDATING for IndexStatus
/// </summary>
public static readonly IndexStatus UPDATING = new IndexStatus("UPDATING");
/// <summary>
/// Default Constructor
/// </summary>
public IndexStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static IndexStatus FindValue(string value)
{
return FindValue<IndexStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator IndexStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type KeyType.
/// </summary>
public class KeyType : ConstantClass
{
/// <summary>
/// Constant HASH for KeyType
/// </summary>
public static readonly KeyType HASH = new KeyType("HASH");
/// <summary>
/// Constant RANGE for KeyType
/// </summary>
public static readonly KeyType RANGE = new KeyType("RANGE");
/// <summary>
/// Default Constructor
/// </summary>
public KeyType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static KeyType FindValue(string value)
{
return FindValue<KeyType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator KeyType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ProjectionType.
/// </summary>
public class ProjectionType : ConstantClass
{
/// <summary>
/// Constant ALL for ProjectionType
/// </summary>
public static readonly ProjectionType ALL = new ProjectionType("ALL");
/// <summary>
/// Constant INCLUDE for ProjectionType
/// </summary>
public static readonly ProjectionType INCLUDE = new ProjectionType("INCLUDE");
/// <summary>
/// Constant KEYS_ONLY for ProjectionType
/// </summary>
public static readonly ProjectionType KEYS_ONLY = new ProjectionType("KEYS_ONLY");
/// <summary>
/// Default Constructor
/// </summary>
public ProjectionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ProjectionType FindValue(string value)
{
return FindValue<ProjectionType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ProjectionType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ReturnConsumedCapacity.
/// </summary>
public class ReturnConsumedCapacity : ConstantClass
{
/// <summary>
/// Constant INDEXES for ReturnConsumedCapacity
/// </summary>
public static readonly ReturnConsumedCapacity INDEXES = new ReturnConsumedCapacity("INDEXES");
/// <summary>
/// Constant NONE for ReturnConsumedCapacity
/// </summary>
public static readonly ReturnConsumedCapacity NONE = new ReturnConsumedCapacity("NONE");
/// <summary>
/// Constant TOTAL for ReturnConsumedCapacity
/// </summary>
public static readonly ReturnConsumedCapacity TOTAL = new ReturnConsumedCapacity("TOTAL");
/// <summary>
/// Default Constructor
/// </summary>
public ReturnConsumedCapacity(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ReturnConsumedCapacity FindValue(string value)
{
return FindValue<ReturnConsumedCapacity>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ReturnConsumedCapacity(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ReturnItemCollectionMetrics.
/// </summary>
public class ReturnItemCollectionMetrics : ConstantClass
{
/// <summary>
/// Constant NONE for ReturnItemCollectionMetrics
/// </summary>
public static readonly ReturnItemCollectionMetrics NONE = new ReturnItemCollectionMetrics("NONE");
/// <summary>
/// Constant SIZE for ReturnItemCollectionMetrics
/// </summary>
public static readonly ReturnItemCollectionMetrics SIZE = new ReturnItemCollectionMetrics("SIZE");
/// <summary>
/// Default Constructor
/// </summary>
public ReturnItemCollectionMetrics(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ReturnItemCollectionMetrics FindValue(string value)
{
return FindValue<ReturnItemCollectionMetrics>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ReturnItemCollectionMetrics(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ReturnValue.
/// </summary>
public class ReturnValue : ConstantClass
{
/// <summary>
/// Constant ALL_NEW for ReturnValue
/// </summary>
public static readonly ReturnValue ALL_NEW = new ReturnValue("ALL_NEW");
/// <summary>
/// Constant ALL_OLD for ReturnValue
/// </summary>
public static readonly ReturnValue ALL_OLD = new ReturnValue("ALL_OLD");
/// <summary>
/// Constant NONE for ReturnValue
/// </summary>
public static readonly ReturnValue NONE = new ReturnValue("NONE");
/// <summary>
/// Constant UPDATED_NEW for ReturnValue
/// </summary>
public static readonly ReturnValue UPDATED_NEW = new ReturnValue("UPDATED_NEW");
/// <summary>
/// Constant UPDATED_OLD for ReturnValue
/// </summary>
public static readonly ReturnValue UPDATED_OLD = new ReturnValue("UPDATED_OLD");
/// <summary>
/// Default Constructor
/// </summary>
public ReturnValue(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ReturnValue FindValue(string value)
{
return FindValue<ReturnValue>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ReturnValue(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ScalarAttributeType.
/// </summary>
public class ScalarAttributeType : ConstantClass
{
/// <summary>
/// Constant B for ScalarAttributeType
/// </summary>
public static readonly ScalarAttributeType B = new ScalarAttributeType("B");
/// <summary>
/// Constant N for ScalarAttributeType
/// </summary>
public static readonly ScalarAttributeType N = new ScalarAttributeType("N");
/// <summary>
/// Constant S for ScalarAttributeType
/// </summary>
public static readonly ScalarAttributeType S = new ScalarAttributeType("S");
/// <summary>
/// Default Constructor
/// </summary>
public ScalarAttributeType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ScalarAttributeType FindValue(string value)
{
return FindValue<ScalarAttributeType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ScalarAttributeType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type Select.
/// </summary>
public class Select : ConstantClass
{
/// <summary>
/// Constant ALL_ATTRIBUTES for Select
/// </summary>
public static readonly Select ALL_ATTRIBUTES = new Select("ALL_ATTRIBUTES");
/// <summary>
/// Constant ALL_PROJECTED_ATTRIBUTES for Select
/// </summary>
public static readonly Select ALL_PROJECTED_ATTRIBUTES = new Select("ALL_PROJECTED_ATTRIBUTES");
/// <summary>
/// Constant COUNT for Select
/// </summary>
public static readonly Select COUNT = new Select("COUNT");
/// <summary>
/// Constant SPECIFIC_ATTRIBUTES for Select
/// </summary>
public static readonly Select SPECIFIC_ATTRIBUTES = new Select("SPECIFIC_ATTRIBUTES");
/// <summary>
/// Default Constructor
/// </summary>
public Select(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static Select FindValue(string value)
{
return FindValue<Select>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator Select(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type StreamViewType.
/// </summary>
public class StreamViewType : ConstantClass
{
/// <summary>
/// Constant KEYS_ONLY for StreamViewType
/// </summary>
public static readonly StreamViewType KEYS_ONLY = new StreamViewType("KEYS_ONLY");
/// <summary>
/// Constant NEW_AND_OLD_IMAGES for StreamViewType
/// </summary>
public static readonly StreamViewType NEW_AND_OLD_IMAGES = new StreamViewType("NEW_AND_OLD_IMAGES");
/// <summary>
/// Constant NEW_IMAGE for StreamViewType
/// </summary>
public static readonly StreamViewType NEW_IMAGE = new StreamViewType("NEW_IMAGE");
/// <summary>
/// Constant OLD_IMAGE for StreamViewType
/// </summary>
public static readonly StreamViewType OLD_IMAGE = new StreamViewType("OLD_IMAGE");
/// <summary>
/// Default Constructor
/// </summary>
public StreamViewType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static StreamViewType FindValue(string value)
{
return FindValue<StreamViewType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator StreamViewType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TableStatus.
/// </summary>
public class TableStatus : ConstantClass
{
/// <summary>
/// Constant ACTIVE for TableStatus
/// </summary>
public static readonly TableStatus ACTIVE = new TableStatus("ACTIVE");
/// <summary>
/// Constant CREATING for TableStatus
/// </summary>
public static readonly TableStatus CREATING = new TableStatus("CREATING");
/// <summary>
/// Constant DELETING for TableStatus
/// </summary>
public static readonly TableStatus DELETING = new TableStatus("DELETING");
/// <summary>
/// Constant UPDATING for TableStatus
/// </summary>
public static readonly TableStatus UPDATING = new TableStatus("UPDATING");
/// <summary>
/// Default Constructor
/// </summary>
public TableStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TableStatus FindValue(string value)
{
return FindValue<TableStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TableStatus(string value)
{
return FindValue(value);
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Linq;
using System.ComponentModel;
using System.Text;
using NLog.Config;
using NLog.Internal;
using NLog.Common;
/// <summary>
/// Abstract interface that layouts must implement.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Few people will see this conflict.")]
[NLogConfigurationItem]
public abstract class Layout : ISupportsInitialize, IRenderable
{
/// <summary>
/// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/>
/// </summary>
private bool _isInitialized;
private bool _scannedForObjects;
/// <summary>
/// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread).
/// </summary>
/// <remarks>
/// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are
/// like that as well.
///
/// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output.
/// </remarks>
internal bool ThreadAgnostic { get; set; }
/// <summary>
/// Gets the level of stack trace information required for rendering.
/// </summary>
internal StackTraceUsage StackTraceUsage { get; private set; }
private const int MaxInitialRenderBufferLength = 16384;
private int _maxRenderedLength;
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Converts a given text to a <see cref="Layout" />.
/// </summary>
/// <param name="text">Text to be converted.</param>
/// <returns><see cref="SimpleLayout"/> object represented by the text.</returns>
public static implicit operator Layout([Localizable(false)] string text)
{
return FromString(text);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText)
{
return FromString(layoutText, ConfigurationItemFactory.Default);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText, ConfigurationItemFactory configurationItemFactory)
{
return new SimpleLayout(layoutText, configurationItemFactory);
}
/// <summary>
/// Precalculates the layout for the specified log event and stores the result
/// in per-log event cache.
///
/// Only if the layout doesn't have [ThreadAgnostic] and doens't contain layouts with [ThreadAgnostic].
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// Calling this method enables you to store the log event in a buffer
/// and/or potentially evaluate it in another thread even though the
/// layout may contain thread-dependent renderer.
/// </remarks>
public virtual void Precalculate(LogEventInfo logEvent)
{
if (!this.ThreadAgnostic)
{
this.Render(logEvent);
}
}
/// <summary>
/// Renders the event info in layout.
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <returns>String representing log event.</returns>
public string Render(LogEventInfo logEvent)
{
if (!this._isInitialized)
{
this.Initialize(this.LoggingConfiguration);
}
return this.GetFormattedMessage(logEvent);
}
internal void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target)
{
if (!this.ThreadAgnostic)
{
RenderAppendBuilder(logEvent, target, true);
}
}
/// <summary>
/// Renders the event info in layout to the provided target
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <param name="target">Appends the string representing log event to target</param>
/// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param>
internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder target, bool cacheLayoutResult = false)
{
if (!this._isInitialized)
{
this.Initialize(this.LoggingConfiguration);
}
if (!this.ThreadAgnostic)
{
string cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
target.Append(cachedValue);
return;
}
}
cacheLayoutResult = cacheLayoutResult && !this.ThreadAgnostic;
using (var localTarget = new AppendBuilderCreator(target, cacheLayoutResult))
{
RenderFormattedMessage(logEvent, localTarget.Builder);
if (cacheLayoutResult)
{
// when needed as it generates garbage
logEvent.AddCachedLayoutValue(this, localTarget.Builder.ToString());
}
}
}
/// <summary>
/// Valid default implementation of <see cref="GetFormattedMessage" />, when having implemented the optimized <see cref="RenderFormattedMessage"/>
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="reusableBuilder">StringBuilder to help minimize allocations [optional].</param>
/// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param>
/// <returns>The rendered layout.</returns>
internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder reusableBuilder = null, bool cacheLayoutResult = true)
{
if (!this.ThreadAgnostic)
{
string cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
return cachedValue;
}
}
int initialLength = this._maxRenderedLength;
if (initialLength > MaxInitialRenderBufferLength)
{
initialLength = MaxInitialRenderBufferLength;
}
var sb = reusableBuilder ?? new StringBuilder(initialLength);
RenderFormattedMessage(logEvent, sb);
if (sb.Length > this._maxRenderedLength)
{
this._maxRenderedLength = sb.Length;
}
if (cacheLayoutResult && !this.ThreadAgnostic)
{
return logEvent.AddCachedLayoutValue(this, sb.ToString());
}
else
{
return sb.ToString();
}
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="target"><see cref="StringBuilder"/> for the result</param>
protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
target.Append(GetFormattedMessage(logEvent) ?? string.Empty);
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
this.Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
this.Close();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
if (!this._isInitialized)
{
this.LoggingConfiguration = configuration;
this._isInitialized = true;
this._scannedForObjects = false;
this.InitializeLayout();
if (!this._scannedForObjects)
{
InternalLogger.Debug("Initialized Layout done but not scanned for objects");
PerformObjectScanning();
}
}
}
internal void PerformObjectScanning()
{
var objectGraphScannerList = ObjectGraphScanner.FindReachableObjects<object>(this);
// determine whether the layout is thread-agnostic
// layout is thread agnostic if it is thread-agnostic and
// all its nested objects are thread-agnostic.
this.ThreadAgnostic = objectGraphScannerList.All(item => item.GetType().IsDefined(typeof(ThreadAgnosticAttribute), true));
// determine the max StackTraceUsage, to decide if Logger needs to capture callsite
this.StackTraceUsage = StackTraceUsage.None; // Incase this Layout should implement IStackTraceUsage
this.StackTraceUsage = objectGraphScannerList.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(item => item == null ? StackTraceUsage.None : item.StackTraceUsage);
this._scannedForObjects = true;
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
if (this._isInitialized)
{
this.LoggingConfiguration = null;
this._isInitialized = false;
this.CloseLayout();
}
}
/// <summary>
/// Initializes the layout.
/// </summary>
protected virtual void InitializeLayout()
{
PerformObjectScanning();
}
/// <summary>
/// Closes the layout.
/// </summary>
protected virtual void CloseLayout()
{
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <returns>The rendered layout.</returns>
protected abstract string GetFormattedMessage(LogEventInfo logEvent);
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the Layout.</typeparam>
/// <param name="name"> Name of the Layout.</param>
public static void Register<T>(string name)
where T : Layout
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="layoutType"> Type of the Layout.</param>
/// <param name="name"> Name of the Layout.</param>
public static void Register(string name, Type layoutType)
{
ConfigurationItemFactory.Default.Layouts
.RegisterDefinition(name, layoutType);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Text;
#if !PocketPC
using System.Data.SqlClient;
using System.Xml.XPath;
#endif
namespace ASE.Xml
{
#if ASEPUBLIC
public class XmlIni
#else
internal class XmlIni
#endif
{
#region Static
private static string _fileNameS = "";
public static string FileName
{
get
{
if (_fileNameS == "")
{
#if !PocketPC
_fileNameS = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\user.config";
#else
_fileNameS = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\user.config";
#endif
_fileNameS = _fileNameS.Replace(@"file:\", "");
}
return _fileNameS;
}
set
{
_fileNameS = value;
_instance = null;
}
}
private static XmlIni _instance = null;
/// <summary>
/// Instance XmlIni
/// </summary>
public static XmlIni Instance
{
get
{
//if (_instance == null)
_instance = new XmlIni(_fileNameS, false);
return _instance;
}
set
{
_instance =value;
}
}
#endregion Static
#region Constructor
/// <summary>
/// Constructor. Create XmlIni with file ApplicationPath\user.config
/// </summary>
public XmlIni()
{
#if !PocketPC
_fileName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\user.config";
#else
_fileName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\user.config";
#endif
_fileName = _fileName.Replace(@"file:\", "");
}
/// <summary>
/// Constructor. Create XmlIni with file "fileName"
/// </summary>
/// <param name="fileName">Path to user config</param>
public XmlIni(string fileName): this()
{
if (fileName != "")
_fileName = fileName;
}
/// <summary>
/// Constructor. Create XmlIni with file "fileName"
/// </summary>
/// <param name="fileName">Path to user config</param>
/// <param name="isFixed"></param>
public XmlIni(string fileName, bool isFixed): this()
{
if (fileName != "")
_fileName = fileName;
_fixed = isFixed;
}
private string _fileName = "";
#endregion Constructor
#region path, attribute, defaultValue
private bool _fixed = true;
private string _lastDocLoad = "";
private XmlDocument _doc = null;
private XmlDocument XmlDoc
{
get
{
if (_fixed)
{
if ((_doc == null) || (_lastDocLoad != _fileName))
{
if (_doc == null)
_doc = new XmlDocument();
if (File.Exists(_fileName))
{
_lastDocLoad = _fileName;
_doc.Load(_fileName);
}
}
}
else
{
if (_doc == null)
_doc = new XmlDocument();
if (File.Exists(_fileName))
{
_doc.Load(_fileName);
}
}
return _doc;
}
}
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public string ReadString(string path, string attribute, string defaultValue)
{
string[] keys = path.Split('/');
if (keys == null)
return defaultValue;
if (keys.Length == 0)
return defaultValue;
if (!File.Exists(_fileName))
return defaultValue;
XmlDocument doc = XmlDoc;
//doc.Load(_fileName);
XmlNode node = doc["ASE.Tools.XmlIni"];
for(int i = 0; i < keys.Length; i++)
{
if (node == null)
return defaultValue;
if (keys[i] == "")
continue;
node = node[keys[i]];
}
if (node == null)
return defaultValue;
if (attribute == "")
attribute = "key";
if (attribute == "")
{
if (node.Value == "")
return defaultValue;
else
return node.Value;
}
XmlAttribute attr = node.Attributes[attribute];
if (attr == null)
return defaultValue;
if (attr.Value == "")
return defaultValue;
else
return attr.Value;
}
/// <summary>
/// Write string to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteString(string path, string attribute, string value)
{
string[] keys = path.Split('/');
if (keys == null)
return -1;
if (keys.Length == 0)
return -2;
XmlDocument doc = XmlDoc;
//if (File.Exists(_fileName))
//doc.Load(_fileName);
XmlNode node = doc["ASE.Tools.XmlIni"];
if (node == null)
{
node = doc.CreateNode(XmlNodeType.Element, "ASE.Tools.XmlIni", "");
doc.AppendChild(node);
}
for(int i = 0; i < keys.Length; i++)
{
if (keys[i] == "")
continue;
XmlNode newNode = node[keys[i]];
if (newNode == null)
{
newNode = doc.CreateNode(XmlNodeType.Element, keys[i], "");
node.AppendChild(newNode);
}
node = newNode;
}
if (attribute == "")
attribute = "key";
XmlAttribute attr = node.Attributes[attribute];
if (attr == null)
{
attr = doc.CreateAttribute(attribute);
node.Attributes.Append(attr);
}
attr.Value = value;
doc.Save(_fileName);
return 0;
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public int ReadInt(string path, string attribute, int defaultValue)
{
return int.Parse(ReadString(path, attribute, defaultValue.ToString()));
}
/// <summary>
/// Write int to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteInt(string path, string attribute, int value)
{
return WriteString(path, attribute, value.ToString());
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public long ReadLong(string path, string attribute, long defaultValue)
{
return long.Parse(ReadString(path, attribute, defaultValue.ToString()));
}
/// <summary>
/// Write long to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteLong(string path, string attribute, long value)
{
return WriteString(path, attribute, value.ToString());
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public DateTime ReadDateTime(string path, string attribute, DateTime defaultValue)
{
return DateTime.Parse(ReadString(path, attribute, defaultValue.ToString()));
}
/// <summary>
/// Write DateTime to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteDateTime(string path, string attribute, DateTime value)
{
return WriteString(path, attribute, value.ToString());
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public bool ReadBoolean(string path, string attribute, bool defaultValue)
{
return ReadInt(path, attribute, (defaultValue) ? 1:0) == 1;
}
/// <summary>
/// Write Boolean to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteBoolean(string path, string attribute, bool value)
{
return WriteString(path, attribute, (value) ? "1":"0");
}
#endregion path, attribute, defaultValue
#region path, defaultValue
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public string ReadString(string path, string defaultValue)
{
return ReadString(path, "", defaultValue);
}
/// <summary>
/// Write string to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteString(string path, string value)
{
return WriteString(path, "", value);
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public int ReadInt(string path, int defaultValue)
{
return int.Parse(ReadString(path, "", defaultValue.ToString()));
}
/// <summary>
/// Write int to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteInt(string path, int value)
{
return WriteString(path, "", value.ToString());
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public long ReadLong(string path, long defaultValue)
{
return long.Parse(ReadString(path, defaultValue.ToString()));
}
/// <summary>
/// Write long to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteLong(string path, long value)
{
return WriteString(path, value.ToString());
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public DateTime ReadDateTime(string path, DateTime defaultValue)
{
return DateTime.Parse(ReadString(path, DateTime.MinValue.ToString()));
}
/// <summary>
/// Write DateTime to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteDateTime(string path, long value)
{
return WriteString(path, value.ToString());
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public bool ReadBoolean(string path, bool defaultValue)
{
return ReadInt(path, (defaultValue) ? 1:0) == 1;
}
/// <summary>
/// Write Boolean to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public int WriteBoolean(string path, bool value)
{
return WriteString(path, (value) ? "1":"0");
}
#endregion path, defaultValue
#region path
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or ""</returns>
public string ReadString(string path)
{
return ReadString(path, "", "");
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public int ReadInt(string path)
{
return int.Parse(ReadString(path, "", "0"));
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public long ReadLong(string path)
{
return long.Parse(ReadString(path, "0"));
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or DateTime.MinValue</returns>
public DateTime ReadDateTime(string path)
{
return DateTime.Parse(ReadString(path, DateTime.MinValue.ToString()));
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or DateTime.MinValue</returns>
public bool ReadBoolean(string path)
{
return int.Parse(ReadString(path, "0")) == 1;
}
#endregion path
#region Delete
public int Delete(string path, string attribute)
{
string[] keys = path.Split('/');
if (keys == null)
return -1;
if (keys.Length == 0)
return -2;
if (!File.Exists(_fileName))
return -3;
XmlDocument doc = XmlDoc;
//doc.Load(_fileName);
XmlNode node = doc["ASE.Tools.XmlIni"];
for(int i = 0; i < keys.Length; i++)
{
if (node == null)
return -4;
node = node[keys[i]];
}
if (node == null)
return -5;
if (attribute == "")
attribute = "key";
XmlAttribute attr = node.Attributes[attribute];
if (attr == null)
return -6;
node.Attributes.Remove(attr);
doc.Save(_fileName);
return 0;
}
public int Delete(string path)
{
string[] keys = path.Split('/');
if (keys == null)
return -1;
if (keys.Length == 0)
return -2;
if (!File.Exists(_fileName))
return -3;
XmlDocument doc = XmlDoc;
//doc.Load(_fileName);
XmlNode node = doc["ASE.Tools.XmlIni"];
for(int i = 0; i < keys.Length; i++)
{
if (node == null)
return -4;
if ((i == keys.Length - 1) && (node[keys[i]] != null))
{
node.RemoveChild(node[keys[i]]);
doc.Save(_fileName);
return 0;
}
node = node[keys[i]];
}
return -5;
}
#endregion Delete
#region GetLists
public string[] GetPathes(string rootPath)
{
string[] keys = rootPath.Split('/');
if (keys == null)
return new string[0];
if (!File.Exists(_fileName))
return new string[0];
XmlDocument doc = XmlDoc;
//doc.Load(_fileName);
XmlNode node = doc["ASE.Tools.XmlIni"];
for(int i = 0; i < keys.Length; i++)
{
if (node == null)
return new string[0];
if (keys[i] == "")
continue;
node = node[keys[i]];
}
if (node == null)
return new string[0];
ArrayList list = new ArrayList();
foreach (XmlNode child in node.ChildNodes)
list.Add(child.Name);
return (string[]) list.ToArray(typeof(string));
}
public string[] GetAttributes(string path)
{
string[] keys = path.Split('/');
if (keys == null)
return new string[0];
if (!File.Exists(_fileName))
return new string[0];
XmlDocument doc = XmlDoc;
//doc.Load(_fileName);
XmlNode node = doc["ASE.Tools.XmlIni"];
for(int i = 0; i < keys.Length; i++)
{
if (node == null)
return new string[0];
if (keys[i] == "")
continue;
node = node[keys[i]];
}
ArrayList list = new ArrayList();
foreach (XmlAttribute item in node.Attributes)
list.Add(item.Name);
return (string[]) list.ToArray(typeof(string));
}
#endregion GetLists
}
#if ASEPUBLIC
public class XmlIniStatic
#else
internal class XmlIniStatic
#endif
{
#region path, attribute, defaultValue
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static string ReadString(string path, string attribute, string defaultValue)
{
return XmlIni.Instance.ReadString(path, attribute, defaultValue);
}
/// <summary>
/// Write string to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteString(string path, string attribute, string value)
{
return XmlIni.Instance.WriteString(path, attribute, value);
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static int ReadInt(string path, string attribute, int defaultValue)
{
return XmlIni.Instance.ReadInt(path, attribute, defaultValue);
}
/// <summary>
/// Write int to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteInt(string path, string attribute, int value)
{
return XmlIni.Instance.WriteString(path, attribute, value.ToString());
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static long ReadLong(string path, string attribute, long defaultValue)
{
return XmlIni.Instance.ReadLong(path, attribute, defaultValue);
}
/// <summary>
/// Write long to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteLong(string path, string attribute, long value)
{
return XmlIni.Instance.WriteLong(path, attribute, value);
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static DateTime ReadDateTime(string path, string attribute, DateTime defaultValue)
{
return XmlIni.Instance.ReadDateTime(path, attribute, defaultValue);
}
/// <summary>
/// Write DateTime to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteDateTime(string path, string attribute, DateTime value)
{
return XmlIni.Instance.WriteDateTime(path, attribute, value);
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static bool ReadBoolean(string path, string attribute, bool defaultValue)
{
return XmlIni.Instance.ReadBoolean(path, attribute, defaultValue);
}
/// <summary>
/// Write Boolean to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteBoolean(string path, string attribute, bool value)
{
return XmlIni.Instance.WriteBoolean(path, attribute, value);
}
#endregion path, attribute, defaultValue
#region path, defaultValue
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static string ReadString(string path, string defaultValue)
{
return XmlIni.Instance.ReadString(path, defaultValue);
}
/// <summary>
/// Write string to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteString(string path, string value)
{
return XmlIni.Instance.WriteString(path, value);
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static int ReadInt(string path, int defaultValue)
{
return XmlIni.Instance.ReadInt(path, defaultValue);
}
/// <summary>
/// Write int to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteInt(string path, int value)
{
return XmlIni.Instance.WriteInt(path, value);
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static long ReadLong(string path, long defaultValue)
{
return XmlIni.Instance.ReadLong(path, defaultValue);
}
/// <summary>
/// Write long to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteLong(string path, long value)
{
return XmlIni.Instance.WriteLong(path, value);
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static DateTime ReadDateTime(string path, DateTime defaultValue)
{
return XmlIni.Instance.ReadDateTime(path, defaultValue);
}
/// <summary>
/// Write DateTime to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteDateTime(string path, long value)
{
return XmlIni.Instance.WriteDateTime(path, value);
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static bool ReadBoolean(string path, bool defaultValue)
{
return XmlIni.Instance.ReadBoolean(path, defaultValue);
}
/// <summary>
/// Write Boolean to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteBoolean(string path, bool value)
{
return XmlIni.Instance.WriteBoolean(path, value);
}
#endregion path, defaultValue
#region path
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or ""</returns>
public static string ReadString(string path)
{
return XmlIni.Instance.ReadString(path);
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public static int ReadInt(string path)
{
return XmlIni.Instance.ReadInt(path);
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public static long ReadLong(string path)
{
return XmlIni.Instance.ReadLong(path);
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or DateTime.MinValue</returns>
public static DateTime ReadDateTime(string path)
{
return XmlIni.Instance.ReadDateTime(path);
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public static bool ReadBoolean(string path)
{
return XmlIni.Instance.ReadBoolean(path);
}
#endregion path
#region Delete
public static int Delete(string path, string attribute)
{
return XmlIni.Instance.Delete(path, attribute);
}
public static int Delete(string path)
{
return XmlIni.Instance.Delete(path);
}
#endregion Delete
#region GetLists
public static string[] GetPathes(string rootPath)
{
return XmlIni.Instance.GetPathes(rootPath);
}
public static string[] GetAttributes(string path)
{
return XmlIni.Instance.GetAttributes(path);
}
#endregion GetLists
public static void Refresh()
{
XmlIni.Instance = null;
}
}
#if ASEPUBLIC
public class IniFileS
#else
internal class IniFileS
#endif
{
#region path, attribute, defaultValue
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static string ReadString(string path, string attribute, string defaultValue)
{
return XmlIni.Instance.ReadString(path, attribute, defaultValue);
}
/// <summary>
/// Write string to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteString(string path, string attribute, string value)
{
return XmlIni.Instance.WriteString(path, attribute, value);
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static int ReadInt(string path, string attribute, int defaultValue)
{
return XmlIni.Instance.ReadInt(path, attribute, defaultValue);
}
/// <summary>
/// Write int to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteInt(string path, string attribute, int value)
{
return XmlIni.Instance.WriteString(path, attribute, value.ToString());
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static long ReadLong(string path, string attribute, long defaultValue)
{
return XmlIni.Instance.ReadLong(path, attribute, defaultValue);
}
/// <summary>
/// Write long to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteLong(string path, string attribute, long value)
{
return XmlIni.Instance.WriteLong(path, attribute, value);
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static DateTime ReadDateTime(string path, string attribute, DateTime defaultValue)
{
return XmlIni.Instance.ReadDateTime(path, attribute, defaultValue);
}
/// <summary>
/// Write DateTime to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteDateTime(string path, string attribute, DateTime value)
{
return XmlIni.Instance.WriteDateTime(path, attribute, value);
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="defaultValue">Value returned if path or attribute exits</param>
/// <returns>Readed or default value</returns>
public static bool ReadBoolean(string path, string attribute, bool defaultValue)
{
return XmlIni.Instance.ReadBoolean(path, attribute, defaultValue);
}
/// <summary>
/// Write Boolean to file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <param name="attribute">Attribute if need</param>
/// <param name="value">Value</param>
/// <returns>0 if success</returns>
public static int WriteBoolean(string path, string attribute, bool value)
{
return XmlIni.Instance.WriteBoolean(path, attribute, value);
}
#endregion path, attribute, defaultValue
#region path
/// <summary>
/// Read string from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or ""</returns>
public static string ReadString(string path)
{
return XmlIni.Instance.ReadString(path);
}
/// <summary>
/// Read int from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public static int ReadInt(string path)
{
return XmlIni.Instance.ReadInt(path);
}
/// <summary>
/// Read long from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public static long ReadLong(string path)
{
return XmlIni.Instance.ReadLong(path);
}
/// <summary>
/// Read DateTime from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or DateTime.MinValue</returns>
public static DateTime ReadDateTime(string path)
{
return XmlIni.Instance.ReadDateTime(path);
}
/// <summary>
/// Read Boolean from file
/// </summary>
/// <param name="path">Key path "myOption/mySubOption"</param>
/// <returns>Readed value or 0</returns>
public static bool ReadBoolean(string path)
{
return XmlIni.Instance.ReadBoolean(path);
}
#endregion path
#region Delete
public static int Delete(string path, string attribute)
{
return XmlIni.Instance.Delete(path, attribute);
}
public static int Delete(string path)
{
return XmlIni.Instance.Delete(path);
}
#endregion Delete
#region GetLists
public static string[] GetPathes(string rootPath)
{
return XmlIni.Instance.GetPathes(rootPath);
}
public static string[] GetAttributes(string path)
{
return XmlIni.Instance.GetAttributes(path);
}
#endregion GetLists
public static void Refresh()
{
XmlIni.Instance = null;
}
}
#if !PocketPC
public class Crypt
{
public static byte[] Encrypt(byte[] data, string password)
{
SymmetricAlgorithm sa = Rijndael.Create();
ICryptoTransform ct = sa.CreateEncryptor(
(new PasswordDeriveBytes(password, null)).GetBytes(16),
new byte[16]);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
public static string Encrypt(string data, string password)
{
return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data), password));
}
static public byte[] Decrypt(byte[] data, string password)
{
BinaryReader br = new BinaryReader(InternalDecrypt(data, password));
return br.ReadBytes((int)br.BaseStream.Length);
}
static public string Decrypt(string data, string password)
{
CryptoStream cs = InternalDecrypt(Convert.FromBase64String(data), password);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
static CryptoStream InternalDecrypt(byte[] data, string password)
{
SymmetricAlgorithm sa = Rijndael.Create();
ICryptoTransform ct = sa.CreateDecryptor(
(new PasswordDeriveBytes(password, null)).GetBytes(16),
new byte[16]);
MemoryStream ms = new MemoryStream(data);
return new CryptoStream(ms, ct, CryptoStreamMode.Read);
}
}
#endif
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.