context stringlengths 2.52k 185k | gt stringclasses 1 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.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Calls the specified web service on each log message.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// The web service must implement a method that accepts a number of string parameters.
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" />
/// <p>The example web service that works with this example is shown below</p>
/// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" />
/// </example>
[Target("WebService")]
public sealed class WebServiceTarget : MethodCallTargetBase
{
private const string SoapEnvelopeNamespaceUri = "http://schemas.xmlsoap.org/soap/envelope/";
private const string Soap12EnvelopeNamespaceUri = "http://www.w3.org/2003/05/soap-envelope";
/// <summary>
/// dictionary that maps a concrete <see cref="HttpPostFormatterBase"/> implementation
/// to a specific <see cref="WebServiceProtocol"/>-value.
/// </summary>
private static Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>> _postFormatterFactories =
new Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>>()
{
{ WebServiceProtocol.Soap11, t => new HttpPostSoap11Formatter(t)},
{ WebServiceProtocol.Soap12, t => new HttpPostSoap12Formatter(t)},
{ WebServiceProtocol.HttpPost, t => new HttpPostFormEncodedFormatter(t)},
{ WebServiceProtocol.JsonPost, t => new HttpPostJsonFormatter(t)},
{ WebServiceProtocol.XmlPost, t => new HttpPostXmlDocumentFormatter(t)},
};
/// <summary>
/// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
/// </summary>
public WebServiceTarget()
{
Protocol = WebServiceProtocol.Soap11;
//default NO utf-8 bom
const bool writeBOM = false;
Encoding = new UTF8Encoding(writeBOM);
IncludeBOM = writeBOM;
OptimizeBufferReuse = true;
Headers = new List<MethodCallParameter>();
}
/// <summary>
/// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
/// </summary>
/// <param name="name">Name of the target</param>
public WebServiceTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the web service URL.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public Uri Url { get; set; }
/// <summary>
/// Gets or sets the Web service method name. Only used with Soap.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string MethodName { get; set; }
/// <summary>
/// Gets or sets the Web service namespace. Only used with Soap.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string Namespace { get; set; }
/// <summary>
/// Gets or sets the protocol to be used when calling web service.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
[DefaultValue("Soap11")]
public WebServiceProtocol Protocol
{
get => _activeProtocol.Key;
set => _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(value, null);
}
private KeyValuePair<WebServiceProtocol, HttpPostFormatterBase> _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>();
#if !SILVERLIGHT
/// <summary>
/// Gets or sets the proxy configuration when calling web service
/// </summary>
/// <docgen category='Web Service Options' order='10' />
[DefaultValue("DefaultWebProxy")]
public WebServiceProxyType ProxyType
{
get => _activeProxy.Key;
set => _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(value, null);
}
private KeyValuePair<WebServiceProxyType, IWebProxy> _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>();
#endif
/// <summary>
/// Gets or sets the custom proxy address, include port separated by a colon
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string ProxyAddress { get; set; }
/// <summary>
/// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property.
///
/// This will only work for UTF-8.
/// </summary>
public bool? IncludeBOM { get; set; }
/// <summary>
/// Gets or sets the encoding.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs)
/// </summary>
/// <value>A value of <c>true</c> if Rfc3986; otherwise, <c>false</c> for legacy Rfc2396.</value>
/// <docgen category='Web Service Options' order='10' />
public bool EscapeDataRfc3986 { get; set; }
/// <summary>
/// Gets or sets a value whether escaping be done according to the old NLog style (Very non-standard)
/// </summary>
/// <value>A value of <c>true</c> if legacy encoding; otherwise, <c>false</c> for standard UTF8 encoding.</value>
/// <docgen category='Web Service Options' order='10' />
public bool EscapeDataNLogLegacy { get; set; }
/// <summary>
/// Gets or sets the name of the root XML element,
/// if POST of XML document chosen.
/// If so, this property must not be <c>null</c>.
/// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>).
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string XmlRoot { get; set; }
/// <summary>
/// Gets or sets the (optional) root namespace of the XML document,
/// if POST of XML document chosen.
/// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>).
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string XmlRootNamespace { get; set; }
/// <summary>
/// Gets the array of parameters to be passed.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
[ArrayParameter(typeof(MethodCallParameter), "header")]
public IList<MethodCallParameter> Headers { get; private set; }
#if !SILVERLIGHT
/// <summary>
/// Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in <see cref="Headers"/> parameters)
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public bool PreAuthenticate { get; set; }
#endif
private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter();
private bool _foundEnableGroupLayout;
private bool _onlyEnableGroupLayout; // Attempt to minimize Parameter-Array-Key-allocations
/// <summary>
/// Initializes the target
/// </summary>
protected override void InitializeTarget()
{
_foundEnableGroupLayout = false;
_onlyEnableGroupLayout = true;
base.InitializeTarget();
for (int i = 0; i < Parameters.Count; ++i)
{
if (Parameters[i].EnableGroupLayout)
{
_foundEnableGroupLayout = true;
if (!_onlyEnableGroupLayout)
break;
}
else
{
_onlyEnableGroupLayout = false;
}
}
}
/// <summary>
/// Writes an array of logging events to the log target
/// </summary>
/// <param name="logEvents">Array of logging events to write</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
if (!_foundEnableGroupLayout)
{
base.Write(logEvents);
}
else if (logEvents.Count == 1)
{
base.Write(logEvents[0]);
}
else
{
if (Headers != null && Headers.Count > 0)
{
if (_convetToHeaderArrayDelegate == null)
_convetToHeaderArrayDelegate = (l) => ConvertToHeaderArray(l.LogEvent);
var headerBuckets = logEvents.BucketSort(_convetToHeaderArrayDelegate, ArrayDeepEqualityComparer<string>.Default);
foreach (var headerBucket in headerBuckets)
{
DoGroupInvoke(headerBucket.Value, headerBucket.Key);
}
}
else
{
DoGroupInvoke(logEvents, ArrayHelper.Empty<string>());
}
}
}
private SortHelpers.KeySelector<AsyncLogEventInfo, string[]> _convetToHeaderArrayDelegate;
string[] ConvertToHeaderArray(LogEventInfo logEvent)
{
string[] headers = new string[Headers.Count];
for (int i = 0; i < Headers.Count; i++)
{
headers[i] = RenderLogEvent(Headers[i].Layout, logEvent);
}
return headers;
}
/// <summary>
/// Writes a group of LogEvents in a single WebRequest
/// </summary>
/// <param name="logEvents">Array of logging events to write</param>
/// <param name="headerValues">WebRequest Header Values matching the LogEvents group</param>
private void DoGroupInvoke(IList<AsyncLogEventInfo> logEvents, string[] headerValues)
{
if (_convetToParameterArrayDelegate == null)
_convetToParameterArrayDelegate = (l) => ConvetToParameterArray(l.LogEvent, true);
var parameterBuckets = _onlyEnableGroupLayout
? new SortHelpers.ReadOnlySingleBucketDictionary<object[], IList<AsyncLogEventInfo>>(new KeyValuePair<object[], IList<AsyncLogEventInfo>>(new object[Parameters.Count], logEvents), ArrayDeepEqualityComparer<object>.Default)
: logEvents.BucketSort(_convetToParameterArrayDelegate, ArrayDeepEqualityComparer<object>.Default);
foreach (var bucket in parameterBuckets)
{
for (int i = 0; i < Parameters.Count; ++i)
{
var param = Parameters[i];
if (param.EnableGroupLayout)
{
bucket.Key[i] = ConvertParameterGroupValue(bucket.Value, param);
}
}
if (bucket.Value.Count > 1)
{
AsyncContinuation[] groupContinuations = new AsyncContinuation[bucket.Value.Count];
for (int i = 0; i < groupContinuations.Length; ++i)
{
groupContinuations[i] = bucket.Value[i].Continuation;
}
AsyncContinuation groupCompleted = (ex) =>
{
for (int i = 0; i < groupContinuations.Length; ++i)
try
{
groupContinuations[i].Invoke(ex);
}
catch (Exception ex2)
{
InternalLogger.Trace(ex2, "Exception in Webservice invoke, but ignoring it.");
/* Nothing to do about it */
};
};
DoGroupInvokeAsync(headerValues, bucket.Key, groupCompleted);
}
else
{
DoGroupInvokeAsync(headerValues, bucket.Key, bucket.Value[0].Continuation);
}
}
}
private SortHelpers.KeySelector<AsyncLogEventInfo, object[]> _convetToParameterArrayDelegate;
class ArrayDeepEqualityComparer<TValue> : IEqualityComparer<TValue[]>
{
public static readonly ArrayDeepEqualityComparer<TValue> Default = new ArrayDeepEqualityComparer<TValue>();
public bool Equals(TValue[] x, TValue[] y)
{
if (x.Length != y.Length)
return false;
object xval, yval;
for (int i = 0; i < x.Length; ++i)
{
xval = x[i];
yval = y[i];
if (xval != null && yval != null)
{
if (!xval.Equals(yval))
return false;
}
else if (!ReferenceEquals(xval, yval))
{
return false;
}
}
return true;
}
public int GetHashCode(TValue[] obj)
{
int hashCode = obj.Length.GetHashCode();
for (int i = 0; i < obj.Length; ++i)
{
if (obj[i] != null)
hashCode = hashCode ^ obj[i].GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// Calls the target method. Must be implemented in concrete classes.
/// </summary>
/// <param name="parameters">Method call parameters.</param>
protected override void DoInvoke(object[] parameters)
{
// method is not used, instead asynchronous overload will be used
throw new NotImplementedException();
}
/// <summary>
/// Calls the target DoInvoke method, and handles AsyncContinuation callback
/// </summary>
/// <param name="parameters">Method call parameters.</param>
/// <param name="continuation">The continuation.</param>
protected override void DoInvoke(object[] parameters, AsyncContinuation continuation)
{
var request = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters));
DoInvoke(parameters, request, continuation);
}
/// <summary>
/// Invokes the web service method.
/// </summary>
/// <param name="parameters">Parameters to be passed.</param>
/// <param name="logEvent">The logging event.</param>
protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent)
{
var request = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters));
if (Headers != null && Headers.Count > 0)
{
for (int i = 0; i < Headers.Count; i++)
{
string headerValue = RenderLogEvent(Headers[i].Layout, logEvent.LogEvent);
if (headerValue == null)
continue;
request.Headers[Headers[i].Name] = headerValue;
}
}
DoInvoke(parameters, request, logEvent.Continuation);
}
void DoGroupInvokeAsync(string[] headerValues, object[] parameters, AsyncContinuation continuation)
{
var request = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters));
if (Headers != null && Headers.Count > 0)
{
for (int i = 0; i < Headers.Count; i++)
{
string headerValue = headerValues[i];
if (headerValue == null)
continue;
request.Headers[Headers[i].Name] = headerValue;
}
}
DoInvoke(parameters, request, continuation);
}
void DoInvoke(object[] parameters, HttpWebRequest request, AsyncContinuation continuation)
{
Func<AsyncCallback, IAsyncResult> begin = (r) => request.BeginGetRequestStream(r, null);
Func<IAsyncResult, Stream> getStream = request.EndGetRequestStream;
#if !SILVERLIGHT
switch (ProxyType)
{
case WebServiceProxyType.NoProxy:
request.Proxy = null;
break;
#if !NETSTANDARD1_0
case WebServiceProxyType.AutoProxy:
if (_activeProxy.Value == null)
{
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
_activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy);
}
request.Proxy = _activeProxy.Value;
break;
case WebServiceProxyType.ProxyAddress:
if (!string.IsNullOrEmpty(ProxyAddress))
{
if (_activeProxy.Value == null)
{
IWebProxy proxy = new WebProxy(ProxyAddress, true);
_activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy);
}
request.Proxy = _activeProxy.Value;
}
break;
#endif
}
#endif
#if !SILVERLIGHT && !NETSTANDARD1_0
if (PreAuthenticate || ProxyType == WebServiceProxyType.AutoProxy)
{
request.PreAuthenticate = true;
}
#endif
DoInvoke(parameters, continuation, request, begin, getStream);
}
internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc,
Func<IAsyncResult, Stream> getStreamFunc)
{
Stream postPayload = null;
if (Protocol == WebServiceProtocol.HttpGet)
{
PrepareGetRequest(request);
}
else
{
if (_activeProtocol.Value == null)
_activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(Protocol, _postFormatterFactories[Protocol](this));
postPayload = _activeProtocol.Value.PrepareRequest(request, parameters);
}
var sendContinuation = CreateSendContinuation(continuation, request);
PostPayload(continuation, beginFunc, getStreamFunc, postPayload, sendContinuation);
}
private AsyncContinuation CreateSendContinuation(AsyncContinuation continuation, HttpWebRequest request)
{
AsyncContinuation sendContinuation =
ex =>
{
if (ex != null)
{
DoInvokeCompleted(continuation, ex);
return;
}
try
{
request.BeginGetResponse(
r =>
{
try
{
using (var response = request.EndGetResponse(r))
{
}
DoInvokeCompleted(continuation, null);
}
catch (Exception ex2)
{
InternalLogger.Error(ex2, "Error when sending to Webservice: {0}", Name);
if (ex2.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
DoInvokeCompleted(continuation, ex2);
}
},
null);
}
catch (Exception ex2)
{
InternalLogger.Error(ex2, "Error when sending to Webservice: {0}", Name);
if (ex2.MustBeRethrown())
{
throw;
}
DoInvokeCompleted(continuation, ex2);
}
};
return sendContinuation;
}
private void PostPayload(AsyncContinuation continuation, Func<AsyncCallback, IAsyncResult> beginFunc, Func<IAsyncResult, Stream> getStreamFunc, Stream postPayload, AsyncContinuation sendContinuation)
{
if (postPayload != null && postPayload.Length > 0)
{
postPayload.Position = 0;
try
{
_pendingManualFlushList.BeginOperation();
beginFunc(
result =>
{
try
{
using (Stream stream = getStreamFunc(result))
{
WriteStreamAndFixPreamble(postPayload, stream, IncludeBOM, Encoding);
postPayload.Dispose();
}
sendContinuation(null);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error when sending to Webservice: {0}", Name);
if (ex.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
postPayload.Dispose();
DoInvokeCompleted(continuation, ex);
}
});
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error when sending to Webservice: {0}", Name);
if (ex.MustBeRethrown())
{
throw;
}
DoInvokeCompleted(continuation, ex);
}
}
else
{
_pendingManualFlushList.BeginOperation();
sendContinuation(null);
}
}
private void DoInvokeCompleted(AsyncContinuation continuation, Exception ex)
{
_pendingManualFlushList.CompleteOperation(ex);
continuation(ex);
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
_pendingManualFlushList.RegisterCompletionNotification(asyncContinuation).Invoke(null);
}
/// <summary>
/// Closes the target.
/// </summary>
protected override void CloseTarget()
{
_pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests?
base.CloseTarget();
}
/// <summary>
/// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol.
/// </summary>
/// <param name="parameterValues"></param>
/// <returns></returns>
private Uri BuildWebServiceUrl(object[] parameterValues)
{
if (Protocol != WebServiceProtocol.HttpGet)
{
return Url;
}
//if the protocol is HttpGet, we need to add the parameters to the query string of the url
string queryParameters = string.Empty;
using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None)
{
StringBuilder sb = targetBuilder.Result ?? new StringBuilder();
BuildWebServiceQueryParameters(parameterValues, sb);
queryParameters = sb.ToString();
}
var builder = new UriBuilder(Url);
//append our query string to the URL following
//the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx
if (builder.Query != null && builder.Query.Length > 1)
{
builder.Query = string.Concat(builder.Query.Substring(1), "&", queryParameters);
}
else
{
builder.Query = queryParameters;
}
return builder.Uri;
}
private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb)
{
UrlHelper.EscapeEncodingFlag encodingFlags = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986);
string separator = string.Empty;
for (int i = 0; i < Parameters.Count; i++)
{
sb.Append(separator);
sb.Append(Parameters[i].Name);
sb.Append("=");
string parameterValue = XmlHelper.XmlConvertToString(parameterValues[i]);
if (!string.IsNullOrEmpty(parameterValue))
{
UrlHelper.EscapeDataEncode(parameterValue, sb, encodingFlags);
}
separator = "&";
}
}
private void PrepareGetRequest(HttpWebRequest request)
{
request.Method = "GET";
}
/// <summary>
/// Write from input to output. Fix the UTF-8 bom
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="writeUtf8BOM"></param>
/// <param name="encoding"></param>
private static void WriteStreamAndFixPreamble(Stream input, Stream output, bool? writeUtf8BOM, Encoding encoding)
{
//only when utf-8 encoding is used, the Encoding preamble is optional
var nothingToDo = writeUtf8BOM == null || !(encoding is UTF8Encoding);
const int preambleSize = 3;
if (!nothingToDo)
{
//it's UTF-8
var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize;
//BOM already in Encoding.
nothingToDo = writeUtf8BOM.Value && hasBomInEncoding;
//Bom already not in Encoding
nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding;
}
var offset = nothingToDo ? 0 : preambleSize;
input.CopyWithOffset(output, offset);
}
/// <summary>
/// base class for POST formatters, that
/// implement former <c>PrepareRequest()</c> method,
/// that creates the content for
/// the requested kind of HTTP request
/// </summary>
private abstract class HttpPostFormatterBase
{
protected HttpPostFormatterBase(WebServiceTarget target)
{
Target = target;
}
protected abstract string ContentType { get; }
protected WebServiceTarget Target { get; private set; }
public MemoryStream PrepareRequest(HttpWebRequest request, object[] parameterValues)
{
InitRequest(request);
var ms = new MemoryStream();
WriteContent(ms, parameterValues);
return ms;
}
protected virtual void InitRequest(HttpWebRequest request)
{
request.Method = "POST";
request.ContentType = string.Concat(ContentType, "; charset=", Target.Encoding.WebName);
}
protected abstract void WriteContent(MemoryStream ms, object[] parameterValues);
}
private class HttpPostFormEncodedFormatter : HttpPostTextFormatterBase
{
readonly UrlHelper.EscapeEncodingFlag _encodingFlags;
public HttpPostFormEncodedFormatter(WebServiceTarget target) : base(target)
{
_encodingFlags = UrlHelper.GetUriStringEncodingFlags(target.EscapeDataNLogLegacy, true, target.EscapeDataRfc3986);
}
protected override string ContentType => "application/x-www-form-urlencoded";
protected override string Separator => "&";
protected override void AppendFormattedParameter(StringBuilder builder, MethodCallParameter parameter, object value)
{
builder.Append(parameter.Name);
builder.Append('=');
string parameterValue = XmlHelper.XmlConvertToString(value);
if (!string.IsNullOrEmpty(parameterValue))
{
UrlHelper.EscapeDataEncode(parameterValue, builder, _encodingFlags);
}
}
}
private class HttpPostJsonFormatter : HttpPostTextFormatterBase
{
private IJsonConverter JsonConverter => _jsonConverter ?? (_jsonConverter = ConfigurationItemFactory.Default.JsonConverter);
private IJsonConverter _jsonConverter = null;
public HttpPostJsonFormatter(WebServiceTarget target) : base(target)
{
}
protected override string ContentType => "application/json";
protected override string Separator => ",";
protected override void BeginFormattedMessage(StringBuilder builder)
{
builder.Append('{');
}
protected override void EndFormattedMessage(StringBuilder builder)
{
builder.Append('}');
}
protected override void AppendFormattedParameter(StringBuilder builder, MethodCallParameter parameter, object value)
{
builder.Append('"');
builder.Append(parameter.Name);
builder.Append("\":");
JsonConverter.SerializeObject(value, builder);
}
}
private class HttpPostSoap11Formatter : HttpPostSoapFormatterBase
{
public HttpPostSoap11Formatter(WebServiceTarget target) : base(target)
{
}
protected override string SoapEnvelopeNamespace => SoapEnvelopeNamespaceUri;
protected override string SoapName => "soap";
protected override void InitRequest(HttpWebRequest request)
{
base.InitRequest(request);
string soapAction;
if (Target.Namespace.EndsWith("/", StringComparison.Ordinal))
{
soapAction = string.Concat(Target.Namespace, Target.MethodName);
}
else
{
soapAction = string.Concat(Target.Namespace, "/", Target.MethodName);
}
request.Headers["SOAPAction"] = soapAction;
}
}
private class HttpPostSoap12Formatter : HttpPostSoapFormatterBase
{
public HttpPostSoap12Formatter(WebServiceTarget target) : base(target)
{
}
protected override string SoapEnvelopeNamespace => Soap12EnvelopeNamespaceUri;
protected override string SoapName => "soap12";
}
private abstract class HttpPostSoapFormatterBase : HttpPostXmlFormatterBase
{
private readonly XmlWriterSettings _xmlWriterSettings;
protected HttpPostSoapFormatterBase(WebServiceTarget target) : base(target)
{
_xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding };
}
protected abstract string SoapEnvelopeNamespace { get; }
protected abstract string SoapName { get; }
protected override void WriteContent(MemoryStream ms, object[] parameterValues)
{
XmlWriter xtw = XmlWriter.Create(ms, _xmlWriterSettings);
xtw.WriteStartElement(SoapName, "Envelope", SoapEnvelopeNamespace);
xtw.WriteStartElement("Body", SoapEnvelopeNamespace);
xtw.WriteStartElement(Target.MethodName, Target.Namespace);
WriteAllParametersToCurrenElement(xtw, parameterValues);
xtw.WriteEndElement(); // methodname
xtw.WriteEndElement(); // Body
xtw.WriteEndElement(); // soap:Envelope
xtw.Flush();
}
}
private abstract class HttpPostTextFormatterBase : HttpPostFormatterBase
{
readonly ReusableBuilderCreator _reusableStringBuilder = new ReusableBuilderCreator();
readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024);
readonly byte[] _encodingPreamble;
protected HttpPostTextFormatterBase(WebServiceTarget target) : base(target)
{
_encodingPreamble = target.Encoding.GetPreamble();
}
protected abstract string Separator { get; }
protected virtual void BeginFormattedMessage(StringBuilder builder)
{
}
protected abstract void AppendFormattedParameter(StringBuilder builder, MethodCallParameter parameter, object value);
protected virtual void EndFormattedMessage(StringBuilder builder)
{
}
protected override void WriteContent(MemoryStream ms, object[] parameterValues)
{
lock (_reusableStringBuilder)
{
using (var targetBuilder = _reusableStringBuilder.Allocate())
{
bool first = true;
BeginFormattedMessage(targetBuilder.Result);
for (int i = 0; i < Target.Parameters.Count; i++)
{
if (!first)
targetBuilder.Result.Append(Separator);
else
first = false;
AppendFormattedParameter(targetBuilder.Result, Target.Parameters[i], parameterValues[i]);
}
EndFormattedMessage(targetBuilder.Result);
using (var transformBuffer = _reusableEncodingBuffer.Allocate())
{
if (_encodingPreamble.Length > 0)
ms.Write(_encodingPreamble, 0, _encodingPreamble.Length);
targetBuilder.Result.CopyToStream(ms, Target.Encoding, transformBuffer.Result);
}
}
}
}
}
private class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase
{
private readonly XmlWriterSettings _xmlWriterSettings;
protected override string ContentType => "application/xml";
public HttpPostXmlDocumentFormatter(WebServiceTarget target) : base(target)
{
if (string.IsNullOrEmpty(target.XmlRoot))
throw new InvalidOperationException("WebServiceProtocol.Xml requires WebServiceTarget.XmlRoot to be set.");
_xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding, OmitXmlDeclaration = true, Indent = false };
}
protected override void WriteContent(MemoryStream ms, object[] parameterValues)
{
XmlWriter xtw = XmlWriter.Create(ms, _xmlWriterSettings);
xtw.WriteStartElement(Target.XmlRoot, Target.XmlRootNamespace);
WriteAllParametersToCurrenElement(xtw, parameterValues);
xtw.WriteEndElement();
xtw.Flush();
}
}
private abstract class HttpPostXmlFormatterBase : HttpPostFormatterBase
{
protected HttpPostXmlFormatterBase(WebServiceTarget target) : base(target)
{
}
protected override string ContentType => "text/xml";
protected void WriteAllParametersToCurrenElement(XmlWriter currentXmlWriter, object[] parameterValues)
{
for (int i = 0; i < Target.Parameters.Count; i++)
{
string parameterValue = XmlHelper.XmlConvertToStringSafe(parameterValues[i]);
currentXmlWriter.WriteElementString(Target.Parameters[i].Name, parameterValue);
}
}
}
}
}
| |
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MembershipService;
using Orleans.Providers;
using System.Collections.Generic;
using Orleans.Services;
namespace Orleans.Hosting
{
public static class LegacyClusterConfigurationExtensions
{
/// <summary>
/// Specifies the configuration to use for this silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="configuration">The configuration.</param>
/// <remarks>This method may only be called once per builder instance.</remarks>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder UseConfiguration(this ISiloHostBuilder builder, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
return builder.AddLegacyClusterConfigurationSupport(configuration);
}
/// <summary>
/// Loads <see cref="ClusterConfiguration"/> using <see cref="ClusterConfiguration.StandardLoad"/>.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder LoadClusterConfiguration(this ISiloHostBuilder builder)
{
var configuration = new ClusterConfiguration();
configuration.StandardLoad();
return builder.UseConfiguration(configuration);
}
/// <summary>
/// Configures a localhost silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="siloPort">The silo-to-silo communication port.</param>
/// <param name="gatewayPort">The client-to-silo communication port.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder ConfigureLocalHostPrimarySilo(this ISiloHostBuilder builder, int siloPort = 22222, int gatewayPort = 40000)
{
string siloName = Silo.PrimarySiloName;
builder.Configure<SiloOptions>(options => options.SiloName = siloName);
return builder.UseConfiguration(ClusterConfiguration.LocalhostPrimarySilo(siloPort, gatewayPort));
}
public static ISiloHostBuilder AddLegacyClusterConfigurationSupport(this ISiloHostBuilder builder, ClusterConfiguration configuration)
{
LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, builder);
LegacyRemindersConfigurator.Configure(configuration.Globals, builder);
return builder.ConfigureServices(services => AddLegacyClusterConfigurationSupport(services, configuration));
}
/// <summary>
/// Specifies the configuration to use for this silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="configuration">The configuration.</param>
/// <remarks>This method may only be called once per builder instance.</remarks>
/// <returns>The silo builder.</returns>
public static ISiloBuilder UseConfiguration(this ISiloBuilder builder, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
return builder.AddLegacyClusterConfigurationSupport(configuration);
}
/// <summary>
/// Loads <see cref="ClusterConfiguration"/> using <see cref="ClusterConfiguration.StandardLoad"/>.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The silo builder.</returns>
public static ISiloBuilder LoadClusterConfiguration(this ISiloBuilder builder)
{
var configuration = new ClusterConfiguration();
configuration.StandardLoad();
return builder.UseConfiguration(configuration);
}
/// <summary>
/// Configures a localhost silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="siloPort">The silo-to-silo communication port.</param>
/// <param name="gatewayPort">The client-to-silo communication port.</param>
/// <returns>The silo builder.</returns>
public static ISiloBuilder ConfigureLocalHostPrimarySilo(this ISiloBuilder builder, int siloPort = 22222, int gatewayPort = 40000)
{
string siloName = Silo.PrimarySiloName;
builder.Configure<SiloOptions>(options => options.SiloName = siloName);
return builder.UseConfiguration(ClusterConfiguration.LocalhostPrimarySilo(siloPort, gatewayPort));
}
public static ISiloBuilder AddLegacyClusterConfigurationSupport(this ISiloBuilder builder, ClusterConfiguration configuration)
{
LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, builder);
LegacyRemindersConfigurator.Configure(configuration.Globals, builder);
return builder.ConfigureServices(services => AddLegacyClusterConfigurationSupport(services, configuration));
}
private static void AddLegacyClusterConfigurationSupport(IServiceCollection services, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
if (services.TryGetClusterConfiguration() != null)
{
throw new InvalidOperationException("Cannot configure legacy ClusterConfiguration support twice");
}
// these will eventually be removed once our code doesn't depend on the old ClientConfiguration
services.AddSingleton(configuration);
services.TryAddSingleton<LegacyConfigurationWrapper>();
services.TryAddSingleton(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().ClusterConfig.Globals);
services.TryAddTransient(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().NodeConfig);
services.TryAddSingleton<Factory<NodeConfiguration>>(
sp =>
{
var initializationParams = sp.GetRequiredService<LegacyConfigurationWrapper>();
return () => initializationParams.NodeConfig;
});
services.Configure<ClusterOptions>(options =>
{
if (string.IsNullOrWhiteSpace(options.ClusterId) && !string.IsNullOrWhiteSpace(configuration.Globals.ClusterId))
{
options.ClusterId = configuration.Globals.ClusterId;
}
if (string.IsNullOrWhiteSpace(options.ServiceId))
{
options.ServiceId = configuration.Globals.ServiceId.ToString();
}
});
services.Configure<MultiClusterOptions>(options =>
{
var globals = configuration.Globals;
if (globals.HasMultiClusterNetwork)
{
options.HasMultiClusterNetwork = true;
options.BackgroundGossipInterval = globals.BackgroundGossipInterval;
options.DefaultMultiCluster = globals.DefaultMultiCluster?.ToList();
options.GlobalSingleInstanceNumberRetries = globals.GlobalSingleInstanceNumberRetries;
options.GlobalSingleInstanceRetryInterval = globals.GlobalSingleInstanceRetryInterval;
options.MaxMultiClusterGateways = globals.MaxMultiClusterGateways;
options.UseGlobalSingleInstanceByDefault = globals.UseGlobalSingleInstanceByDefault;
foreach(GlobalConfiguration.GossipChannelConfiguration channelConfig in globals.GossipChannels)
{
options.GossipChannels.Add(GlobalConfiguration.Remap(channelConfig.ChannelType), channelConfig.ConnectionString);
}
}
});
services.TryAddFromExisting<IMessagingConfiguration, GlobalConfiguration>();
services.AddOptions<StatisticsOptions>()
.Configure<NodeConfiguration>((options, nodeConfig) => LegacyConfigurationExtensions.CopyStatisticsOptions(nodeConfig, options));
services.AddOptions<DeploymentLoadPublisherOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.DeploymentLoadPublisherRefreshTime = config.DeploymentLoadPublisherRefreshTime;
});
services.AddOptions<LoadSheddingOptions>()
.Configure<NodeConfiguration>((options, nodeConfig) =>
{
options.LoadSheddingEnabled = nodeConfig.LoadSheddingEnabled;
options.LoadSheddingLimit = nodeConfig.LoadSheddingLimit;
});
// Translate legacy configuration to new Options
services.AddOptions<SiloMessagingOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
LegacyConfigurationExtensions.CopyCommonMessagingOptions(config, options);
options.SiloSenderQueues = config.SiloSenderQueues;
options.GatewaySenderQueues = config.GatewaySenderQueues;
options.MaxForwardCount = config.MaxForwardCount;
options.ClientDropTimeout = config.ClientDropTimeout;
options.ClientRegistrationRefresh = config.ClientRegistrationRefresh;
options.MaxRequestProcessingTime = config.MaxRequestProcessingTime;
options.AssumeHomogenousSilosForTesting = config.AssumeHomogenousSilosForTesting;
})
.Configure<NodeConfiguration>((options, config) =>
{
options.PropagateActivityId = config.PropagateActivityId;
LimitValue requestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
options.MaxEnqueuedRequestsSoftLimit = requestLimit.SoftLimitThreshold;
options.MaxEnqueuedRequestsHardLimit = requestLimit.HardLimitThreshold;
LimitValue statelessWorkerRequestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER);
options.MaxEnqueuedRequestsSoftLimit_StatelessWorker = statelessWorkerRequestLimit.SoftLimitThreshold;
options.MaxEnqueuedRequestsHardLimit_StatelessWorker = statelessWorkerRequestLimit.HardLimitThreshold;
});
services.Configure<NetworkingOptions>(options => LegacyConfigurationExtensions.CopyNetworkingOptions(configuration.Globals, options));
services.AddOptions<EndpointOptions>()
.Configure<IOptions<SiloOptions>>((options, siloOptions) =>
{
var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
if (!string.IsNullOrEmpty(nodeConfig.HostNameOrIPAddress) || nodeConfig.Port != 0)
{
options.AdvertisedIPAddress = nodeConfig.Endpoint.Address;
options.SiloPort = nodeConfig.Endpoint.Port;
}
var gatewayEndpoint = nodeConfig.ProxyGatewayEndpoint;
if (gatewayEndpoint != null)
{
options.GatewayPort = gatewayEndpoint.Port;
options.GatewayListeningEndpoint = gatewayEndpoint;
}
});
services.Configure<SerializationProviderOptions>(options =>
{
options.SerializationProviders = configuration.Globals.SerializationProviders;
options.FallbackSerializationProvider = configuration.Globals.FallbackSerializationProvider;
});
services.Configure<TelemetryOptions>(options =>
{
LegacyConfigurationExtensions.CopyTelemetryOptions(configuration.Defaults.TelemetryConfiguration, services, options);
});
services.AddOptions<GrainClassOptions>().Configure<IOptions<SiloOptions>>((options, siloOptions) =>
{
var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
options.ExcludedGrainTypes.AddRange(nodeConfig.ExcludedGrainTypes);
});
services.AddOptions<SchedulingOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.AllowCallChainReentrancy = config.AllowCallChainReentrancy;
options.PerformDeadlockDetection = config.PerformDeadlockDetection;
})
.Configure<NodeConfiguration>((options, nodeConfig) =>
{
options.MaxActiveThreads = nodeConfig.MaxActiveThreads;
options.DelayWarningThreshold = nodeConfig.DelayWarningThreshold;
options.ActivationSchedulingQuantum = nodeConfig.ActivationSchedulingQuantum;
options.TurnWarningLengthThreshold = nodeConfig.TurnWarningLengthThreshold;
options.EnableWorkerThreadInjection = nodeConfig.EnableWorkerThreadInjection;
LimitValue itemLimit = nodeConfig.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS);
options.MaxPendingWorkItemsSoftLimit = itemLimit.SoftLimitThreshold;
});
services.AddOptions<GrainCollectionOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.CollectionQuantum = config.CollectionQuantum;
options.CollectionAge = config.Application.DefaultCollectionAgeLimit;
foreach (GrainTypeConfiguration grainConfig in config.Application.ClassSpecific)
{
if(grainConfig.CollectionAgeLimit.HasValue)
{
options.ClassSpecificCollectionAge.Add(grainConfig.FullTypeName, grainConfig.CollectionAgeLimit.Value);
}
};
});
LegacyProviderConfigurator<ISiloLifecycle>.ConfigureServices(configuration.Globals.ProviderConfigurations, services);
if (!string.IsNullOrWhiteSpace(configuration.Globals.DefaultPlacementStrategy))
{
services.AddSingleton(typeof(PlacementStrategy), MapDefaultPlacementStrategy(configuration.Globals.DefaultPlacementStrategy));
}
services.AddOptions<ActivationCountBasedPlacementOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.ChooseOutOf = config.ActivationCountBasedPlacementChooseOutOf;
});
services.AddOptions<StaticClusterDeploymentOptions>().Configure<ClusterConfiguration>((options, config) =>
{
options.SiloNames = config.Overrides.Keys.ToList();
});
// add grain service configs as keyed services
foreach (IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values)
{
var type = Type.GetType(grainServiceConfiguration.ServiceType);
services.AddSingletonKeyedService(type, (sp, k) => grainServiceConfiguration);
}
// populate grain service options
foreach(IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values)
{
services.AddGrainService(Type.GetType(grainServiceConfiguration.ServiceType));
}
services.AddOptions<ConsistentRingOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.UseVirtualBucketsConsistentRing = config.UseVirtualBucketsConsistentRing;
options.NumVirtualBucketsConsistentRing = config.NumVirtualBucketsConsistentRing;
});
services.AddOptions<ClusterMembershipOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.NumMissedTableIAmAliveLimit = config.NumMissedTableIAmAliveLimit;
options.LivenessEnabled = config.LivenessEnabled;
options.ProbeTimeout = config.ProbeTimeout;
options.TableRefreshTimeout = config.TableRefreshTimeout;
options.DeathVoteExpirationTimeout = config.DeathVoteExpirationTimeout;
options.IAmAliveTablePublishTimeout = config.IAmAliveTablePublishTimeout;
options.MaxJoinAttemptTime = config.MaxJoinAttemptTime;
options.ExpectedClusterSize = config.ExpectedClusterSize;
options.ValidateInitialConnectivity = config.ValidateInitialConnectivity;
options.NumMissedProbesLimit = config.NumMissedProbesLimit;
options.UseLivenessGossip = config.UseLivenessGossip;
options.NumProbedSilos = config.NumProbedSilos;
options.NumVotesForDeathDeclaration = config.NumVotesForDeathDeclaration;
})
.Configure<ClusterConfiguration>((options, config) =>
{
options.IsRunningAsUnitTest = config.IsRunningAsUnitTest;
});
services.AddOptions<GrainVersioningOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.DefaultCompatibilityStrategy = config.DefaultCompatibilityStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_COMPATABILITY_STRATEGY;
options.DefaultVersionSelectorStrategy = config.DefaultVersionSelectorStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_VERSION_SELECTOR_STRATEGY;
});
services.AddOptions<PerformanceTuningOptions>()
.Configure<NodeConfiguration>((options, config) =>
{
options.DefaultConnectionLimit = config.DefaultConnectionLimit;
options.Expect100Continue = config.Expect100Continue;
options.UseNagleAlgorithm = config.UseNagleAlgorithm;
options.MinDotNetThreadPoolSize = config.MinDotNetThreadPoolSize;
options.MinIOThreadPoolSize = config.MinDotNetThreadPoolSize;
});
services.AddOptions<TypeManagementOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.TypeMapRefreshInterval = config.TypeMapRefreshInterval;
});
services.AddOptions<GrainDirectoryOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.CachingStrategy = Remap(config.DirectoryCachingStrategy);
options.CacheSize = config.CacheSize;
options.InitialCacheTTL = config.InitialCacheTTL;
options.MaximumCacheTTL = config.MaximumCacheTTL;
options.CacheTTLExtensionFactor = config.CacheTTLExtensionFactor;
options.LazyDeregistrationDelay = config.DirectoryLazyDeregistrationDelay;
});
}
private static Type MapDefaultPlacementStrategy(string strategy)
{
switch (strategy)
{
case nameof(RandomPlacement):
return typeof(RandomPlacement);
case nameof(PreferLocalPlacement):
return typeof(PreferLocalPlacement);
case nameof(SystemPlacement):
return typeof(SystemPlacement);
case nameof(ActivationCountBasedPlacement):
return typeof(ActivationCountBasedPlacement);
case nameof(HashBasedPlacement):
return typeof(HashBasedPlacement);
default:
return null;
}
}
public static ClusterConfiguration TryGetClusterConfiguration(this IServiceCollection services)
{
return services
.FirstOrDefault(s => s.ServiceType == typeof(ClusterConfiguration))
?.ImplementationInstance as ClusterConfiguration;
}
private static GrainDirectoryOptions.CachingStrategyType Remap(GlobalConfiguration.DirectoryCachingStrategyType type)
{
switch (type)
{
case GlobalConfiguration.DirectoryCachingStrategyType.None:
return GrainDirectoryOptions.CachingStrategyType.None;
case GlobalConfiguration.DirectoryCachingStrategyType.LRU:
return GrainDirectoryOptions.CachingStrategyType.LRU;
case GlobalConfiguration.DirectoryCachingStrategyType.Adaptive:
return GrainDirectoryOptions.CachingStrategyType.Adaptive;
default:
throw new NotSupportedException($"DirectoryCachingStrategyType {type} is not supported");
}
}
}
}
| |
#region Using directives
#define USE_TRACING
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
#endregion
//////////////////////////////////////////////////////////////////////
// Contains AuthSubUtil, a helper class for authsub communications
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>helper class for communications between a 3rd party site and Google using the AuthSub protocol
/// </summary>
//////////////////////////////////////////////////////////////////////
public sealed class AuthSubUtil
{
private static readonly string DEFAULT_PROTOCOL = "https";
private static readonly string DEFAULT_DOMAIN = "www.google.com";
private static readonly string DEFAULT_HANDLER = "/accounts/AuthSubRequest";
// to prevent the compiler from creating a default public one.
private AuthSubUtil()
{
}
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the request URL to be used to retrieve an AuthSub
/// token. On success, the user will be redirected to the continue URL
/// with the AuthSub token appended to the URL.
/// Use getTokenFromReply(String) to retrieve the token from the reply.
/// </summary>
/// <param name="continueUrl">the URL to redirect to on successful
/// token retrieval</param>
/// <param name="scope">the scope of the requested AuthSub token</param>
/// <param name="secure">if the token will be used securely</param>
/// <param name="session"> if the token will be exchanged for a
/// session cookie</param>
/// <returns>the URL to be used to retrieve the AuthSub token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRequestUrl(string continueUrl,
string scope,
bool secure,
bool session)
{
return getRequestUrl(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, continueUrl, scope,
secure, session);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the request URL to be used to retrieve an AuthSub
/// token. On success, the user will be redirected to the continue URL
/// with the AuthSub token appended to the URL.
/// Use getTokenFromReply(String) to retrieve the token from the reply.
/// </summary>
/// <param name="hostedDomain">the name of the hosted domain,
/// like www.myexample.com</param>
/// <param name="continueUrl">the URL to redirect to on successful
/// token retrieval</param>
/// <param name="scope">the scope of the requested AuthSub token</param>
/// <param name="secure">if the token will be used securely</param>
/// <param name="session"> if the token will be exchanged for a
/// session cookie</param>
/// <returns>the URL to be used to retrieve the AuthSub token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRequestUrl(string hostedDomain,
string continueUrl,
string scope,
bool secure,
bool session)
{
return getRequestUrl(hostedDomain, DEFAULT_PROTOCOL, DEFAULT_DOMAIN, DEFAULT_HANDLER,
continueUrl, scope, secure, session);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the request URL to be used to retrieve an AuthSub
/// token. On success, the user will be redirected to the continue URL
/// with the AuthSub token appended to the URL.
/// Use getTokenFromReply(String) to retrieve the token from the reply.
/// </summary>
/// <param name="protocol">the protocol to use to communicate with the
/// server</param>
/// <param name="authenticationDomain">the domain at which the authentication server
/// exists</param>
/// <param name="continueUrl">the URL to redirect to on successful
/// token retrieval</param>
/// <param name="scope">the scope of the requested AuthSub token</param>
/// <param name="secure">if the token will be used securely</param>
/// <param name="session"> if the token will be exchanged for a
/// session cookie</param>
/// <returns>the URL to be used to retrieve the AuthSub token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRequestUrl(string protocol,
string authenticationDomain,
string continueUrl,
string scope,
bool secure,
bool session)
{
return getRequestUrl(null, protocol, authenticationDomain, DEFAULT_HANDLER,
continueUrl, scope, secure, session);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the request URL to be used to retrieve an AuthSub
/// token. On success, the user will be redirected to the continue URL
/// with the AuthSub token appended to the URL.
/// Use getTokenFromReply(String) to retrieve the token from the reply.
/// </summary>
/// <param name="protocol">the protocol to use to communicate with the
/// server</param>
/// <param name="authenticationDomain">the domain at which the authentication server
/// exists</param>
/// <param name="handler">the location of the authentication handler
/// (defaults to "/accounts/AuthSubRequest".</param>
/// <param name="continueUrl">the URL to redirect to on successful
/// token retrieval</param>
/// <param name="scope">the scope of the requested AuthSub token</param>
/// <param name="secure">if the token will be used securely</param>
/// <param name="session"> if the token will be exchanged for a
/// session cookie</param>
/// <returns>the URL to be used to retrieve the AuthSub token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRequestUrl(string protocol,
string authenticationDomain,
string handler,
string continueUrl,
string scope,
bool secure,
bool session)
{
return getRequestUrl(null, protocol, authenticationDomain, handler, continueUrl,
scope, secure, session);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the request URL to be used to retrieve an AuthSub
/// token. On success, the user will be redirected to the continue URL
/// with the AuthSub token appended to the URL.
/// Use getTokenFromReply(String) to retrieve the token from the reply.
/// </summary>
/// <param name="hostedDomain">the name of the hosted domain,
/// like www.myexample.com</param>
/// <param name="protocol">the protocol to use to communicate with the
/// server</param>
/// <param name="authenticationDomain">the domain at which the authentication server
/// exists</param>
/// <param name="handler">the location of the authentication handler
/// (defaults to "/accounts/AuthSubRequest".</param>
/// <param name="continueUrl">the URL to redirect to on successful
/// token retrieval</param>
/// <param name="scope">the scope of the requested AuthSub token</param>
/// <param name="secure">if the token will be used securely</param>
/// <param name="session"> if the token will be exchanged for a
/// session cookie</param>
/// <returns>the URL to be used to retrieve the AuthSub token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRequestUrl(string hostedDomain,
string protocol,
string authenticationDomain,
string handler,
string continueUrl,
string scope,
bool secure,
bool session)
{
StringBuilder url = new StringBuilder(protocol);
url.Append("://");
url.Append(authenticationDomain);
url.Append(handler);
url.Append("?");
addParameter(url, "next", continueUrl);
url.Append("&");
addParameter(url, "scope", scope);
url.Append("&");
addParameter(url, "secure", secure ? "1" : "0");
url.Append("&");
addParameter(url, "session", session ? "1" : "0");
if (hostedDomain != null)
{
url.Append("&");
addParameter(url, "hd", hostedDomain);
}
return url.ToString();
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Adds the query parameter with the given name and value to the URL.
/// </summary>
//////////////////////////////////////////////////////////////////////
private static void addParameter(StringBuilder url,
string name,
string value)
{
// encode them
name = Utilities.UriEncodeReserved(name);
value = Utilities.UriEncodeReserved(value);
// Append the name/value pair
url.Append(name);
url.Append('=');
url.Append(value);
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the URL to use to exchange the one-time-use token for
/// a session token.
/// </summary>
/// <returns>the URL to exchange for the session token</returns>
//////////////////////////////////////////////////////////////////////
public static string getSessionTokenUrl()
{
return getSessionTokenUrl(DEFAULT_PROTOCOL, DEFAULT_DOMAIN);
}
//end of public static string getSessionTokenUrl()
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the URL to use to exchange the one-time-use token for
/// a session token.
/// </summary>
/// <param name="protocol">the protocol to use to communicate with
/// the server</param>
/// <param name="domain">the domain at which the authentication server
/// exists</param>
/// <returns>the URL to exchange for the session token</returns>
//////////////////////////////////////////////////////////////////////
public static string getSessionTokenUrl(string protocol, string domain)
{
return protocol + "://" + domain + "/accounts/AuthSubSessionToken";
}
//end of public static string getSessionTokenUrl()
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the URL that handles token revocation, using the default
/// domain and the default protocol
/// </summary>
/// <returns>the URL to exchange for the session token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRevokeTokenUrl()
{
return getRevokeTokenUrl(DEFAULT_PROTOCOL, DEFAULT_DOMAIN);
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the URL that handles token revocation.
/// </summary>
/// <param name="protocol">the protocol to use to communicate with
/// the server</param>
/// <param name="domain">the domain at which the authentication server
/// exists</param>
/// <returns>the URL to exchange for the session token</returns>
//////////////////////////////////////////////////////////////////////
public static string getRevokeTokenUrl(string protocol, string domain)
{
return protocol + "://" + domain + "/accounts/AuthSubRevokeToken";
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Parses and returns the AuthSub token returned by Google on a successful
/// AuthSub login request. The token will be appended as a query parameter
/// to the continue URL specified while making the AuthSub request.
/// </summary>
/// <param name="uri">The reply URI to parse </param>
/// <returns>the token value of the URI, or null if none </returns>
//////////////////////////////////////////////////////////////////////
public static string getTokenFromReply(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
char[] deli = {'?', '&'};
TokenCollection tokens = new TokenCollection(uri.Query, deli);
foreach (string token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = {'='};
string[] parameters = token.Split(otherDeli, 2);
if (parameters[0] == "token")
{
return parameters[1];
}
}
}
return null;
}
//end of public static string getTokenFromReply(URL url)
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Exchanges the one time use token returned in the URL for a session
/// token. If the key is non-null, the token will be used securely,
/// and the request will be signed
/// </summary>
/// <param name="onetimeUseToken">the token send by google in the URL</param>
/// <param name="key">the private key used to sign</param>
/// <returns>the session token</returns>
//////////////////////////////////////////////////////////////////////
public static string exchangeForSessionToken(string onetimeUseToken,
AsymmetricAlgorithm key)
{
return exchangeForSessionToken(DEFAULT_PROTOCOL, DEFAULT_DOMAIN,
onetimeUseToken, key);
}
//end of public static String exchangeForSessionToken(String onetimeUseToken, PrivateKey key)
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Exchanges the one time use token returned in the URL for a session
/// token. If the key is non-null, the token will be used securely,
/// and the request will be signed
/// </summary>
/// <param name="protocol">the protocol to use to communicate with the
/// server</param>
/// <param name="domain">the domain at which the authentication server
/// exists</param>
/// <param name="onetimeUseToken">the token send by google in the URL</param>
/// <param name="key">the private key used to sign</param>
/// <returns>the session token</returns>
//////////////////////////////////////////////////////////////////////
public static string exchangeForSessionToken(string protocol,
string domain,
string onetimeUseToken,
AsymmetricAlgorithm key)
{
HttpWebResponse response = null;
string authSubToken = null;
try
{
string sessionUrl = getSessionTokenUrl(protocol, domain);
Uri uri = new Uri(sessionUrl);
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
string header = formAuthorizationHeader(onetimeUseToken, key, uri, "GET");
request.Headers.Add(header);
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException e)
{
Tracing.TraceMsg("exchangeForSessionToken failed " + e.Status);
throw new GDataRequestException("Execution of exchangeForSessionToken", e);
}
if (response != null)
{
int code = (int) response.StatusCode;
if (code != 200)
{
throw new GDataRequestException(
"Execution of exchangeForSessionToken request returned unexpected result: " + code, response);
}
// get the body and parse it
authSubToken = Utilities.ParseValueFormStream(response.GetResponseStream(),
GoogleAuthentication.AuthSubToken);
}
Tracing.Assert(authSubToken != null, "did not find an auth token in exchangeForSessionToken");
return authSubToken;
}
//end of public static String exchangeForSessionToken(String onetimeUseToken, PrivateKey key)
/// <summary>
/// Revokes the specified token. If the <code>key</code> is non-null,
/// the token will be used securely and the request to revoke the
/// token will be signed.
/// </summary>
/// <param name="token">the AuthSub token to revoke</param>
/// <param name="key">the private key to sign the request</param>
public static void revokeToken(string token,
AsymmetricAlgorithm key)
{
revokeToken(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, token, key);
}
/// <summary>
/// Revokes the specified token. If the <code>key</code> is non-null,
/// the token will be used securely and the request to revoke the
/// token will be signed.
/// </summary>
/// <param name="protocol"></param>
/// <param name="domain"></param>
/// <param name="token">the AuthSub token to revoke</param>
/// <param name="key">the private key to sign the request</param>
public static void revokeToken(string protocol,
string domain,
string token,
AsymmetricAlgorithm key)
{
HttpWebResponse response = null;
try
{
string revokeUrl = getRevokeTokenUrl(protocol, domain);
Uri uri = new Uri(revokeUrl);
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
string header = formAuthorizationHeader(token, key, uri, "GET");
request.Headers.Add(header);
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException e)
{
Tracing.TraceMsg("revokeToken failed " + e.Status);
throw new GDataRequestException("Execution of revokeToken", e);
}
if (response != null)
{
int code = (int) response.StatusCode;
if (code != 200)
{
throw new GDataRequestException(
"Execution of revokeToken request returned unexpected result: " + code, response);
}
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Forms the AuthSub authorization header.
/// if key is null, the token will be in insecure mode, otherwise
/// the token will be used securely and the header contains
/// a signature
/// </summary>
/// <param name="token">the AuthSub token to use </param>
/// <param name="key">the private key to used </param>
/// <param name="requestUri">the request uri to use </param>
/// <param name="requestMethod">the HTTP method to use </param>
/// <returns>the authorization header </returns>
//////////////////////////////////////////////////////////////////////
public static string formAuthorizationHeader(string token,
AsymmetricAlgorithm key,
Uri requestUri,
string requestMethod)
{
if (key == null)
{
return string.Format(CultureInfo.InvariantCulture, "Authorization: AuthSub token=\"{0}\"", token);
}
if (requestUri == null)
{
throw new ArgumentNullException("requestUri");
}
// Form signature for secure mode
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int timestamp = (int) t.TotalSeconds;
string nounce = generateULONGRnd();
string dataToSign = string.Format(CultureInfo.InvariantCulture,
"{0} {1} {2} {3}",
requestMethod,
requestUri.AbsoluteUri,
timestamp.ToString(CultureInfo.InvariantCulture),
nounce);
byte[] signature = sign(dataToSign, key);
string encodedSignature = Convert.ToBase64String(signature);
string algorithmName = key is DSACryptoServiceProvider ? "dsa-sha1" : "rsa-sha1";
return string.Format(CultureInfo.InvariantCulture,
"Authorization: AuthSub token=\"{0}\" data=\"{1}\" sig=\"{2}\" sigalg=\"{3}\"",
token, dataToSign, encodedSignature, algorithmName);
}
//end of public static string formAuthorizationHeader(string token, p key, Uri requestUri, string requestMethod)
//////////////////////////////////////////////////////////////////////
/// <summary>Retrieves information about the AuthSub token.
/// If the <code>key</code> is non-null, the token will be used securely
/// and the request to revoke the token will be signed.
/// </summary>
/// <param name="token">tthe AuthSub token for which to receive information </param>
/// <param name="key">the private key to sign the request</param>
/// <returns>the token information in the form of a Dictionary from the name of the
/// attribute to the value of the attribute</returns>
//////////////////////////////////////////////////////////////////////
public static Dictionary<string, string> GetTokenInfo(string token,
AsymmetricAlgorithm key)
{
return GetTokenInfo(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, token, key);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Retrieves information about the AuthSub token.
/// If the <code>key</code> is non-null, the token will be used securely
/// and the request to revoke the token will be signed.
/// </summary>
/// <param name="protocol">the protocol to use to communicate with the server</param>
/// <param name="domain">the domain at which the authentication server exists</param>
/// <param name="token">tthe AuthSub token for which to receive information </param>
/// <param name="key">the private key to sign the request</param>
/// <returns>the token information in the form of a Dictionary from the name of the
/// attribute to the value of the attribute</returns>
//////////////////////////////////////////////////////////////////////
public static Dictionary<string, string> GetTokenInfo(string protocol,
string domain,
string token,
AsymmetricAlgorithm key)
{
HttpWebResponse response;
try
{
string tokenInfoUrl = GetTokenInfoUrl(protocol, domain);
Uri uri = new Uri(tokenInfoUrl);
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
string header = formAuthorizationHeader(token, key, uri, "GET");
request.Headers.Add(header);
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException e)
{
Tracing.TraceMsg("GetTokenInfo failed " + e.Status);
throw new GDataRequestException("Execution of GetTokenInfo", e);
}
if (response != null)
{
int code = (int) response.StatusCode;
if (code != 200)
{
throw new GDataRequestException(
"Execution of revokeToken request returned unexpected result: " + code, response);
}
TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream());
if (tokens != null)
{
return tokens.CreateDictionary();
}
}
return null;
}
//////////////////////////////////////////////////////////////////////
/// <summary>creates a max 20 character long string of random numbers</summary>
/// <returns> the string containing random numbers</returns>
//////////////////////////////////////////////////////////////////////
private static string generateULONGRnd()
{
byte[] randomNumber = new byte[20];
// Create a new instance of the RNGCryptoServiceProvider.
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
// Fill the array with a random value.
Gen.GetBytes(randomNumber);
StringBuilder x = new StringBuilder(20);
for (int i = 0; i < 20; i++)
{
if (randomNumber[i] == 0 && x.Length == 0)
{
continue;
}
x.Append(Convert.ToInt16(randomNumber[i], CultureInfo.InvariantCulture).ToString()[0]);
}
return x.ToString();
}
//end of private static string generateULONGRnd()
//////////////////////////////////////////////////////////////////////
/// <summary>signs the data with the given key</summary>
/// <param name="dataToSign">the data to sign </param>
/// <param name="key">the private key to used </param>
/// <returns> the signed data</returns>
//////////////////////////////////////////////////////////////////////
private static byte[] sign(string dataToSign, AsymmetricAlgorithm key)
{
byte[] data = new ASCIIEncoding().GetBytes(dataToSign);
try
{
RSACryptoServiceProvider providerRSA = key as RSACryptoServiceProvider;
if (providerRSA != null)
{
return providerRSA.SignData(data, new SHA1CryptoServiceProvider());
}
DSACryptoServiceProvider providerDSA = key as DSACryptoServiceProvider;
if (providerDSA != null)
{
return providerDSA.SignData(data);
}
}
catch (CryptographicException e)
{
Tracing.TraceMsg(e.Message);
}
return null;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the URL that handles token information call.</summary>
/// <param name="protocol">the protocol to use to communicate with the server</param>
/// <param name="domain">the domain at which the authentication server exists</param>
/// <returns> the URL that handles token information call.</returns>
//////////////////////////////////////////////////////////////////////
private static string GetTokenInfoUrl(string protocol,
string domain)
{
return protocol + "://" + domain + "/accounts/AuthSubTokenInfo";
}
}
//end of public class AuthSubUtil
}
/////////////////////////////////////////////////////////////////////////////
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace OutsideSpam.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Rynchodon.AntennaRelay;
using Rynchodon.Autopilot.Data;
using Rynchodon.Autopilot.Pathfinding;
using Rynchodon.Settings;
using Rynchodon.Utility;
using Rynchodon.Weapons;
using Sandbox.Common.ObjectBuilders;
using VRage.Collections;
using VRage.Game;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRage.ObjectBuilders;
using VRageMath;
namespace Rynchodon.Autopilot.Navigator
{
/// <summary>
/// Uses weapons to attack enemy ship
/// </summary>
public class Fighter : NavigatorMover, IEnemyResponse, IDisposable
{
private const float FinalAltitude = -50f, InitialAltitude = 200f;
private static readonly MyObjectBuilderType[] TurretWeaponTypes = new MyObjectBuilderType[] { typeof(MyObjectBuilder_LargeGatlingTurret), typeof(MyObjectBuilder_LargeMissileTurret), typeof(MyObjectBuilder_InteriorTurret) };
private static readonly TargetType[] CumulativeTypes = new TargetType[] { TargetType.SmallGrid, TargetType.LargeGrid, TargetType.Station };
private readonly CachingList<FixedWeapon> m_weapons_fixed = new CachingList<FixedWeapon>();
private readonly CachingList<WeaponTargeting> m_weapons_all = new CachingList<WeaponTargeting>();
private readonly Dictionary<TargetType, BlockTypeList> m_cumulative_targeting = new Dictionary<TargetType, BlockTypeList>();
private WeaponTargeting m_weapon_primary;
private PseudoBlock m_weapon_primary_pseudo;
private LastSeen m_currentTarget;
private Orbiter m_orbiter;
private float m_finalOrbitAltitude;
private float m_weaponRange_min;
private bool m_weaponArmed = false;
private bool m_destroySet = false;
private bool m_weaponDataDirty = true;
private Logable Log
{
get { return new Logable(m_controlBlock.CubeGrid); }
}
public Fighter(Pathfinder pathfinder, AllNavigationSettings navSet)
: base(pathfinder)
{
Arm();
}
~Fighter()
{
Dispose();
}
public void Dispose()
{
Disarm();
}
public bool CanRespond()
{
if (!m_weaponArmed)
{
Arm();
if (!m_weaponArmed)
{
m_navSet.Settings_Commands.Complaint |= InfoString.StringId.FighterUnarmed;
return false;
}
}
GetPrimaryWeapon();
if (m_weapon_primary == null)
{
m_navSet.Settings_Commands.Complaint |= InfoString.StringId.FighterNoPrimary;
return false;
}
m_navSet.Settings_Task_NavEngage.NavigationBlock = m_weapon_primary_pseudo;
if (m_weaponDataDirty)
UpdateWeaponData();
//Log.DebugLog("weapon count: " + m_weapons_all.Count, "CanRespond()");
if (m_weapons_all.Count == 0)
{
m_navSet.Settings_Commands.Complaint |= InfoString.StringId.FighterNoWeapons;
return false;
}
return true;
}
public void UpdateTarget(LastSeen enemy)
{
if (enemy == null)
{
Log.DebugLog("lost target", Logger.severity.DEBUG, condition: m_currentTarget != null);
m_currentTarget = null;
m_orbiter = null;
return;
}
if (m_currentTarget == null || m_currentTarget.Entity != enemy.Entity)
{
Log.DebugLog("new target: " + enemy.Entity.getBestName(), Logger.severity.DEBUG);
m_currentTarget = enemy;
m_navSet.Settings_Task_NavEngage.DestinationEntity = m_currentTarget.Entity;
}
}
public bool CanTarget(IMyCubeGrid grid)
{
CubeGridCache cache = null;
if (m_destroySet)
{
cache = CubeGridCache.GetFor(grid);
if (cache.TerminalBlocks > 0)
{
Log.DebugLog("destoy: " + grid.DisplayName);
return true;
}
else
Log.DebugLog("destroy set but no terminal blocks found: " + grid.DisplayName);
}
if (m_currentTarget != null && grid == m_currentTarget.Entity && m_weapon_primary.CurrentTarget.TType != TargetType.None)
return true;
TargetType gridType = grid.GridSizeEnum == MyCubeSize.Small ? TargetType.SmallGrid
: grid.IsStatic ? TargetType.Station
: TargetType.LargeGrid;
BlockTypeList targetBlocks;
if (m_cumulative_targeting.TryGetValue(gridType, out targetBlocks))
{
if (cache == null)
cache = CubeGridCache.GetFor(grid);
foreach (IMyCubeBlock block in targetBlocks.Blocks(cache))
return true;
}
else
Log.DebugLog("no targeting at all for grid type of: " + grid.DisplayName);
return false;
}
public override void Move()
{
if (!m_weaponArmed)
{
m_mover.StopMove();
return;
}
if (m_weapon_primary == null || m_weapon_primary.CubeBlock.Closed)
{
Log.DebugLog("no primary weapon");
m_mover.StopMove();
return;
}
if (m_currentTarget == null)
{
m_mover.StopMove();
return;
}
if (m_orbiter == null)
{
if (m_navSet.DistanceLessThan(m_weaponRange_min * 2f))
{
// we give orbiter a lower distance, so it will calculate orbital speed from that
m_orbiter = new Orbiter(m_pathfinder, m_navSet, m_currentTarget.Entity, m_weaponRange_min + FinalAltitude, m_currentTarget.HostileName());
// start further out so we can spiral inwards
m_finalOrbitAltitude = m_orbiter.Altitude;
m_orbiter.Altitude = m_finalOrbitAltitude + InitialAltitude - FinalAltitude;
Log.DebugLog("weapon range: " + m_weaponRange_min + ", final orbit altitude: " + m_finalOrbitAltitude + ", initial orbit altitude: " + m_orbiter.Altitude, Logger.severity.DEBUG);
}
else
{
m_mover.Thrust.Update();
Vector3 direction = m_mover.SignificantGravity() ?
(Vector3)m_mover.Thrust.WorldGravity / -m_mover.Thrust.GravityStrength :
Vector3.CalculatePerpendicularVector(Vector3.Normalize(m_weapon_primary_pseudo.WorldPosition - m_currentTarget.GetPosition()));
Vector3 offset = direction * (m_weaponRange_min + InitialAltitude);
m_pathfinder.MoveTo(m_currentTarget, offset);
return;
}
}
Target current = m_weapon_primary.CurrentTarget;
if ((current == null || current.Entity == null) && m_orbiter.Altitude > m_finalOrbitAltitude && m_navSet.DistanceLessThan(m_orbiter.OrbitSpeed * 0.5f))
{
Log.DebugLog("weapon range: " + m_weaponRange_min + ", final orbit altitude: " + m_finalOrbitAltitude + ", initial orbit altitude: " + m_orbiter.Altitude +
", dist: " + m_navSet.Settings_Current.Distance + ", orbit speed: " + m_orbiter.OrbitSpeed, Logger.severity.TRACE);
m_orbiter.Altitude -= 10f;
}
m_orbiter.Move();
////Log.DebugLog("moving to " + (m_currentTarget.predictPosition() + m_currentOffset), "Move()");
//m_mover.CalcMove(m_weapon_primary_pseudo, m_currentTarget.GetPosition() + m_currentOffset, m_currentTarget.GetLinearVelocity());
}
public void Rotate()
{
if (!m_weaponArmed)
{
m_mover.StopRotate();
return;
}
if (m_weapon_primary == null || m_weapon_primary.CubeBlock.Closed)
{
Log.DebugLog("no primary weapon");
Disarm();
m_mover.StopRotate();
return;
}
Vector3? FiringDirection = m_weapon_primary.CurrentTarget.FiringDirection;
if (!FiringDirection.HasValue)
{
if (m_orbiter != null)
m_orbiter.Rotate();
else
m_mover.CalcRotate();
return;
}
//Log.DebugLog("facing target at " + firingDirection.Value, "Rotate()");
RelativeDirection3F upDirect = null;
if (m_mover.SignificantGravity())
upDirect = RelativeDirection3F.FromWorld(m_controlBlock.CubeGrid, -m_mover.Thrust.WorldGravity.vector);
m_mover.CalcRotate(m_weapon_primary_pseudo, RelativeDirection3F.FromWorld(m_weapon_primary_pseudo.Grid, FiringDirection.Value), UpDirect: upDirect, targetEntity: m_weapon_primary.CurrentTarget.Entity);
}
public override void AppendCustomInfo(StringBuilder customInfo)
{
if (m_orbiter != null)
{
if (m_mover.ThrustersOverWorked())
customInfo.AppendLine("Fighter cannot stabilize in gravity");
m_orbiter.AppendCustomInfo(customInfo);
}
else
{
customInfo.Append("Fighter moving to: ");
customInfo.AppendLine(m_currentTarget.HostileName());
}
}
private void Arm()
{
if (!ServerSettings.GetSetting<bool>(ServerSettings.SettingName.bAllowWeaponControl))
{
Log.DebugLog("Cannot arm, weapon control is disabled.", Logger.severity.WARNING);
return;
}
Log.DebugLog("Arming", Logger.severity.DEBUG);
Log.DebugLog("Fixed weapons has not been cleared", Logger.severity.FATAL, condition: m_weapons_fixed.Count != 0);
Log.DebugLog("All weapons has not been cleared", Logger.severity.FATAL, condition: m_weapons_all.Count != 0);
m_weaponRange_min = float.MaxValue;
CubeGridCache cache = CubeGridCache.GetFor(m_controlBlock.CubeGrid);
foreach (FixedWeapon weapon in Registrar.Scripts<FixedWeapon, WeaponTargeting>())
{
if (weapon.CubeBlock.CubeGrid == m_controlBlock.CubeGrid)
{
if (weapon.EngagerTakeControl())
{
Log.DebugLog("Took control of " + weapon.CubeBlock.DisplayNameText);
m_weapons_fixed.Add(weapon);
m_weapons_all.Add(weapon);
weapon.CubeBlock.OnClosing += Weapon_OnClosing;
}
else
Log.DebugLog("failed to get control of: " + weapon.CubeBlock.DisplayNameText);
}
if (weapon.MotorTurretBaseGrid() == m_controlBlock.CubeGrid)
{
Log.DebugLog("Active motor turret: " + weapon.CubeBlock.DisplayNameText);
m_weapons_all.Add(weapon);
weapon.CubeBlock.OnClosing += Weapon_OnClosing;
}
}
foreach (MyObjectBuilderType weaponType in TurretWeaponTypes)
{
foreach (IMyCubeBlock block in cache.BlocksOfType(weaponType))
{
WeaponTargeting weapon;
if (!Registrar.TryGetValue(block.EntityId, out weapon))
{
Logger.AlwaysLog("Failed to get block: " + block.nameWithId(), Logger.severity.WARNING);
continue;
}
if (weapon.CurrentControl != WeaponTargeting.Control.Off)
{
Log.DebugLog("Active turret: " + weapon.CubeBlock.DisplayNameText);
m_weapons_all.Add(weapon);
weapon.CubeBlock.OnClosing += Weapon_OnClosing;
}
}
}
m_weapons_fixed.ApplyAdditions();
m_weapons_all.ApplyAdditions();
m_weaponArmed = m_weapons_all.Count != 0;
m_weaponDataDirty = m_weaponArmed;
if (m_weaponArmed)
Log.DebugLog("Now armed", Logger.severity.DEBUG);
else
Log.DebugLog("Failed to arm", Logger.severity.DEBUG);
}
private void Disarm()
{
if (!m_weaponArmed)
return;
Log.DebugLog("Disarming", Logger.severity.DEBUG);
foreach (FixedWeapon weapon in m_weapons_fixed)
weapon.EngagerReleaseControl();
foreach (WeaponTargeting weapon in m_weapons_all)
weapon.CubeBlock.OnClosing -= Weapon_OnClosing;
m_weapons_fixed.ClearImmediate();
m_weapons_all.ClearImmediate();
m_weaponArmed = false;
m_weaponDataDirty = true;
}
/// <summary>
/// Finds a primary weapon for m_weapon_primary and m_weapon_primary_pseudo.
/// A primary weapon can be any working weapon with ammo.
/// Preference is given to fixed weapons and weapons with targets.
/// If no weapons have ammo, m_weapon_primary and m_weapon_primary_pseudo will be null.
/// </summary>
private void GetPrimaryWeapon()
{
if (m_weapon_primary != null && m_weapon_primary.CubeBlock.IsWorking && m_weapon_primary.CurrentTarget.Entity != null)
return;
WeaponTargeting weapon_primary = null;
bool removed = false;
foreach (FixedWeapon weapon in m_weapons_fixed)
if (weapon.CubeBlock.IsWorking)
{
if (weapon.HasAmmo)
{
weapon_primary = weapon;
if (weapon.CurrentTarget.Entity != null)
{
Log.DebugLog("has target: " + weapon.CubeBlock.DisplayNameText);
break;
}
}
else
Log.DebugLog("no ammo: " + weapon.CubeBlock.DisplayNameText);
}
else
{
Log.DebugLog("not working: " + weapon.CubeBlock.DisplayNameText);
m_weapons_fixed.Remove(weapon);
weapon.EngagerReleaseControl();
removed = true;
}
if (weapon_primary == null)
foreach (WeaponTargeting weapon in m_weapons_all)
if (weapon.CubeBlock.IsWorking)
{
if (weapon.HasAmmo)
{
weapon_primary = weapon;
if (weapon.CurrentTarget.Entity != null)
{
Log.DebugLog("has target: " + weapon.CubeBlock.DisplayNameText);
break;
}
}
else
Log.DebugLog("no ammo: " + weapon.CubeBlock.DisplayNameText);
}
else
{
Log.DebugLog("not working: " + weapon.CubeBlock.DisplayNameText);
m_weapons_all.Remove(weapon);
removed = true;
}
if (removed)
{
m_weapons_fixed.ApplyRemovals();
m_weapons_all.ApplyRemovals();
m_weaponDataDirty = true;
}
if (weapon_primary == null)
{
m_weapon_primary = null;
m_weapon_primary_pseudo = null;
return;
}
if (m_weapon_primary != weapon_primary)
{
m_weapon_primary = weapon_primary;
IMyCubeBlock faceBlock;
FixedWeapon fixedWeapon = weapon_primary as FixedWeapon;
if (fixedWeapon != null && fixedWeapon.CubeBlock.CubeGrid != m_controlBlock.CubeGrid)
{
faceBlock = fixedWeapon.MotorTurretFaceBlock();
Log.DebugLog("MotorTurretFaceBlock == null", Logger.severity.FATAL, condition: faceBlock == null);
}
else
faceBlock = weapon_primary.CubeBlock;
if (m_mover.SignificantGravity())
{
if (m_mover.Thrust.Standard.LocalMatrix.Forward == faceBlock.LocalMatrix.Forward)
{
Log.DebugLog("primary forward matches Standard forward");
Matrix localMatrix = m_mover.Thrust.Standard.LocalMatrix;
localMatrix.Translation = faceBlock.LocalMatrix.Translation;
m_weapon_primary_pseudo = new PseudoBlock(() => faceBlock.CubeGrid, localMatrix);
return;
}
if (m_mover.Thrust.Gravity.LocalMatrix.Forward == faceBlock.LocalMatrix.Forward)
{
Log.DebugLog("primary forward matches Gravity forward");
Matrix localMatrix = m_mover.Thrust.Gravity.LocalMatrix;
localMatrix.Translation = faceBlock.LocalMatrix.Translation;
m_weapon_primary_pseudo = new PseudoBlock(() => faceBlock.CubeGrid, localMatrix);
return;
}
Log.DebugLog("cannot match primary forward to a standard flight matrix. primary forward: " + faceBlock.LocalMatrix.Forward +
", Standard forward: " + m_mover.Thrust.Standard.LocalMatrix.Forward + ", gravity forward: " + m_mover.Thrust.Gravity.LocalMatrix.Forward);
}
m_weapon_primary_pseudo = new PseudoBlock(faceBlock);
}
}
private void UpdateWeaponData()
{
m_weaponRange_min = float.MaxValue;
m_cumulative_targeting.Clear();
m_destroySet = false;
foreach (WeaponTargeting weapon in m_weapons_all)
{
if (!weapon.CubeBlock.IsWorking)
{
m_weapons_all.Remove(weapon);
FixedWeapon asFixed = weapon as FixedWeapon;
if (asFixed != null)
{
m_weapons_fixed.Remove(asFixed);
asFixed.EngagerReleaseControl();
}
continue;
}
bool destroy = weapon.Options.CanTargetType(TargetType.Destroy);
if (!weapon.Options.CanTargetType(TargetType.AllGrid) && !destroy)
continue;
float TargetingRange = weapon.Options.TargetingRange;
if (TargetingRange < 1f)
continue;
if (TargetingRange < m_weaponRange_min)
m_weaponRange_min = TargetingRange;
if (m_destroySet)
continue;
if (destroy)
{
Log.DebugLog("destroy set for " + weapon.CubeBlock.DisplayNameText);
m_destroySet = true;
m_cumulative_targeting.Clear();
continue;
}
else
Log.DebugLog("destroy NOT set for " + weapon.CubeBlock.DisplayNameText);
foreach (TargetType type in CumulativeTypes)
if (weapon.Options.CanTargetType(type))
AddToCumulative(type, weapon.Options.listOfBlocks);
}
m_weapons_fixed.ApplyRemovals();
m_weapons_all.ApplyRemovals();
if (m_weapons_all.Count == 0)
{
Log.DebugLog("No working weapons, " + GetType().Name + " is done here", Logger.severity.INFO);
m_navSet.OnTaskComplete_NavEngage();
}
m_weaponDataDirty = false;
}
private void AddToCumulative(TargetType type, BlockTypeList blocks)
{
if (blocks == null)
return;
Log.DebugLog("adding to type: " + type + ", count: " + blocks.BlockNamesContain.Length);
if (type == TargetType.AllGrid)
{
AddToCumulative(TargetType.SmallGrid, blocks);
AddToCumulative(TargetType.LargeGrid, blocks);
AddToCumulative(TargetType.Station, blocks);
return;
}
BlockTypeList targetBlocks;
if (m_cumulative_targeting.TryGetValue(type, out targetBlocks))
m_cumulative_targeting[type] = BlockTypeList.Union(targetBlocks, blocks);
else
m_cumulative_targeting[type] = blocks;
}
private void Weapon_OnClosing(IMyEntity obj)
{ m_weaponDataDirty = true; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="NFCObject.cs">
// Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFrame>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFrame
{
public class NFCObject : NFIObject
{
public NFCObject(NFGUID self, int nContainerID, int nGroupID, string strClassName, string strConfigIndex)
{
mSelf = self;
mstrClassName = strClassName;
mstrConfigIndex = strConfigIndex;
mnContainerID = nContainerID;
mnGroupID = nGroupID;
Init();
}
~NFCObject()
{
Shut();
}
public override void Init()
{
mRecordManager = new NFCRecordManager(mSelf);
mPropertyManager = new NFCPropertyManager(mSelf);
mHeartManager = new NFCHeartBeatManager(mSelf);
return;
}
public override void Shut()
{
NFIDataList xRecordList = mRecordManager.GetRecordList();
if (null != xRecordList)
{
for(int i = 0; i < xRecordList.Count(); ++i)
{
string strRecordName = xRecordList.StringVal(i);
NFIRecord xRecord = mRecordManager.GetRecord(strRecordName);
if (null != xRecord)
{
xRecord.Clear();
}
}
}
mRecordManager = null;
mPropertyManager = null;
mHeartManager = null;
return;
}
public override void AddHeartBeat(string strHeartBeatName, float fTime, int nCount, NFIHeartBeat.HeartBeatEventHandler handler)
{
GetHeartBeatManager().AddHeartBeat(strHeartBeatName, fTime, nCount, handler);
}
public override bool FindHeartBeat(string strHeartBeatName)
{
return GetHeartBeatManager().FindHeartBeat(strHeartBeatName);
}
public override void RemoveHeartBeat(string strHeartBeatName)
{
GetHeartBeatManager().RemoveHeartBeat(strHeartBeatName);
}
public override bool UpData(float fLastTime, float fAllTime)
{
GetHeartBeatManager().Update(fLastTime);
return true;
}
///////////////////////////////////////////////////////////////////////
public override NFGUID Self()
{
return mSelf;
}
public override int ContainerID()
{
return mnContainerID;
}
public override int GroupID()
{
return mnGroupID;
}
public override string ClassName()
{
return mstrClassName;
}
public override string ConfigIndex()
{
return mstrConfigIndex;
}
public override bool FindProperty(string strPropertyName)
{
if (null != mPropertyManager.GetProperty(strPropertyName))
{
return true;
}
return false;
}
public override bool SetPropertyInt(string strPropertyName, Int64 nValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddInt(0);
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetInt(nValue);
return true;
}
public override bool SetPropertyFloat(string strPropertyName, double fValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddFloat(0.0f);
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetFloat(fValue);
return true;
}
public override bool SetPropertyString(string strPropertyName, string strValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddString("");
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetString(strValue);
return true;
}
public override bool SetPropertyObject(string strPropertyName, NFGUID obj)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddObject(new NFGUID());
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetObject(obj);
return true;
}
public override bool SetPropertyVector2(string strPropertyName, NFVector2 obj)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddVector2(new NFVector2());
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetVector2(obj);
return true;
}
public override bool SetPropertyVector3(string strPropertyName, NFVector3 obj)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddVector3(new NFVector3());
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetVector3(obj);
return true;
}
public override Int64 QueryPropertyInt(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryInt();
}
return 0;
}
public override double QueryPropertyFloat(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryFloat();
}
return 0.0;
}
public override string QueryPropertyString(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryString();
}
return NFIDataList.NULL_STRING;
}
public override NFGUID QueryPropertyObject(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryObject();
}
return NFIDataList.NULL_OBJECT;
}
public override NFVector2 QueryPropertyVector2(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryVector2();
}
return NFIDataList.NULL_VECTOR2;
}
public override NFVector3 QueryPropertyVector3(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryVector3();
}
return NFIDataList.NULL_VECTOR3;
}
public override bool FindRecord(string strRecordName)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return true;
}
return false;
}
public override bool SetRecordInt(string strRecordName, int nRow, int nCol, Int64 nValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetInt(nRow, nCol, nValue);
return true;
}
return false;
}
public override bool SetRecordFloat(string strRecordName, int nRow, int nCol, double fValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetFloat(nRow, nCol, fValue);
return true;
}
return false;
}
public override bool SetRecordString(string strRecordName, int nRow, int nCol, string strValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetString(nRow, nCol, strValue);
return true;
}
return false;
}
public override bool SetRecordObject(string strRecordName, int nRow, int nCol, NFGUID obj)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetObject(nRow, nCol, obj);
return true;
}
return false;
}
public override bool SetRecordVector2(string strRecordName, int nRow, int nCol, NFVector2 obj)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetVector2(nRow, nCol, obj);
return true;
}
return false;
}
public override bool SetRecordVector3(string strRecordName, int nRow, int nCol, NFVector3 obj)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetVector3(nRow, nCol, obj);
return true;
}
return false;
}
public override Int64 QueryRecordInt(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryInt(nRow, nCol);
}
return 0;
}
public override double QueryRecordFloat(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryFloat(nRow, nCol);
}
return 0.0;
}
public override string QueryRecordString(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryString(nRow, nCol);
}
return NFIDataList.NULL_STRING;
}
public override NFGUID QueryRecordObject(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryObject(nRow, nCol);
}
return null;
}
public override NFVector2 QueryRecordVector2(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryVector2(nRow, nCol);
}
return null;
}
public override NFVector3 QueryRecordVector3(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryVector3(nRow, nCol);
}
return null;
}
public override NFIRecordManager GetRecordManager()
{
return mRecordManager;
}
public override NFIHeartBeatManager GetHeartBeatManager()
{
return mHeartManager;
}
public override NFIPropertyManager GetPropertyManager()
{
return mPropertyManager;
}
NFGUID mSelf;
int mnContainerID;
int mnGroupID;
string mstrClassName;
string mstrConfigIndex;
NFIRecordManager mRecordManager;
NFIPropertyManager mPropertyManager;
NFIHeartBeatManager mHeartManager;
}
}
| |
using System.Collections.Immutable;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal sealed class UnusedValueSlotRemover : BoundTreeRewriter
{
private ValueSlotRecorder _recorder;
public override BoundRelation RewriteRelation(BoundRelation node)
{
if (_recorder is null)
{
_recorder = new ValueSlotRecorder();
_recorder.Record(node.GetOutputValues());
}
return base.RewriteRelation(node);
}
private ImmutableArray<T> RemoveUnusedSlots<T>(ImmutableArray<T> array, Func<T, ValueSlot> valueSlotSelector)
{
return array.RemoveAll(v => !_recorder.UsedValueSlots.Contains(valueSlotSelector(v)));
}
protected override BoundRelation RewriteTableRelation(BoundTableRelation node)
{
var definedValues = RemoveUnusedSlots(node.DefinedValues, d => d.ValueSlot);
node = node.Update(node.TableInstance, definedValues);
return base.RewriteTableRelation(node);
}
protected override BoundRelation RewriteFilterRelation(BoundFilterRelation node)
{
_recorder.Record(node.Condition);
return base.RewriteFilterRelation(node);
}
protected override BoundRelation RewriteJoinRelation(BoundJoinRelation node)
{
if (node.Condition is not null)
_recorder.Record(node.Condition);
if (node.PassthruPredicate is not null)
_recorder.Record(node.PassthruPredicate);
if (node.Probe is not null)
_recorder.Record(node.Probe);
var outerReferences = OuterReferenceFinder.GetOuterReferences(node);
foreach (var o in outerReferences)
_recorder.Record(o);
return base.RewriteJoinRelation(node);
}
protected override BoundRelation RewriteHashMatchRelation(BoundHashMatchRelation node)
{
_recorder.Record(node.BuildKey);
_recorder.Record(node.ProbeKey);
if (node.Remainder is not null)
_recorder.Record(node.Remainder);
return base.RewriteHashMatchRelation(node);
}
protected override BoundRelation RewriteComputeRelation(BoundComputeRelation node)
{
var definedValues = RemoveUnusedSlots(node.DefinedValues, d => d.ValueSlot);
node = node.Update(node.Input, definedValues);
_recorder.Record(definedValues);
if (!definedValues.Any())
return RewriteRelation(node.Input);
return base.RewriteComputeRelation(node);
}
protected override BoundRelation RewriteGroupByAndAggregationRelation(BoundGroupByAndAggregationRelation node)
{
var aggregates = RemoveUnusedSlots(node.Aggregates, a => a.Output);
node = node.Update(node.Input, node.Groups, aggregates);
_recorder.Record(node.Aggregates);
_recorder.Record(node.Groups);
return base.RewriteGroupByAndAggregationRelation(node);
}
protected override BoundRelation RewriteStreamAggregatesRelation(BoundStreamAggregatesRelation node)
{
var aggregates = RemoveUnusedSlots(node.Aggregates, a => a.Output);
node = node.Update(node.Input, node.Groups, aggregates);
_recorder.Record(node.Aggregates);
_recorder.Record(node.Groups);
return base.RewriteStreamAggregatesRelation(node);
}
protected override BoundRelation RewriteUnionRelation(BoundUnionRelation node)
{
if (node.IsUnionAll)
{
var definedValues = RemoveUnusedSlots(node.DefinedValues, d => d.ValueSlot);
node = node.Update(node.IsUnionAll, node.Inputs, definedValues, node.Comparers);
}
_recorder.Record(node.DefinedValues);
return base.RewriteUnionRelation(node);
}
protected override BoundRelation RewriteConcatenationRelation(BoundConcatenationRelation node)
{
var definedValues = RemoveUnusedSlots(node.DefinedValues, d => d.ValueSlot);
node = node.Update(node.Inputs, definedValues);
_recorder.Record(node.DefinedValues);
return base.RewriteConcatenationRelation(node);
}
protected override BoundRelation RewriteIntersectOrExceptRelation(BoundIntersectOrExceptRelation node)
{
_recorder.Record(node.Left.GetOutputValues());
_recorder.Record(node.Right.GetOutputValues());
return base.RewriteIntersectOrExceptRelation(node);
}
protected override BoundRelation RewriteProjectRelation(BoundProjectRelation node)
{
var outputs = RemoveUnusedSlots(node.Outputs, v => v);
node = node.Update(node.Input, outputs);
return base.RewriteProjectRelation(node);
}
protected override BoundRelation RewriteSortRelation(BoundSortRelation node)
{
_recorder.Record(node.SortedValues);
return base.RewriteSortRelation(node);
}
protected override BoundRelation RewriteTopRelation(BoundTopRelation node)
{
_recorder.Record(node.TieEntries);
return base.RewriteTopRelation(node);
}
protected override BoundRelation RewriteAssertRelation(BoundAssertRelation node)
{
_recorder.Record(node.Condition);
return base.RewriteAssertRelation(node);
}
protected override BoundRelation RewriteTableSpoolPusher(BoundTableSpoolPusher node)
{
var inputs = node.Input.GetOutputValues().ToImmutableArray();
_recorder.Record(inputs);
return base.RewriteTableSpoolPusher(node);
}
protected override BoundExpression RewriteSingleRowSubselect(BoundSingleRowSubselect node)
{
_recorder.Record(node.Value);
return base.RewriteSingleRowSubselect(node);
}
private sealed class ValueSlotRecorder
{
private readonly ValueSlotDependencyFinder _finder;
public ValueSlotRecorder()
{
_finder = new ValueSlotDependencyFinder(UsedValueSlots);
}
public HashSet<ValueSlot> UsedValueSlots { get; } = new();
public void Record(BoundExpression expression)
{
_finder.VisitExpression(expression);
}
public void Record(IEnumerable<ValueSlot> valueSlots)
{
UsedValueSlots.UnionWith(valueSlots);
}
public void Record(ValueSlot valueSlot)
{
UsedValueSlots.Add(valueSlot);
}
public void Record(ImmutableArray<BoundComputedValue> definedValues)
{
foreach (var definedValue in definedValues)
{
UsedValueSlots.Add(definedValue.ValueSlot);
_finder.VisitExpression(definedValue.Expression);
}
}
public void Record(ImmutableArray<BoundAggregatedValue> definedValues)
{
foreach (var definedValue in definedValues)
{
UsedValueSlots.Add(definedValue.Output);
_finder.VisitExpression(definedValue.Argument);
}
}
public void Record(ImmutableArray<BoundUnifiedValue> definedValues)
{
foreach (var definedValue in definedValues)
{
UsedValueSlots.Add(definedValue.ValueSlot);
UsedValueSlots.UnionWith(definedValue.InputValueSlots);
}
}
public void Record(ImmutableArray<BoundComparedValue> definedValues)
{
foreach (var definedValue in definedValues)
UsedValueSlots.Add(definedValue.ValueSlot);
}
}
}
}
| |
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 Northwind
{
/// <summary>
/// Strongly-typed collection for the Employee class.
/// </summary>
[Serializable]
public partial class EmployeeCollection : ActiveList<Employee, EmployeeCollection>
{
public EmployeeCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>EmployeeCollection</returns>
public EmployeeCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Employee 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 Employees table.
/// </summary>
[Serializable]
public partial class Employee : ActiveRecord<Employee>, IActiveRecord
{
#region .ctors and Default Settings
public Employee()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Employee(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Employee(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Employee(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Employees", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema);
colvarEmployeeID.ColumnName = "EmployeeID";
colvarEmployeeID.DataType = DbType.Int32;
colvarEmployeeID.MaxLength = 0;
colvarEmployeeID.AutoIncrement = true;
colvarEmployeeID.IsNullable = false;
colvarEmployeeID.IsPrimaryKey = true;
colvarEmployeeID.IsForeignKey = false;
colvarEmployeeID.IsReadOnly = false;
colvarEmployeeID.DefaultSetting = @"";
colvarEmployeeID.ForeignKeyTableName = "";
schema.Columns.Add(colvarEmployeeID);
TableSchema.TableColumn colvarLastName = new TableSchema.TableColumn(schema);
colvarLastName.ColumnName = "LastName";
colvarLastName.DataType = DbType.String;
colvarLastName.MaxLength = 20;
colvarLastName.AutoIncrement = false;
colvarLastName.IsNullable = false;
colvarLastName.IsPrimaryKey = false;
colvarLastName.IsForeignKey = false;
colvarLastName.IsReadOnly = false;
colvarLastName.DefaultSetting = @"";
colvarLastName.ForeignKeyTableName = "";
schema.Columns.Add(colvarLastName);
TableSchema.TableColumn colvarFirstName = new TableSchema.TableColumn(schema);
colvarFirstName.ColumnName = "FirstName";
colvarFirstName.DataType = DbType.String;
colvarFirstName.MaxLength = 10;
colvarFirstName.AutoIncrement = false;
colvarFirstName.IsNullable = false;
colvarFirstName.IsPrimaryKey = false;
colvarFirstName.IsForeignKey = false;
colvarFirstName.IsReadOnly = false;
colvarFirstName.DefaultSetting = @"";
colvarFirstName.ForeignKeyTableName = "";
schema.Columns.Add(colvarFirstName);
TableSchema.TableColumn colvarTitle = new TableSchema.TableColumn(schema);
colvarTitle.ColumnName = "Title";
colvarTitle.DataType = DbType.String;
colvarTitle.MaxLength = 30;
colvarTitle.AutoIncrement = false;
colvarTitle.IsNullable = true;
colvarTitle.IsPrimaryKey = false;
colvarTitle.IsForeignKey = false;
colvarTitle.IsReadOnly = false;
colvarTitle.DefaultSetting = @"";
colvarTitle.ForeignKeyTableName = "";
schema.Columns.Add(colvarTitle);
TableSchema.TableColumn colvarTitleOfCourtesy = new TableSchema.TableColumn(schema);
colvarTitleOfCourtesy.ColumnName = "TitleOfCourtesy";
colvarTitleOfCourtesy.DataType = DbType.String;
colvarTitleOfCourtesy.MaxLength = 25;
colvarTitleOfCourtesy.AutoIncrement = false;
colvarTitleOfCourtesy.IsNullable = true;
colvarTitleOfCourtesy.IsPrimaryKey = false;
colvarTitleOfCourtesy.IsForeignKey = false;
colvarTitleOfCourtesy.IsReadOnly = false;
colvarTitleOfCourtesy.DefaultSetting = @"";
colvarTitleOfCourtesy.ForeignKeyTableName = "";
schema.Columns.Add(colvarTitleOfCourtesy);
TableSchema.TableColumn colvarBirthDate = new TableSchema.TableColumn(schema);
colvarBirthDate.ColumnName = "BirthDate";
colvarBirthDate.DataType = DbType.DateTime;
colvarBirthDate.MaxLength = 0;
colvarBirthDate.AutoIncrement = false;
colvarBirthDate.IsNullable = true;
colvarBirthDate.IsPrimaryKey = false;
colvarBirthDate.IsForeignKey = false;
colvarBirthDate.IsReadOnly = false;
colvarBirthDate.DefaultSetting = @"";
colvarBirthDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarBirthDate);
TableSchema.TableColumn colvarHireDate = new TableSchema.TableColumn(schema);
colvarHireDate.ColumnName = "HireDate";
colvarHireDate.DataType = DbType.DateTime;
colvarHireDate.MaxLength = 0;
colvarHireDate.AutoIncrement = false;
colvarHireDate.IsNullable = true;
colvarHireDate.IsPrimaryKey = false;
colvarHireDate.IsForeignKey = false;
colvarHireDate.IsReadOnly = false;
colvarHireDate.DefaultSetting = @"";
colvarHireDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarHireDate);
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 colvarHomePhone = new TableSchema.TableColumn(schema);
colvarHomePhone.ColumnName = "HomePhone";
colvarHomePhone.DataType = DbType.String;
colvarHomePhone.MaxLength = 24;
colvarHomePhone.AutoIncrement = false;
colvarHomePhone.IsNullable = true;
colvarHomePhone.IsPrimaryKey = false;
colvarHomePhone.IsForeignKey = false;
colvarHomePhone.IsReadOnly = false;
colvarHomePhone.DefaultSetting = @"";
colvarHomePhone.ForeignKeyTableName = "";
schema.Columns.Add(colvarHomePhone);
TableSchema.TableColumn colvarExtension = new TableSchema.TableColumn(schema);
colvarExtension.ColumnName = "Extension";
colvarExtension.DataType = DbType.String;
colvarExtension.MaxLength = 4;
colvarExtension.AutoIncrement = false;
colvarExtension.IsNullable = true;
colvarExtension.IsPrimaryKey = false;
colvarExtension.IsForeignKey = false;
colvarExtension.IsReadOnly = false;
colvarExtension.DefaultSetting = @"";
colvarExtension.ForeignKeyTableName = "";
schema.Columns.Add(colvarExtension);
TableSchema.TableColumn colvarPhoto = new TableSchema.TableColumn(schema);
colvarPhoto.ColumnName = "Photo";
colvarPhoto.DataType = DbType.Binary;
colvarPhoto.MaxLength = 2147483647;
colvarPhoto.AutoIncrement = false;
colvarPhoto.IsNullable = true;
colvarPhoto.IsPrimaryKey = false;
colvarPhoto.IsForeignKey = false;
colvarPhoto.IsReadOnly = false;
colvarPhoto.DefaultSetting = @"";
colvarPhoto.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhoto);
TableSchema.TableColumn colvarNotes = new TableSchema.TableColumn(schema);
colvarNotes.ColumnName = "Notes";
colvarNotes.DataType = DbType.String;
colvarNotes.MaxLength = 1073741823;
colvarNotes.AutoIncrement = false;
colvarNotes.IsNullable = true;
colvarNotes.IsPrimaryKey = false;
colvarNotes.IsForeignKey = false;
colvarNotes.IsReadOnly = false;
colvarNotes.DefaultSetting = @"";
colvarNotes.ForeignKeyTableName = "";
schema.Columns.Add(colvarNotes);
TableSchema.TableColumn colvarReportsTo = new TableSchema.TableColumn(schema);
colvarReportsTo.ColumnName = "ReportsTo";
colvarReportsTo.DataType = DbType.Int32;
colvarReportsTo.MaxLength = 0;
colvarReportsTo.AutoIncrement = false;
colvarReportsTo.IsNullable = true;
colvarReportsTo.IsPrimaryKey = false;
colvarReportsTo.IsForeignKey = true;
colvarReportsTo.IsReadOnly = false;
colvarReportsTo.DefaultSetting = @"";
colvarReportsTo.ForeignKeyTableName = "Employees";
schema.Columns.Add(colvarReportsTo);
TableSchema.TableColumn colvarPhotoPath = new TableSchema.TableColumn(schema);
colvarPhotoPath.ColumnName = "PhotoPath";
colvarPhotoPath.DataType = DbType.String;
colvarPhotoPath.MaxLength = 255;
colvarPhotoPath.AutoIncrement = false;
colvarPhotoPath.IsNullable = true;
colvarPhotoPath.IsPrimaryKey = false;
colvarPhotoPath.IsForeignKey = false;
colvarPhotoPath.IsReadOnly = false;
colvarPhotoPath.DefaultSetting = @"";
colvarPhotoPath.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhotoPath);
TableSchema.TableColumn colvarDeleted = new TableSchema.TableColumn(schema);
colvarDeleted.ColumnName = "Deleted";
colvarDeleted.DataType = DbType.Boolean;
colvarDeleted.MaxLength = 0;
colvarDeleted.AutoIncrement = false;
colvarDeleted.IsNullable = false;
colvarDeleted.IsPrimaryKey = false;
colvarDeleted.IsForeignKey = false;
colvarDeleted.IsReadOnly = false;
colvarDeleted.DefaultSetting = @"((0))";
colvarDeleted.ForeignKeyTableName = "";
schema.Columns.Add(colvarDeleted);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Employees",schema);
}
}
#endregion
#region Props
[XmlAttribute("EmployeeID")]
[Bindable(true)]
public int EmployeeID
{
get { return GetColumnValue<int>(Columns.EmployeeID); }
set { SetColumnValue(Columns.EmployeeID, value); }
}
[XmlAttribute("LastName")]
[Bindable(true)]
public string LastName
{
get { return GetColumnValue<string>(Columns.LastName); }
set { SetColumnValue(Columns.LastName, value); }
}
[XmlAttribute("FirstName")]
[Bindable(true)]
public string FirstName
{
get { return GetColumnValue<string>(Columns.FirstName); }
set { SetColumnValue(Columns.FirstName, value); }
}
[XmlAttribute("Title")]
[Bindable(true)]
public string Title
{
get { return GetColumnValue<string>(Columns.Title); }
set { SetColumnValue(Columns.Title, value); }
}
[XmlAttribute("TitleOfCourtesy")]
[Bindable(true)]
public string TitleOfCourtesy
{
get { return GetColumnValue<string>(Columns.TitleOfCourtesy); }
set { SetColumnValue(Columns.TitleOfCourtesy, value); }
}
[XmlAttribute("BirthDate")]
[Bindable(true)]
public DateTime? BirthDate
{
get { return GetColumnValue<DateTime?>(Columns.BirthDate); }
set { SetColumnValue(Columns.BirthDate, value); }
}
[XmlAttribute("HireDate")]
[Bindable(true)]
public DateTime? HireDate
{
get { return GetColumnValue<DateTime?>(Columns.HireDate); }
set { SetColumnValue(Columns.HireDate, 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("HomePhone")]
[Bindable(true)]
public string HomePhone
{
get { return GetColumnValue<string>(Columns.HomePhone); }
set { SetColumnValue(Columns.HomePhone, value); }
}
[XmlAttribute("Extension")]
[Bindable(true)]
public string Extension
{
get { return GetColumnValue<string>(Columns.Extension); }
set { SetColumnValue(Columns.Extension, value); }
}
[XmlAttribute("Photo")]
[Bindable(true)]
public byte[] Photo
{
get { return GetColumnValue<byte[]>(Columns.Photo); }
set { SetColumnValue(Columns.Photo, value); }
}
[XmlAttribute("Notes")]
[Bindable(true)]
public string Notes
{
get { return GetColumnValue<string>(Columns.Notes); }
set { SetColumnValue(Columns.Notes, value); }
}
[XmlAttribute("ReportsTo")]
[Bindable(true)]
public int? ReportsTo
{
get { return GetColumnValue<int?>(Columns.ReportsTo); }
set { SetColumnValue(Columns.ReportsTo, value); }
}
[XmlAttribute("PhotoPath")]
[Bindable(true)]
public string PhotoPath
{
get { return GetColumnValue<string>(Columns.PhotoPath); }
set { SetColumnValue(Columns.PhotoPath, value); }
}
[XmlAttribute("Deleted")]
[Bindable(true)]
public bool Deleted
{
get { return GetColumnValue<bool>(Columns.Deleted); }
set { SetColumnValue(Columns.Deleted, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public Northwind.EmployeeCollection ChildEmployees()
{
return new Northwind.EmployeeCollection().Where(Employee.Columns.ReportsTo, EmployeeID).Load();
}
public Northwind.EmployeeTerritoryCollection EmployeeTerritories()
{
return new Northwind.EmployeeTerritoryCollection().Where(EmployeeTerritory.Columns.EmployeeID, EmployeeID).Load();
}
public Northwind.OrderCollection Orders()
{
return new Northwind.OrderCollection().Where(Order.Columns.EmployeeID, EmployeeID).Load();
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a Employee ActiveRecord object related to this Employee
///
/// </summary>
public Northwind.Employee ParentEmployee
{
get { return Northwind.Employee.FetchByID(this.ReportsTo); }
set { SetColumnValue("ReportsTo", value.EmployeeID); }
}
#endregion
#region Many To Many Helpers
public Northwind.TerritoryCollection GetTerritoryCollection() { return Employee.GetTerritoryCollection(this.EmployeeID); }
public static Northwind.TerritoryCollection GetTerritoryCollection(int varEmployeeID)
{
SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[Territories] INNER JOIN [EmployeeTerritories] ON [Territories].[TerritoryID] = [EmployeeTerritories].[TerritoryID] WHERE [EmployeeTerritories].[EmployeeID] = @EmployeeID", Employee.Schema.Provider.Name);
cmd.AddParameter("@EmployeeID", varEmployeeID, DbType.Int32);
IDataReader rdr = SubSonic.DataService.GetReader(cmd);
TerritoryCollection coll = new TerritoryCollection();
coll.LoadAndCloseReader(rdr);
return coll;
}
public static void SaveTerritoryMap(int varEmployeeID, TerritoryCollection items)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[EmployeeID] = @EmployeeID", Employee.Schema.Provider.Name);
cmdDel.AddParameter("@EmployeeID", varEmployeeID, DbType.Int32);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (Territory item in items)
{
EmployeeTerritory varEmployeeTerritory = new EmployeeTerritory();
varEmployeeTerritory.SetColumnValue("EmployeeID", varEmployeeID);
varEmployeeTerritory.SetColumnValue("TerritoryID", item.GetPrimaryKeyValue());
varEmployeeTerritory.Save();
}
}
public static void SaveTerritoryMap(int varEmployeeID, System.Web.UI.WebControls.ListItemCollection itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[EmployeeID] = @EmployeeID", Employee.Schema.Provider.Name);
cmdDel.AddParameter("@EmployeeID", varEmployeeID, DbType.Int32);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (System.Web.UI.WebControls.ListItem l in itemList)
{
if (l.Selected)
{
EmployeeTerritory varEmployeeTerritory = new EmployeeTerritory();
varEmployeeTerritory.SetColumnValue("EmployeeID", varEmployeeID);
varEmployeeTerritory.SetColumnValue("TerritoryID", l.Value);
varEmployeeTerritory.Save();
}
}
}
public static void SaveTerritoryMap(int varEmployeeID , string[] itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[EmployeeID] = @EmployeeID", Employee.Schema.Provider.Name);
cmdDel.AddParameter("@EmployeeID", varEmployeeID, DbType.Int32);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (string item in itemList)
{
EmployeeTerritory varEmployeeTerritory = new EmployeeTerritory();
varEmployeeTerritory.SetColumnValue("EmployeeID", varEmployeeID);
varEmployeeTerritory.SetColumnValue("TerritoryID", item);
varEmployeeTerritory.Save();
}
}
public static void DeleteTerritoryMap(int varEmployeeID)
{
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[EmployeeID] = @EmployeeID", Employee.Schema.Provider.Name);
cmdDel.AddParameter("@EmployeeID", varEmployeeID, DbType.Int32);
DataService.ExecuteQuery(cmdDel);
}
#endregion
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varLastName,string varFirstName,string varTitle,string varTitleOfCourtesy,DateTime? varBirthDate,DateTime? varHireDate,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varHomePhone,string varExtension,byte[] varPhoto,string varNotes,int? varReportsTo,string varPhotoPath,bool varDeleted)
{
Employee item = new Employee();
item.LastName = varLastName;
item.FirstName = varFirstName;
item.Title = varTitle;
item.TitleOfCourtesy = varTitleOfCourtesy;
item.BirthDate = varBirthDate;
item.HireDate = varHireDate;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.HomePhone = varHomePhone;
item.Extension = varExtension;
item.Photo = varPhoto;
item.Notes = varNotes;
item.ReportsTo = varReportsTo;
item.PhotoPath = varPhotoPath;
item.Deleted = varDeleted;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varEmployeeID,string varLastName,string varFirstName,string varTitle,string varTitleOfCourtesy,DateTime? varBirthDate,DateTime? varHireDate,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varHomePhone,string varExtension,byte[] varPhoto,string varNotes,int? varReportsTo,string varPhotoPath,bool varDeleted)
{
Employee item = new Employee();
item.EmployeeID = varEmployeeID;
item.LastName = varLastName;
item.FirstName = varFirstName;
item.Title = varTitle;
item.TitleOfCourtesy = varTitleOfCourtesy;
item.BirthDate = varBirthDate;
item.HireDate = varHireDate;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.HomePhone = varHomePhone;
item.Extension = varExtension;
item.Photo = varPhoto;
item.Notes = varNotes;
item.ReportsTo = varReportsTo;
item.PhotoPath = varPhotoPath;
item.Deleted = varDeleted;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn EmployeeIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn LastNameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn FirstNameColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn TitleColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn TitleOfCourtesyColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn BirthDateColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn HireDateColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn AddressColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CityColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn RegionColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn PostalCodeColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn CountryColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn HomePhoneColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn ExtensionColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn PhotoColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn NotesColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn ReportsToColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn PhotoPathColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn DeletedColumn
{
get { return Schema.Columns[18]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string EmployeeID = @"EmployeeID";
public static string LastName = @"LastName";
public static string FirstName = @"FirstName";
public static string Title = @"Title";
public static string TitleOfCourtesy = @"TitleOfCourtesy";
public static string BirthDate = @"BirthDate";
public static string HireDate = @"HireDate";
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 HomePhone = @"HomePhone";
public static string Extension = @"Extension";
public static string Photo = @"Photo";
public static string Notes = @"Notes";
public static string ReportsTo = @"ReportsTo";
public static string PhotoPath = @"PhotoPath";
public static string Deleted = @"Deleted";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#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.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi;
namespace Microsoft.Protocols.TestTools.StackSdk.Security.Nlmp
{
/// <summary>
/// The security context of nlmp server sspi. This class is used to provide sspi APIs, specified in GSS-API, such
/// as functions Accept/Sign/Verify/Encrypt/Decrypt.
/// </summary>
public class NlmpServerSecurityContext : ServerSecurityContext
{
#region Consts
/// <summary>
/// the length of ntlm v1 NtChallengeResponse of authenticate packet. see TD 2.2.2.6 NTLM v1 Response:
/// NTLM_RESPONSE.
/// </summary>
private const int NTLM_V1_NT_CHALLENGE_RESPONSE_LENGTH = 24;
/// <summary>
/// the time stamp length. see TD 2.2.2.6 NTLM v1 Response:
/// NTLM_RESPONSE, and TD 2.2.2.7 NTLM v2: NTLMv2_CLIENT_CHALLENGE. see TimeStamp in TD 2.2.2.7 NTLM v2:
/// NTLMv2_CLIENT_CHALLENGE.
/// </summary>
private const int TIME_STAMP_LENGTH = 8;
/// <summary>
/// the offset of ntlm v2 Timestamp in the NtChallengeResponse of authenticate packet. see TimeStamp in TD
/// 2.2.2.7 NTLM v2: NTLMv2_CLIENT_CHALLENGE.
/// </summary>
private const int NTLM_V2_TIME_STAMP_OFFSET_IN_NT_CHALLENGE_RESPONSE = 24;
/// <summary>
/// the client challenge length. see ChallengeFromClient in TD 2.2.2.7 NTLM v2: NTLMv2_CLIENT_CHALLENGE.
/// </summary>
private const int TIME_CLIENT_CHALLENGE_LENGTH = 8;
/// <summary>
/// the offset of ntlm v2 ClientChallenge in the NtChallengeResponse of authenticate packet. see
/// ChallengeFromClient in TD 2.2.2.7 NTLM v2: NTLMv2_CLIENT_CHALLENGE.
/// </summary>
private const int NTLM_V2_CLIENT_CHALLENGE_OFFSET_IN_NT_CHALLENGE_RESPONSE = 32;
/// <summary>
/// the offset of ntlm v2 server name in the NtChallengeResponse of authenticate packet. see AvPairs in TD
/// 2.2.2.7 NTLM v2: NTLMv2_CLIENT_CHALLENGE.
/// </summary>
private const int NTLM_V2_SERVER_NAME_OFFSET_IN_NT_CHALLENGE_RESPONSE = 44;
/// <summary>
/// the reserved length of ntlm v2 server name in the NtChallengeResponse of authenticate packet. see Reserved3
/// in TD 2.2.2.7 NTLM v2: NTLMv2_CLIENT_CHALLENGE.
/// </summary>
private const int NTLM_V2_SERVER_NAME_RESERVED_LENGTH_IN_NT_CHALLENGE_RESPONSE = 4;
#endregion
#region Fields
/// <summary>
/// the nlmp server.
/// </summary>
private NlmpServer nlmpServer;
/// <summary>
/// the negotiate packet that client requests.
/// </summary>
private NlmpNegotiatePacket negotiate;
/// <summary>
/// the challenge packet server responded.
/// </summary>
private NlmpChallengePacket challenge;
/// <summary>
/// the authenticate packet that client requests.
/// </summary>
private NlmpAuthenticatePacket authenticate;
/// <summary>
/// the version client selected. NTLMv1 or NTLMv2.
/// </summary>
private NlmpVersion version;
/// <summary>
/// Whether to continue process.
/// </summary>
private bool needContinueProcessing;
/// <summary>
/// The token returned by Sspi.
/// </summary>
private byte[] token;
/// <summary>
/// the sequence number of server.<para/>
/// it's used for server to sign/encrypt message<para/>
/// In the case of connection-oriented authentication, the SeqNum parameter MUST start at 0 and is incremented
/// by one for each message sent.
/// </summary>
private uint serverSequenceNumber;
/// <summary>
/// the sequence number of client.<para/>
/// it's used for server to verify/decrypt message from client<para/>
/// The receiver expects the first received message to have SeqNum equal to 0, and to be one greater for each
/// subsequent message received.
/// </summary>
private uint clientSequenceNumber;
/// <summary>
/// The server time for ntlm v2 authentication if client did not provide.
/// </summary>
private ulong systemTime;
/// <summary>
/// The instance of delegate VerifyAuthenticatePacketInDcMethod
/// </summary>
private VerifyAuthenticatePacketInDcMethod verifyAuthenticatePacketInDc;
#endregion
#region Properties
/// <summary>
/// the nlmp server context.
/// </summary>
public NlmpServerContext Context
{
get
{
return this.nlmpServer.Context;
}
}
/// <summary>
/// Whether to continue process.
/// </summary>
public override bool NeedContinueProcessing
{
get
{
return this.needContinueProcessing;
}
}
/// <summary>
/// The session key.
/// </summary>
public override byte[] SessionKey
{
get
{
return this.nlmpServer.Context.ExportedSessionKey;
}
}
/// <summary>
/// The token returned by Sspi.
/// </summary>
public override byte[] Token
{
get
{
return this.token;
}
}
/// <summary>
/// Gets or sets sequence number for Verify, Encrypt and Decrypt message.
/// For Digest SSP, it must be 0.
/// </summary>
public override uint SequenceNumber
{
get
{
return this.serverSequenceNumber;
}
set
{
this.serverSequenceNumber = value;
}
}
/// <summary>
/// Package type
/// </summary>
public override SecurityPackageType PackageType
{
get
{
return SecurityPackageType.Ntlm;
}
}
/// <summary>
/// Queries the sizes of the structures used in the per-message functions.
/// </summary>
public override SecurityPackageContextSizes ContextSizes
{
get
{
SecurityPackageContextSizes size = new SecurityPackageContextSizes();
size.MaxSignatureSize = NlmpUtility.NLMP_MAX_SIGNATURE_SIZE;
return size;
}
}
#endregion
#region Constructor
/// <summary>
/// constructor
/// </summary>
/// <param name="flags">the negotiate flags indicates the capabilities of server or client</param>
/// <param name="clientCredential">
/// the credential of client. server sdk can not retrieve password from AD/Account Database;<para/>
/// instead, server sdk get the user credential from this parameter.
/// </param>
/// <param name="isDomainJoined">whether the server joined to domain</param>
/// <param name="netbiosDomainName">the netbios domain name of server</param>
/// <param name="netbiosMachineName">the netbios machine name of server</param>
public NlmpServerSecurityContext(
NegotiateTypes flags,
NlmpClientCredential clientCredential,
bool isDomainJoined,
string netbiosDomainName,
string netbiosMachineName)
{
this.version = new NlmpVersion();
this.nlmpServer = new NlmpServer();
this.nlmpServer.Context.NegFlg = flags;
this.nlmpServer.Context.ClientCredential = clientCredential;
this.nlmpServer.Context.IsDomainJoined = isDomainJoined;
this.nlmpServer.Context.NbDomainName = netbiosDomainName;
this.nlmpServer.Context.NbMachineName = netbiosMachineName;
this.needContinueProcessing = true;
}
/// <summary>
/// constructor
/// </summary>
/// <param name="flags">the negotiate flags indicates the capabilities of server or client</param>
/// <param name="isDomainJoined">whether the server joined to domain</param>
/// <param name="netbiosDomainName">the netbios domain name of server</param>
/// <param name="netbiosMachineName">the netbios machine name of server</param>
/// <param name="verifyAuthenticatePacketInDcMethod">
/// the delegate method used to verify authentication packet in AD/Account Database;
/// </param>
public NlmpServerSecurityContext(
NegotiateTypes flags,
bool isDomainJoined,
string netbiosDomainName,
string netbiosMachineName,
VerifyAuthenticatePacketInDcMethod verifyAuthenticatePacketInDcMethod)
{
this.version = new NlmpVersion();
this.nlmpServer = new NlmpServer();
this.nlmpServer.Context.NegFlg = flags;
this.nlmpServer.Context.ClientCredential = null;
this.nlmpServer.Context.IsDomainJoined = isDomainJoined;
this.nlmpServer.Context.NbDomainName = netbiosDomainName;
this.nlmpServer.Context.NbMachineName = netbiosMachineName;
this.needContinueProcessing = true;
this.verifyAuthenticatePacketInDc = verifyAuthenticatePacketInDcMethod;
}
#endregion
#region Gss Apis
/// <summary>
/// The function enables the server component of a transport application to establish a security context
/// between the server and a remote client.
/// </summary>
/// <param name="inToken">The token to be used in context.</param>
/// <exception cref="ArgumentException">
/// invalid packet type of inToken, must be NEGOTIATE or AUTHENTICATE
/// </exception>
public override void Accept(byte[] inToken)
{
// if connectionless
if (inToken == null)
{
AcceptNegotiatePacket(null);
return;
}
NlmpEmptyPacket packet = new NlmpEmptyPacket(inToken);
if (packet.Header.MessageType == MessageType_Values.NEGOTIATE)
{
AcceptNegotiatePacket(new NlmpNegotiatePacket(inToken));
}
else if (packet.Header.MessageType == MessageType_Values.AUTHENTICATE)
{
AcceptAuthenticatePacket(new NlmpAuthenticatePacket(inToken));
this.needContinueProcessing = false;
}
else
{
throw new ArgumentException(
"invalid packet type of inToken, must be NEGOTIATE or AUTHENTICATE", "inToken");
}
}
/// <summary>
/// Encrypts Message. User decides what SecBuffers are used.
/// </summary>
/// <param name="securityBuffers">
/// the security buffer array to encrypt.<para/>
/// it can contain none or some data security buffer, that are combine to one message to encrypt.<para/>
/// it can contain none or some token security buffer, in which the signature will be stored.
/// </param>
/// <exception cref="ArgumentNullException">the securityBuffers must not be null</exception>
public override void Encrypt(params SecurityBuffer[] securityBuffers)
{
NlmpUtility.UpdateSealingKeyForConnectionlessMode(
this.nlmpServer.Context.NegFlg, this.nlmpServer.Context.ServerHandle,
this.nlmpServer.Context.ServerSealingKey, this.serverSequenceNumber);
NlmpUtility.GssApiEncrypt(
this.version,
this.nlmpServer.Context.NegFlg,
this.nlmpServer.Context.ServerHandle,
this.nlmpServer.Context.ServerSigningKey,
ref this.serverSequenceNumber,
securityBuffers);
}
/// <summary>
/// This takes the given SecBuffers, which are used by SSPI method DecryptMessage.
/// </summary>
/// <param name="securityBuffers">
/// the security buffer array to decrypt.<para/>
/// it can contain none or some data security buffer, that are combine to one message to decrypt.<para/>
/// it can contain none or some token security buffer, in which the signature is stored.
/// </param>
/// <returns>the encrypt result, if verify, it's the verify result.</returns>
/// <exception cref="ArgumentNullException">the securityBuffers must not be null</exception>
public override bool Decrypt(params SecurityBuffer[] securityBuffers)
{
NlmpUtility.UpdateSealingKeyForConnectionlessMode(
this.nlmpServer.Context.NegFlg, this.nlmpServer.Context.ClientHandle,
this.nlmpServer.Context.ClientSealingKey, this.clientSequenceNumber);
return NlmpUtility.GssApiDecrypt(
this.version,
this.nlmpServer.Context.NegFlg,
this.nlmpServer.Context.ClientHandle,
this.nlmpServer.Context.ClientSigningKey,
ref this.clientSequenceNumber,
securityBuffers);
}
/// <summary>
/// Sign data according SecBuffers.
/// </summary>
/// <param name="securityBuffers">
/// the security buffer array to sign.<para/>
/// it can contain none or some data security buffer, that are combine to one message to sign.<para/>
/// it must contain token security buffer, in which the signature will be stored.
/// </param>
/// <exception cref="ArgumentNullException">the securityBuffers must not be null</exception>
/// <exception cref="ArgumentException">securityBuffers must contain signature to store signature</exception>
public override void Sign(params SecurityBuffer[] securityBuffers)
{
NlmpUtility.UpdateSealingKeyForConnectionlessMode(
this.nlmpServer.Context.NegFlg, this.nlmpServer.Context.ServerHandle,
this.nlmpServer.Context.ServerSealingKey, this.serverSequenceNumber);
NlmpUtility.GssApiSign(
this.version,
this.nlmpServer.Context.NegFlg,
this.nlmpServer.Context.ServerHandle,
this.nlmpServer.Context.ServerSigningKey,
ref this.serverSequenceNumber,
securityBuffers);
}
/// <summary>
/// Encrypts Message. User decides what SecBuffers are used.
/// </summary>
/// <param name="securityBuffers">
/// the security buffer array to verify.<para/>
/// it can contain none or some data security buffer, that are combine to one message to verify.<para/>
/// it must contain token security buffer, in which the signature is stored.
/// </param>
/// <exception cref="ArgumentNullException">the securityBuffers must not be null</exception>
/// <exception cref="ArgumentException">securityBuffers must contain signature to verify</exception>
public override bool Verify(params SecurityBuffer[] securityBuffers)
{
NlmpUtility.UpdateSealingKeyForConnectionlessMode(
this.nlmpServer.Context.NegFlg, this.nlmpServer.Context.ClientHandle,
this.nlmpServer.Context.ClientSealingKey, this.clientSequenceNumber);
return NlmpUtility.GssApiVerify(
this.version,
this.nlmpServer.Context.NegFlg,
this.nlmpServer.Context.ClientHandle,
this.nlmpServer.Context.ClientSigningKey,
ref this.clientSequenceNumber,
securityBuffers);
}
#endregion
#region Implicit Ntlm Api
/// <summary>
/// Update ServerChallenge to this context
/// </summary>
/// <param name="serverChallenge">the serverChallenge to update</param>
public void UpdateServerChallenge(ulong serverChallenge)
{
#region Prepare the Nlmp Negotiate Flags
// the flags for negotiage
NegotiateTypes nlmpFlags = NegotiateTypes.NTLMSSP_NEGOTIATE_NTLM | NegotiateTypes.NTLM_NEGOTIATE_OEM;
#endregion
#region Prepare the ServerName
List<AV_PAIR> pairs = new List<AV_PAIR>();
NlmpUtility.AddAVPair(pairs, AV_PAIR_IDs.MsvAvEOL, 0x00, null);
#endregion
this.challenge = this.nlmpServer.CreateChallengePacket(nlmpFlags, NlmpUtility.GetVersion(), serverChallenge,
GenerateTargetName(), pairs);
this.token = this.challenge.ToBytes();
}
/// <summary>
/// verify the implicit ntlm session security token.
/// this api is invoked by protocol need the implicit Ntlm authenticate, such as CifsSdk and the SmbSdk with
/// none extended session security.
/// </summary>
/// <param name="accountName">the user name which determined by the security context of the user initiating the
/// connection to share</param>
/// <param name="domainName">the Primary Domain of the user</param>
/// <param name="serverTime">the time of the server</param>
/// <param name="caseInsensitivePassword">the NtChallengeResponse</param>
/// <param name="caseSensitivePassword">the LmChallengeResponse</param>
/// <returns>success or fail</returns>
public bool VerifySecurityToken(
//string workstationName,
string accountName,
string domainName,
ulong serverTime,
byte[] caseInsensitivePassword,
byte[] caseSensitivePassword)
{
if (string.IsNullOrEmpty(accountName))
{
return false;
}
this.systemTime = serverTime;
NlmpAuthenticatePacket authenticatePacket = new NlmpAuthenticatePacket();
authenticatePacket.SetNtChallengeResponse(caseSensitivePassword);
authenticatePacket.SetLmChallengeResponse(caseInsensitivePassword);
authenticatePacket.SetDomainName(domainName);
authenticatePacket.SetUserName(accountName);
authenticatePacket.SetWorkstation(string.Empty);
authenticatePacket.SetEncryptedRandomSessionKey(new byte[0]);
try
{
this.AcceptAuthenticatePacket(authenticatePacket);
}
catch (InvalidOperationException)
{
return false;
}
catch (ArgumentException) // caseSensitivePassword or caseInsensitivePassword is not long enough
{
return false;
}
return true;
}
#endregion
#region Private Methods
/// <summary>
/// accept the negotiate packet, generated the challenge packet.
/// </summary>
/// <param name="negotiatePacket">the negotiate packet</param>
private void AcceptNegotiatePacket(NlmpNegotiatePacket negotiatePacket)
{
// save the negotiate, to valid the mic when authenticate.
this.negotiate = negotiatePacket;
// generated negotiate flags for challenge packet
NegotiateTypes negotiateFlags = GeneratedNegotiateFlags(negotiatePacket);
// initialize target name
string targetName = GenerateTargetName();
// initialize av pairs.
ICollection<AV_PAIR> targetInfo = GenerateTargetInfo();
VERSION sspiVersion = NlmpUtility.GetVersion();
// the serverChallenge is 8 bytes.
ulong serverChallenge = BitConverter.ToUInt64(NlmpUtility.Nonce(8), 0);
NlmpChallengePacket challengePacket = this.nlmpServer.CreateChallengePacket(
negotiateFlags, sspiVersion, serverChallenge, targetName, targetInfo);
this.challenge = challengePacket;
this.token = challengePacket.ToBytes();
}
/// <summary>
/// generate the target info of challenge packet
/// </summary>
/// <returns>the target info in the challenge packet</returns>
private ICollection<AV_PAIR> GenerateTargetInfo()
{
ICollection<AV_PAIR> targetInfo = new Collection<AV_PAIR>();
// nb machine name
if (this.nlmpServer.Context.NbMachineName != null)
{
byte[] nbMachineName = NlmpUtility.Unicode(this.nlmpServer.Context.NbMachineName);
NlmpUtility.AddAVPair(
targetInfo, AV_PAIR_IDs.MsvAvNbComputerName, (ushort)nbMachineName.Length, nbMachineName);
}
// nb domain name
if (this.nlmpServer.Context.NbDomainName != null)
{
byte[] nbDomainName = NlmpUtility.Unicode(this.nlmpServer.Context.NbDomainName);
NlmpUtility.AddAVPair(
targetInfo, AV_PAIR_IDs.MsvAvNbDomainName, (ushort)nbDomainName.Length, nbDomainName);
}
// dns machine name
if (this.nlmpServer.Context.DnsMachineName != null)
{
byte[] dnsMachineName = NlmpUtility.Unicode(this.nlmpServer.Context.DnsMachineName);
NlmpUtility.AddAVPair(
targetInfo, AV_PAIR_IDs.MsvAvDnsComputerName, (ushort)dnsMachineName.Length, dnsMachineName);
}
// dns domain name
if (this.nlmpServer.Context.DnsDomainName != null)
{
byte[] dnsDomainName = NlmpUtility.Unicode(this.nlmpServer.Context.DnsDomainName);
NlmpUtility.AddAVPair(
targetInfo, AV_PAIR_IDs.MsvAvDnsDomainName, (ushort)dnsDomainName.Length, dnsDomainName);
}
// dns forest name
if (this.nlmpServer.Context.DnsForestName != null)
{
byte[] dnsForestName = NlmpUtility.Unicode(this.nlmpServer.Context.DnsForestName);
NlmpUtility.AddAVPair(
targetInfo, AV_PAIR_IDs.MsvAvDnsTreeName, (ushort)dnsForestName.Length, dnsForestName);
}
// eol
NlmpUtility.AddAVPair(targetInfo, AV_PAIR_IDs.MsvAvEOL, 0, null);
return targetInfo;
}
/// <summary>
/// generate the target name of challenge packet.
/// </summary>
/// <returns>the target name in the challenge packet</returns>
private string GenerateTargetName()
{
string targetName = string.Empty;
// domain or netbios
if (this.nlmpServer.Context.IsDomainJoined)
{
targetName = this.nlmpServer.Context.NbDomainName;
}
else
{
targetName = this.nlmpServer.Context.NbMachineName;
}
return targetName;
}
/// <summary>
/// generated negotiate flags for challenge packet
/// </summary>
/// <param name="negotiatePacket">the negotiate packet from client</param>
/// <returns>the negotiate flags to generate challenge packet</returns>
private NegotiateTypes GeneratedNegotiateFlags(NlmpNegotiatePacket negotiatePacket)
{
NegotiateTypes negotiateFlags = this.nlmpServer.Context.NegFlg;
// in the connectionless mode, the negotiate is null, return the flags in context.
if (negotiatePacket == null)
{
return negotiateFlags;
}
// Unicode or oem
if (NegotiateTypes.NTLMSSP_NEGOTIATE_UNICODE ==
(negotiatePacket.Payload.NegotiateFlags & NegotiateTypes.NTLMSSP_NEGOTIATE_UNICODE))
{
negotiateFlags |= NegotiateTypes.NTLMSSP_NEGOTIATE_UNICODE;
}
else if (NegotiateTypes.NTLM_NEGOTIATE_OEM ==
(negotiatePacket.Payload.NegotiateFlags & NegotiateTypes.NTLM_NEGOTIATE_OEM))
{
negotiateFlags |= NegotiateTypes.NTLM_NEGOTIATE_OEM;
}
// extended security or lm
if (NegotiateTypes.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY ==
(negotiatePacket.Payload.NegotiateFlags &
NegotiateTypes.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY))
{
negotiateFlags |= NegotiateTypes.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY;
}
else if (NegotiateTypes.NTLMSSP_NEGOTIATE_LM_KEY ==
(negotiatePacket.Payload.NegotiateFlags & NegotiateTypes.NTLMSSP_NEGOTIATE_LM_KEY))
{
negotiateFlags |= NegotiateTypes.NTLMSSP_NEGOTIATE_LM_KEY;
}
// target info
if (NegotiateTypes.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY ==
(negotiateFlags & NegotiateTypes.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY))
{
negotiateFlags |= NegotiateTypes.NTLMSSP_NEGOTIATE_TARGET_INFO;
}
return negotiateFlags;
}
/// <summary>
/// accept the authenticate packet, if failed, throw exception.
/// </summary>
/// <param name="authenticatePacket">authenciate packet</param>
/// <exception cref="InvalidOperationException">INVALID message error</exception>
/// <exception cref="InvalidOperationException">mic of authenticate packet is invalid</exception>
private void AcceptAuthenticatePacket(NlmpAuthenticatePacket authenticatePacket)
{
// save the authenticate to valid the mic.
this.authenticate = authenticatePacket;
// retrieve the client authenticate information
ClientAuthenticateInfomation authenticateInformation =
RetrieveClientAuthenticateInformation(authenticatePacket);
// update the version of context
this.version = authenticateInformation.Version;
if (authenticateInformation.ClientTime != 0)
{
this.systemTime = authenticateInformation.ClientTime;
}
byte[] exportedSessionKey = null;
if (this.nlmpServer.Context.ClientCredential == null)
{
if (verifyAuthenticatePacketInDc == null)
{
throw new InvalidOperationException(
"In domain environment, the delegate method " +
"VerifyAuthenticatePacketInDcMethod should not be null");
}
// in domain environment, the authentication is hosted in Active Directory,
// the response pair MUST be sent to DC to verify [MS-APDS] section 3.1.5
// DC will return the authentication result and the session key
DcValidationInfo dcValidationInfo = verifyAuthenticatePacketInDc(
authenticatePacket,
this.challenge.Payload.ServerChallenge);
if (dcValidationInfo.status != NtStatus.STATUS_SUCCESS)
{
throw new InvalidOperationException(
string.Format(
"verify authentication packet in DC failed, NtStatus value ={0}",
dcValidationInfo.status.ToString()));
}
exportedSessionKey = dcValidationInfo.sessionKey;
}
else
{
// in workgroup environment. the authentication is hosted locally.
authenticateInformation = VerifyAuthenticatePacketLocally(
authenticatePacket,
authenticateInformation,
out exportedSessionKey);
}
// save keys
this.nlmpServer.Context.ExportedSessionKey = exportedSessionKey;
// initialize keys and handles
InitializeKeys(exportedSessionKey);
}
/// <summary>
/// Verify the authenticate packet locally
/// </summary>
/// <param name="authenticatePacket">actual authenticate packet</param>
/// <param name="authenticateInformation">expected authenticate information</param>
/// <param name="exportedSessionKey">exported session key</param>
/// <returns></returns>
private ClientAuthenticateInfomation VerifyAuthenticatePacketLocally(
NlmpAuthenticatePacket authenticatePacket,
ClientAuthenticateInfomation authenticateInformation,
out byte[] exportedSessionKey)
{
// valid user name
if (authenticateInformation.UserName.ToUpper() != this.nlmpServer.Context.ClientCredential.AccountName.ToUpper())
{
throw new InvalidOperationException(
"the user name is invalid!"
+ " the user name retrieved form authenticate packet is not equal to the context.");
}
// calc the basekeys
byte[] responseKeyLm;
byte[] expectedNtChallengeResponse;
byte[] expectedLmChallengeResponse;
byte[] sessionBaseKey;
byte[] keyExchangeKey;
CalculateBaseKeys(
authenticateInformation.ClientChallenge,
this.systemTime,
authenticateInformation.ServerName,
authenticateInformation.DomainName,
authenticateInformation.UserName,
this.nlmpServer.Context.ClientCredential.Password,
out responseKeyLm, out expectedNtChallengeResponse, out expectedLmChallengeResponse,
out sessionBaseKey, out keyExchangeKey);
// valid message
ValidAuthenticateMessage(authenticatePacket, expectedNtChallengeResponse, expectedLmChallengeResponse);
// generate keys.
if (NlmpUtility.IsKeyExch(this.nlmpServer.Context.NegFlg))
{
exportedSessionKey = NlmpUtility.RC4(
keyExchangeKey, authenticatePacket.Payload.EncryptedRandomSessionKey);
}
else
{
exportedSessionKey = keyExchangeKey;
}
// validate mic
byte[] messageMic = authenticatePacket.Payload.MIC;
byte[] zeroMic = new byte[16];
if (messageMic != null && !ArrayUtility.CompareArrays<byte>(messageMic, zeroMic))
{
AUTHENTICATE_MESSAGE payload = authenticatePacket.Payload;
payload.MIC = zeroMic;
authenticatePacket.Payload = payload;
byte[] mic = NlmpUtility.GetMic(exportedSessionKey, this.negotiate, this.challenge, this.authenticate);
if (!ArrayUtility.CompareArrays<byte>(messageMic, mic))
{
throw new InvalidOperationException("mic of authenticate packet is invalid");
}
}
return authenticateInformation;
}
/// <summary>
/// valid the authenticate message
/// </summary>
/// <param name="authenticate">
/// the authenticate packet of client, contains the challenge response calculated by client
/// </param>
/// <param name="expectedNtChallengeResponse">the nt challenge response calculated by server</param>
/// <param name="expectedLmChallengeResponse">the lm challenge response calculated by server</param>
private static void ValidAuthenticateMessage(
NlmpAuthenticatePacket authenticate,
byte[] expectedNtChallengeResponse, byte[] expectedLmChallengeResponse)
{
if (authenticate.Payload.NtChallengeResponseFields.Len == 0
|| !ArrayUtility.CompareArrays<byte>(expectedNtChallengeResponse,
authenticate.Payload.NtChallengeResponse))
{
if (authenticate.Payload.LmChallengeResponseFields.Len == 0
|| !ArrayUtility.CompareArrays<byte>(expectedLmChallengeResponse,
authenticate.Payload.LmChallengeResponse))
{
throw new InvalidOperationException("INVALID message error");
}
}
}
/// <summary>
/// calculate the base keys to initialize the other keys
/// </summary>
/// <param name="clientChallenge">the challenge generated by client</param>
/// <param name="time">the time generated by client</param>
/// <param name="serverName">the server name from the authenticate packet</param>
/// <param name="domainName">the domain name from the authenticate packet</param>
/// <param name="userName">the user name from the authenticate packet</param>
/// <param name="userPassword">the user password from the authenticate packet</param>
/// <param name="responseKeyLm">output the lm key</param>
/// <param name="expectedNtChallengeResponse">output the expected nt challenge response of server</param>
/// <param name="expectedLmChallengeResponse">output the expected lm challenge response of server</param>
/// <param name="sessionBaseKey">output the session base key of server</param>
/// <param name="keyExchangeKey">output the key exchange key of server</param>
private void CalculateBaseKeys(
ulong clientChallenge,
ulong time,
byte[] serverName,
string domainName,
string userName,
string userPassword,
out byte[] responseKeyLm,
out byte[] expectedNtChallengeResponse,
out byte[] expectedLmChallengeResponse,
out byte[] sessionBaseKey,
out byte[] keyExchangeKey)
{
// calculate the response key nt and lm
byte[] responseKeyNt = NlmpUtility.GetResponseKeyNt(this.version, domainName, userName, userPassword);
responseKeyLm = NlmpUtility.GetResponseKeyLm(this.version, domainName, userName, userPassword);
// calcute the expected key
expectedNtChallengeResponse = null;
expectedLmChallengeResponse = null;
sessionBaseKey = null;
NlmpUtility.ComputeResponse(this.version, this.nlmpServer.Context.NegFlg, responseKeyNt, responseKeyLm,
this.challenge.Payload.ServerChallenge, clientChallenge, time, serverName,
out expectedNtChallengeResponse, out expectedLmChallengeResponse, out sessionBaseKey);
// update session key
this.nlmpServer.Context.SessionBaseKey = new byte[sessionBaseKey.Length];
Array.Copy(sessionBaseKey, this.nlmpServer.Context.SessionBaseKey, sessionBaseKey.Length);
// key exchange key
keyExchangeKey = NlmpUtility.KXKey(
this.version, sessionBaseKey,
this.authenticate.Payload.LmChallengeResponse,
this.challenge.Payload.ServerChallenge,
this.nlmpServer.Context.NegFlg, responseKeyLm);
}
/// <summary>
/// retrieve the domain name from client. client encode the domain name in the authenticate packet.
/// </summary>
/// <param name="authenticatePacket">the authenticate packet contains the domain name</param>
/// <returns>the authentication information of client</returns>
private ClientAuthenticateInfomation RetrieveClientAuthenticateInformation(
NlmpAuthenticatePacket authenticatePacket)
{
ClientAuthenticateInfomation authenticateInformation = new ClientAuthenticateInfomation();
// retrieve the version of client
if (authenticatePacket.Payload.NtChallengeResponseFields.Len == NTLM_V1_NT_CHALLENGE_RESPONSE_LENGTH)
{
authenticateInformation.Version = NlmpVersion.v1;
}
else
{
authenticateInformation.Version = NlmpVersion.v2;
}
// retrieve the client challenge
if (authenticateInformation.Version == NlmpVersion.v1)
{
authenticateInformation.ClientChallenge = BitConverter.ToUInt64(ArrayUtility.SubArray<byte>(
authenticatePacket.Payload.LmChallengeResponse, 0, TIME_CLIENT_CHALLENGE_LENGTH), 0);
}
else
{
authenticateInformation.ClientChallenge = BitConverter.ToUInt64(
ArrayUtility.SubArray<byte>(authenticatePacket.Payload.NtChallengeResponse,
NTLM_V2_CLIENT_CHALLENGE_OFFSET_IN_NT_CHALLENGE_RESPONSE, TIME_CLIENT_CHALLENGE_LENGTH), 0);
}
// retrieve the domain name of client
if (NlmpUtility.IsUnicode(authenticatePacket.Payload.NegotiateFlags))
{
authenticateInformation.DomainName = Encoding.Unicode.GetString(authenticatePacket.Payload.DomainName);
}
else
{
authenticateInformation.DomainName = Encoding.ASCII.GetString(authenticatePacket.Payload.DomainName);
}
// retrieve the user name of client
if (NlmpUtility.IsUnicode(authenticatePacket.Payload.NegotiateFlags))
{
authenticateInformation.UserName = Encoding.Unicode.GetString(authenticatePacket.Payload.UserName);
}
else
{
authenticateInformation.UserName = Encoding.ASCII.GetString(authenticatePacket.Payload.UserName);
}
// retrieve the server name of client
if (authenticateInformation.Version == NlmpVersion.v2)
{
authenticateInformation.ServerName =
ArrayUtility.SubArray<byte>(authenticatePacket.Payload.NtChallengeResponse,
NTLM_V2_SERVER_NAME_OFFSET_IN_NT_CHALLENGE_RESPONSE,
authenticatePacket.Payload.NtChallengeResponseFields.Len -
NTLM_V2_SERVER_NAME_OFFSET_IN_NT_CHALLENGE_RESPONSE -
NTLM_V2_SERVER_NAME_RESERVED_LENGTH_IN_NT_CHALLENGE_RESPONSE);
}
// retrieve the time of client
ICollection<AV_PAIR> targetInfo =
NlmpUtility.BytesGetAvPairCollection(this.challenge.Payload.TargetInfo);
// retrieve the time
authenticateInformation.ClientTime = NlmpUtility.GetTime(targetInfo);
// if server did not response the timestamp, use the client time stamp
if (!NlmpUtility.AvPairContains(targetInfo, AV_PAIR_IDs.MsvAvTimestamp)
&& authenticateInformation.Version == NlmpVersion.v2)
{
authenticateInformation.ClientTime = BitConverter.ToUInt64(
ArrayUtility.SubArray<byte>(authenticatePacket.Payload.NtChallengeResponse,
NTLM_V2_TIME_STAMP_OFFSET_IN_NT_CHALLENGE_RESPONSE, TIME_STAMP_LENGTH), 0);
}
return authenticateInformation;
}
/// <summary>
/// after successfully authenticate, initialize the keys and handles
/// </summary>
/// <param name="exportedSessionKey">the exported key to initialize the keys and handles</param>
private void InitializeKeys(byte[] exportedSessionKey)
{
// initialize keys
this.nlmpServer.Context.ClientSigningKey =
NlmpUtility.SignKey(this.nlmpServer.Context.NegFlg, exportedSessionKey, "Client");
this.nlmpServer.Context.ServerSigningKey =
NlmpUtility.SignKey(this.nlmpServer.Context.NegFlg, exportedSessionKey, "Server");
this.nlmpServer.Context.ClientSealingKey =
NlmpUtility.SealKey(this.nlmpServer.Context.NegFlg, exportedSessionKey, "Client");
this.nlmpServer.Context.ServerSealingKey =
NlmpUtility.SealKey(this.nlmpServer.Context.NegFlg, exportedSessionKey, "Server");
// initialize handles
NlmpUtility.RC4Init(this.nlmpServer.Context.ClientHandle, this.nlmpServer.Context.ClientSealingKey);
NlmpUtility.RC4Init(this.nlmpServer.Context.ServerHandle, this.nlmpServer.Context.ServerSealingKey);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlSchemas.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Globalization;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Diagnostics;
using System.Threading;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security;
using System.Net;
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSchemas : CollectionBase, IEnumerable<XmlSchema> {
XmlSchemaSet schemaSet;
Hashtable references;
SchemaObjectCache cache; // cached schema top-level items
bool shareTypes;
Hashtable mergedSchemas;
internal Hashtable delayedSchemas = new Hashtable();
bool isCompiled = false;
static volatile XmlSchema xsd;
static volatile XmlSchema xml;
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.this"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema this[int index] {
get { return (XmlSchema)List[index]; }
set { List[index] = value; }
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.this1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema this[string ns] {
get {
IList values = (IList)SchemaSet.Schemas(ns);
if (values.Count == 0)
return null;
if (values.Count == 1)
return (XmlSchema)values[0];
throw new InvalidOperationException(Res.GetString(Res.XmlSchemaDuplicateNamespace, ns));
}
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.GetSchemas"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public IList GetSchemas(string ns) {
return (IList)SchemaSet.Schemas(ns);
}
internal SchemaObjectCache Cache {
get {
if (cache == null)
cache = new SchemaObjectCache();
return cache;
}
}
internal Hashtable MergedSchemas {
get {
if (mergedSchemas == null)
mergedSchemas = new Hashtable();
return mergedSchemas;
}
}
internal Hashtable References {
get {
if (references == null)
references = new Hashtable();
return references;
}
}
internal XmlSchemaSet SchemaSet {
get {
if (schemaSet == null) {
schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = null;
schemaSet.ValidationEventHandler += new ValidationEventHandler(IgnoreCompileErrors);
}
return schemaSet;
}
}
internal int Add(XmlSchema schema, bool delay) {
if (delay) {
if (delayedSchemas[schema] == null)
delayedSchemas.Add(schema, schema);
return -1;
}
else {
return Add(schema);
}
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Add"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Add(XmlSchema schema) {
if (List.Contains(schema))
return List.IndexOf(schema);
return List.Add(schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Add"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Add(XmlSchema schema, Uri baseUri) {
if (List.Contains(schema))
return List.IndexOf(schema);
if (baseUri != null)
schema.BaseUri = baseUri;
return List.Add(schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Add1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Add(XmlSchemas schemas) {
foreach (XmlSchema schema in schemas) {
Add(schema);
}
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.AddReference"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void AddReference(XmlSchema schema) {
References[schema] = schema;
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Insert"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Insert(int index, XmlSchema schema) {
List.Insert(index, schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.IndexOf"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(XmlSchema schema) {
return List.IndexOf(schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(XmlSchema schema) {
return List.Contains(schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Contains1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(string targetNamespace) {
return SchemaSet.Contains(targetNamespace);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Remove"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(XmlSchema schema) {
List.Remove(schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(XmlSchema[] array, int index) {
List.CopyTo(array, index);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnInsert"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnInsert(int index, object value) {
AddName((XmlSchema)value);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnRemove"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnRemove(int index, object value) {
RemoveName((XmlSchema)value);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnClear"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnClear() {
schemaSet = null;
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnSet"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnSet(int index, object oldValue, object newValue) {
RemoveName((XmlSchema)oldValue);
AddName((XmlSchema)newValue);
}
void AddName(XmlSchema schema) {
if (isCompiled) throw new InvalidOperationException(Res.GetString(Res.XmlSchemaCompiled));
if (SchemaSet.Contains(schema))
SchemaSet.Reprocess(schema);
else {
Prepare(schema);
SchemaSet.Add(schema);
}
}
void Prepare(XmlSchema schema) {
// need to remove illegal <import> externals;
ArrayList removes = new ArrayList();
string ns = schema.TargetNamespace;
foreach (XmlSchemaExternal external in schema.Includes) {
if (external is XmlSchemaImport) {
if (ns == ((XmlSchemaImport)external).Namespace) {
removes.Add(external);
}
}
}
foreach(XmlSchemaObject o in removes) {
schema.Includes.Remove(o);
}
}
void RemoveName(XmlSchema schema) {
SchemaSet.Remove(schema);
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Find"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Find(XmlQualifiedName name, Type type) {
return Find(name, type, true);
}
internal object Find(XmlQualifiedName name, Type type, bool checkCache) {
if (!IsCompiled) {
foreach (XmlSchema schema in List) {
Preprocess(schema);
}
}
IList values = (IList)SchemaSet.Schemas(name.Namespace);
if (values == null) return null;
foreach (XmlSchema schema in values) {
Preprocess(schema);
XmlSchemaObject ret = null;
if (typeof(XmlSchemaType).IsAssignableFrom(type)) {
ret = schema.SchemaTypes[name];
if (ret == null || !type.IsAssignableFrom(ret.GetType())) {
continue;
}
}
else if (type == typeof(XmlSchemaGroup)) {
ret = schema.Groups[name];
}
else if (type == typeof(XmlSchemaAttributeGroup)) {
ret = schema.AttributeGroups[name];
}
else if (type == typeof(XmlSchemaElement)) {
ret = schema.Elements[name];
}
else if (type == typeof(XmlSchemaAttribute)) {
ret = schema.Attributes[name];
}
else if (type == typeof(XmlSchemaNotation)) {
ret = schema.Notations[name];
}
#if DEBUG
else {
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "XmlSchemas.Find: Invalid object type " + type.FullName));
}
#endif
if (ret != null && shareTypes && checkCache && !IsReference(ret))
ret = Cache.AddItem(ret, name, this);
if (ret != null) {
return ret;
}
}
return null;
}
IEnumerator<XmlSchema> IEnumerable<XmlSchema>.GetEnumerator() {
return new XmlSchemaEnumerator(this);
}
internal static void Preprocess(XmlSchema schema) {
if (!schema.IsPreprocessed) {
try {
XmlNameTable nameTable = new System.Xml.NameTable();
Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null);
prep.SchemaLocations = new Hashtable();
prep.Execute(schema, schema.TargetNamespace, false);
}
catch(XmlSchemaException e) {
throw CreateValidationException(e, e.Message);
}
}
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.IsDataSet"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static bool IsDataSet(XmlSchema schema) {
foreach (XmlSchemaObject o in schema.Items) {
if (o is XmlSchemaElement) {
XmlSchemaElement e = (XmlSchemaElement)o;
if (e.UnhandledAttributes != null) {
foreach (XmlAttribute a in e.UnhandledAttributes) {
if (a.LocalName == "IsDataSet" && a.NamespaceURI == "urn:schemas-microsoft-com:xml-msdata") {
// currently the msdata:IsDataSet uses its own format for the boolean values
if (a.Value == "True" || a.Value == "true" || a.Value == "1") return true;
}
}
}
}
}
return false;
}
void Merge(XmlSchema schema) {
if (MergedSchemas[schema] != null)
return;
IList originals = (IList)SchemaSet.Schemas(schema.TargetNamespace);
if (originals != null && originals.Count > 0) {
MergedSchemas.Add(schema, schema);
Merge(originals, schema);
}
else {
Add(schema);
MergedSchemas.Add(schema, schema);
}
}
void AddImport(IList schemas, string ns) {
foreach(XmlSchema s in schemas) {
bool add = true;
foreach (XmlSchemaExternal external in s.Includes) {
if (external is XmlSchemaImport && ((XmlSchemaImport)external).Namespace == ns) {
add = false;
break;
}
}
if (add) {
XmlSchemaImport import = new XmlSchemaImport();
import.Namespace = ns;
s.Includes.Add(import);
}
}
}
void Merge(IList originals, XmlSchema schema) {
foreach (XmlSchema s in originals) {
if (schema == s) {
return;
}
}
foreach (XmlSchemaExternal external in schema.Includes) {
if (external is XmlSchemaImport) {
external.SchemaLocation = null;
if (external.Schema != null) {
Merge(external.Schema);
}
else {
AddImport(originals, ((XmlSchemaImport)external).Namespace);
}
}
else {
if (external.Schema == null) {
// we do not process includes or redefines by the schemaLocation
if (external.SchemaLocation != null) {
throw new InvalidOperationException(Res.GetString(Res.XmlSchemaIncludeLocation, this.GetType().Name, external.SchemaLocation));
}
}
else {
external.SchemaLocation = null;
Merge(originals, external.Schema);
}
}
}
// bring all included items to the parent schema;
bool[] matchedItems = new bool[schema.Items.Count];
int count = 0;
for (int i = 0; i < schema.Items.Count; i++) {
XmlSchemaObject o = schema.Items[i];
XmlSchemaObject dest = Find(o, originals);
if (dest != null) {
if (!Cache.Match(dest, o, shareTypes)) {
//
Debug.WriteLineIf(DiagnosticsSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Failed to Merge " + MergeFailedMessage(o, dest, schema.TargetNamespace)
+ "' Plase Compare hash:\r\n" + Cache.looks[dest] + "\r\n" + Cache.looks[o]);
throw new InvalidOperationException(MergeFailedMessage(o, dest, schema.TargetNamespace));
}
matchedItems[i] = true;
count++;
}
}
if (count != schema.Items.Count) {
XmlSchema destination = (XmlSchema)originals[0];
for (int i = 0; i < schema.Items.Count; i++) {
if (!matchedItems[i]) {
destination.Items.Add(schema.Items[i]);
}
}
destination.IsPreprocessed = false;
Preprocess(destination);
}
}
static string ItemName(XmlSchemaObject o) {
if (o is XmlSchemaNotation) {
return ((XmlSchemaNotation)o).Name;
}
else if (o is XmlSchemaGroup) {
return ((XmlSchemaGroup)o).Name;
}
else if (o is XmlSchemaElement) {
return ((XmlSchemaElement)o).Name;
}
else if (o is XmlSchemaType) {
return ((XmlSchemaType)o).Name;
}
else if (o is XmlSchemaAttributeGroup) {
return ((XmlSchemaAttributeGroup)o).Name;
}
else if (o is XmlSchemaAttribute) {
return ((XmlSchemaAttribute)o).Name;
}
return null;
}
internal static XmlQualifiedName GetParentName(XmlSchemaObject item) {
while (item.Parent != null) {
if (item.Parent is XmlSchemaType) {
XmlSchemaType type = (XmlSchemaType)item.Parent;
if (type.Name != null && type.Name.Length != 0) {
return type.QualifiedName;
}
}
item = item.Parent;
}
return XmlQualifiedName.Empty;
}
static string GetSchemaItem(XmlSchemaObject o, string ns, string details) {
if (o == null) {
return null;
}
while (o.Parent != null && !(o.Parent is XmlSchema)) {
o = o.Parent;
}
if (ns == null || ns.Length == 0) {
XmlSchemaObject tmp = o;
while (tmp.Parent != null) {
tmp = tmp.Parent;
}
if (tmp is XmlSchema) {
ns = ((XmlSchema)tmp).TargetNamespace;
}
}
string item = null;
if (o is XmlSchemaNotation) {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details);
}
else if (o is XmlSchemaGroup) {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, "group", ((XmlSchemaGroup)o).Name, details);
}
else if (o is XmlSchemaElement) {
XmlSchemaElement e = ((XmlSchemaElement)o);
if (e.Name == null || e.Name.Length == 0) {
XmlQualifiedName parentName = XmlSchemas.GetParentName(o);
// Element reference '{0}' declared in schema type '{1}' from namespace '{2}'
item = Res.GetString(Res.XmlSchemaElementReference, e.RefName.ToString(), parentName.Name, parentName.Namespace);
}
else {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, "element", e.Name, details);
}
}
else if (o is XmlSchemaType) {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, o.GetType() == typeof(XmlSchemaSimpleType) ? "simpleType" : "complexType", ((XmlSchemaType)o).Name, null);
}
else if (o is XmlSchemaAttributeGroup) {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, "attributeGroup", ((XmlSchemaAttributeGroup)o).Name, details);
}
else if (o is XmlSchemaAttribute) {
XmlSchemaAttribute a = ((XmlSchemaAttribute)o);
if (a.Name == null || a.Name.Length == 0) {
XmlQualifiedName parentName = XmlSchemas.GetParentName(o);
// Attribure reference '{0}' declared in schema type '{1}' from namespace '{2}'
return Res.GetString(Res.XmlSchemaAttributeReference, a.RefName.ToString(), parentName.Name, parentName.Namespace);
}
else {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, "attribute", a.Name, details);
}
}
else if (o is XmlSchemaContent) {
XmlQualifiedName parentName = XmlSchemas.GetParentName(o);
// Check content definition of schema type '{0}' from namespace '{1}'. {2}
item = Res.GetString(Res.XmlSchemaContentDef, parentName.Name, parentName.Namespace, null);
}
else if (o is XmlSchemaExternal) {
string itemType = o is XmlSchemaImport ? "import" : o is XmlSchemaInclude ? "include" : o is XmlSchemaRedefine ? "redefine" : o.GetType().Name;
item = Res.GetString(Res.XmlSchemaItem, ns, itemType, details);
}
else if (o is XmlSchema) {
item = Res.GetString(Res.XmlSchema, ns, details);
}
else {
item = Res.GetString(Res.XmlSchemaNamedItem, ns, o.GetType().Name, null, details);
}
return item;
}
static string Dump(XmlSchemaObject o) {
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlSerializer s = new XmlSerializer(o.GetType());
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlWriter xmlWriter = XmlWriter.Create(sw, settings);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xs", XmlSchema.Namespace);
s.Serialize(xmlWriter, o, ns);
return sw.ToString();
}
static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string ns) {
string err = Res.GetString(Res.XmlSerializableMergeItem, ns, GetSchemaItem(src, ns, null));
err += "\r\n" + Dump(src);
err += "\r\n" + Dump(dest);
return err;
}
internal XmlSchemaObject Find(XmlSchemaObject o, IList originals) {
string name = ItemName(o);
if (name == null)
return null;
Type type = o.GetType();
foreach (XmlSchema s in originals) {
foreach(XmlSchemaObject item in s.Items) {
if (item.GetType() == type && name == ItemName(item)) {
return item;
}
}
}
return null;
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.IsCompiled"]/*' />
public bool IsCompiled {
get { return isCompiled; }
}
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Compile"]/*' />
public void Compile(ValidationEventHandler handler, bool fullCompile) {
if (isCompiled)
return;
foreach(XmlSchema s in delayedSchemas.Values)
Merge(s);
delayedSchemas.Clear();
if (fullCompile) {
schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = null;
schemaSet.ValidationEventHandler += handler;
foreach (XmlSchema s in References.Values)
schemaSet.Add(s);
int schemaCount = schemaSet.Count;
foreach (XmlSchema s in List) {
if (!SchemaSet.Contains(s)) {
schemaSet.Add(s);
schemaCount++;
}
}
if (!SchemaSet.Contains(XmlSchema.Namespace)) {
AddReference(XsdSchema);
schemaSet.Add(XsdSchema);
schemaCount++;
}
if (!SchemaSet.Contains(XmlReservedNs.NsXml)) {
AddReference(XmlSchema);
schemaSet.Add(XmlSchema);
schemaCount++;
}
schemaSet.Compile();
schemaSet.ValidationEventHandler -= handler;
isCompiled = schemaSet.IsCompiled && schemaCount == schemaSet.Count;
}
else {
try {
XmlNameTable nameTable = new System.Xml.NameTable();
Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null);
prep.XmlResolver = null;
prep.SchemaLocations = new Hashtable();
prep.ChameleonSchemas = new Hashtable();
foreach (XmlSchema schema in SchemaSet.Schemas()) {
prep.Execute(schema, schema.TargetNamespace, true);
}
}
catch(XmlSchemaException e) {
throw CreateValidationException(e, e.Message);
}
}
}
internal static Exception CreateValidationException(XmlSchemaException exception, string message) {
XmlSchemaObject source = exception.SourceSchemaObject;
if (exception.LineNumber == 0 && exception.LinePosition == 0) {
throw new InvalidOperationException(GetSchemaItem(source, null, message), exception);
}
else {
string ns = null;
if (source != null) {
while (source.Parent != null) {
source = source.Parent;
}
if (source is XmlSchema) {
ns = ((XmlSchema)source).TargetNamespace;
}
}
throw new InvalidOperationException(Res.GetString(Res.XmlSchemaSyntaxErrorDetails, ns, message, exception.LineNumber, exception.LinePosition), exception);
}
}
internal static void IgnoreCompileErrors(object sender, ValidationEventArgs args) {
return;
}
internal static XmlSchema XsdSchema {
get {
if (xsd == null) {
xsd = CreateFakeXsdSchema(XmlSchema.Namespace, "schema");
}
return xsd;
}
}
internal static XmlSchema XmlSchema {
get {
if (xml == null) {
xml = XmlSchema.Read(new StringReader(xmlSchema), null);
}
return xml;
}
}
private static XmlSchema CreateFakeXsdSchema(string ns, string name) {
/* Create fake xsd schema to fool the XmlSchema.Compiler
<xsd:schema targetNamespace="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="schema">
<xsd:complexType />
</xsd:element>
</xsd:schema>
*/
XmlSchema schema = new XmlSchema();
schema.TargetNamespace = ns;
XmlSchemaElement element = new XmlSchemaElement();
element.Name = name;
XmlSchemaComplexType type = new XmlSchemaComplexType();
element.SchemaType = type;
schema.Items.Add(element);
return schema;
}
internal void SetCache(SchemaObjectCache cache, bool shareTypes) {
this.shareTypes = shareTypes;
this.cache = cache;
if (shareTypes) {
cache.GenerateSchemaGraph(this);
}
}
internal bool IsReference(XmlSchemaObject type) {
XmlSchemaObject parent = type;
while (parent.Parent != null) {
parent = parent.Parent;
}
return References.Contains(parent);
}
internal const string xmlSchema = @"<?xml version='1.0' encoding='UTF-8' ?>
<xs:schema targetNamespace='http://www.w3.org/XML/1998/namespace' xmlns:xs='http://www.w3.org/2001/XMLSchema' xml:lang='en'>
<xs:attribute name='lang' type='xs:language'/>
<xs:attribute name='space'>
<xs:simpleType>
<xs:restriction base='xs:NCName'>
<xs:enumeration value='default'/>
<xs:enumeration value='preserve'/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name='base' type='xs:anyURI'/>
<xs:attribute name='id' type='xs:ID' />
<xs:attributeGroup name='specialAttrs'>
<xs:attribute ref='xml:base'/>
<xs:attribute ref='xml:lang'/>
<xs:attribute ref='xml:space'/>
</xs:attributeGroup>
</xs:schema>";
}
public class XmlSchemaEnumerator : IEnumerator<XmlSchema>, System.Collections.IEnumerator {
private XmlSchemas list;
private int idx, end;
public XmlSchemaEnumerator(XmlSchemas list) {
this.list = list;
this.idx = -1;
this.end = list.Count - 1;
}
public void Dispose() {
}
public bool MoveNext() {
if (this.idx >= this.end)
return false;
this.idx++;
return true;
}
public XmlSchema Current {
get { return this.list[this.idx]; }
}
object System.Collections.IEnumerator.Current {
get { return this.list[this.idx]; }
}
void System.Collections.IEnumerator.Reset() {
this.idx = -1;
}
}
}
| |
/*
* 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using RestSharp;
using System.Text.RegularExpressions;
using QuantConnect.Logging;
using QuantConnect.Orders.Fees;
using QuantConnect.Util;
namespace QuantConnect.Brokerages.GDAX
{
public partial class GDAXBrokerage
{
#region Declarations
/// <summary>
/// Collection of partial split messages
/// </summary>
public ConcurrentDictionary<long, GDAXFill> FillSplit { get; set; }
private readonly string _passPhrase;
private const string SymbolMatching = "ETH|LTC|BTC|BCH";
private readonly IAlgorithm _algorithm;
private readonly CancellationTokenSource _canceller = new CancellationTokenSource();
private readonly ConcurrentQueue<WebSocketMessage> _messageBuffer = new ConcurrentQueue<WebSocketMessage>();
private volatile bool _streamLocked;
private readonly ConcurrentDictionary<Symbol, OrderBook> _orderBooks = new ConcurrentDictionary<Symbol, OrderBook>();
private readonly bool _isDataQueueHandler;
// GDAX has different rate limits for public and private endpoints
// https://docs.gdax.com/#rate-limits
internal enum GdaxEndpointType { Public, Private }
private readonly RateGate _publicEndpointRateLimiter = new RateGate(6, TimeSpan.FromSeconds(1));
private readonly RateGate _privateEndpointRateLimiter = new RateGate(10, TimeSpan.FromSeconds(1));
// order ids needed for market order fill tracking
private string _pendingGdaxMarketOrderId;
private int _pendingLeanMarketOrderId;
/// <summary>
/// Rest client used to call missing conversion rates
/// </summary>
public IRestClient RateClient { get; set; }
#endregion
/// <summary>
/// The list of websocket channels to subscribe
/// </summary>
protected virtual string[] ChannelNames { get; } = { "heartbeat", "user", "matches" };
/// <summary>
/// Locking object for the Ticks list in the data queue handler
/// </summary>
protected readonly object TickLocker = new object();
/// <summary>
/// Constructor for brokerage
/// </summary>
/// <param name="wssUrl">websockets url</param>
/// <param name="websocket">instance of websockets client</param>
/// <param name="restClient">instance of rest client</param>
/// <param name="apiKey">api key</param>
/// <param name="apiSecret">api secret</param>
/// <param name="passPhrase">pass phrase</param>
/// <param name="algorithm">the algorithm instance is required to retreive account type</param>
public GDAXBrokerage(string wssUrl, IWebSocket websocket, IRestClient restClient, string apiKey, string apiSecret, string passPhrase, IAlgorithm algorithm)
: base(wssUrl, websocket, restClient, apiKey, apiSecret, Market.GDAX, "GDAX")
{
FillSplit = new ConcurrentDictionary<long, GDAXFill>();
_passPhrase = passPhrase;
_algorithm = algorithm;
RateClient = new RestClient("http://data.fixer.io/api/latest?base=usd&access_key=26a2eb9f13db3f14b6df6ec2379f9261");
WebSocket.Open += (sender, args) =>
{
var tickers = new[]
{
"LTCUSD", "LTCEUR", "LTCBTC",
"BTCUSD", "BTCEUR", "BTCGBP",
"ETHBTC", "ETHUSD", "ETHEUR",
"BCHBTC", "BCHUSD", "BCHEUR"
};
Subscribe(tickers.Select(ticker => Symbol.Create(ticker, SecurityType.Crypto, Market.GDAX)));
};
_isDataQueueHandler = this is GDAXDataQueueHandler;
}
/// <summary>
/// Lock the streaming processing while we're sending orders as sometimes they fill before the REST call returns.
/// </summary>
public void LockStream()
{
Log.Trace("GDAXBrokerage.Messaging.LockStream(): Locking Stream");
_streamLocked = true;
}
/// <summary>
/// Unlock stream and process all backed up messages.
/// </summary>
public void UnlockStream()
{
Log.Trace("GDAXBrokerage.Messaging.UnlockStream(): Processing Backlog...");
while (_messageBuffer.Any())
{
WebSocketMessage e;
_messageBuffer.TryDequeue(out e);
OnMessageImpl(this, e);
}
Log.Trace("GDAXBrokerage.Messaging.UnlockStream(): Stream Unlocked.");
// Once dequeued in order; unlock stream.
_streamLocked = false;
}
/// <summary>
/// Wss message handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public override void OnMessage(object sender, WebSocketMessage e)
{
// Verify if we're allowed to handle the streaming packet yet; while we're placing an order we delay the
// stream processing a touch.
try
{
if (_streamLocked)
{
_messageBuffer.Enqueue(e);
return;
}
}
catch (Exception err)
{
Log.Error(err);
}
OnMessageImpl(sender, e);
}
/// <summary>
/// Implementation of the OnMessage event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMessageImpl(object sender, WebSocketMessage e)
{
try
{
var raw = JsonConvert.DeserializeObject<Messages.BaseMessage>(e.Message, JsonSettings);
LastHeartbeatUtcTime = DateTime.UtcNow;
if (raw.Type == "heartbeat")
{
return;
}
else if (raw.Type == "snapshot")
{
OnSnapshot(e.Message);
return;
}
else if (raw.Type == "l2update")
{
OnL2Update(e.Message);
return;
}
else if (raw.Type == "error")
{
Log.Error($"GDAXBrokerage.OnMessage.error(): Data: {Environment.NewLine}{e.Message}");
var error = JsonConvert.DeserializeObject<Messages.Error>(e.Message, JsonSettings);
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, $"GDAXBrokerage.OnMessage: {error.Message} {error.Reason}"));
return;
}
else if (raw.Type == "match")
{
OrderMatch(e.Message);
return;
}
else if (raw.Type == "open" || raw.Type == "change" || raw.Type == "done" || raw.Type == "received" || raw.Type == "subscriptions" || raw.Type == "last_match")
{
//known messages we don't need to handle or log
return;
}
Log.Trace($"GDAXWebsocketsBrokerage.OnMessage: Unexpected message format: {e.Message}");
}
catch (Exception exception)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}"));
throw;
}
}
private void OnSnapshot(string data)
{
try
{
var message = JsonConvert.DeserializeObject<Messages.Snapshot>(data);
var symbol = ConvertProductId(message.ProductId);
OrderBook orderBook;
if (!_orderBooks.TryGetValue(symbol, out orderBook))
{
orderBook = new OrderBook(symbol);
_orderBooks[symbol] = orderBook;
}
else
{
orderBook.BestBidAskUpdated -= OnBestBidAskUpdated;
orderBook.Clear();
}
foreach (var row in message.Bids)
{
var price = decimal.Parse(row[0], NumberStyles.Float, CultureInfo.InvariantCulture);
var size = decimal.Parse(row[1], NumberStyles.Float, CultureInfo.InvariantCulture);
orderBook.UpdateBidRow(price, size);
}
foreach (var row in message.Asks)
{
var price = decimal.Parse(row[0], NumberStyles.Float, CultureInfo.InvariantCulture);
var size = decimal.Parse(row[1], NumberStyles.Float, CultureInfo.InvariantCulture);
orderBook.UpdateAskRow(price, size);
}
orderBook.BestBidAskUpdated += OnBestBidAskUpdated;
if (_isDataQueueHandler)
{
EmitQuoteTick(symbol, orderBook.BestBidPrice, orderBook.BestBidSize, orderBook.BestAskPrice, orderBook.BestAskSize);
}
}
catch (Exception e)
{
Log.Error(e);
throw;
}
}
private void OnBestBidAskUpdated(object sender, BestBidAskUpdatedEventArgs e)
{
if (_isDataQueueHandler)
{
EmitQuoteTick(e.Symbol, e.BestBidPrice, e.BestBidSize, e.BestAskPrice, e.BestAskSize);
}
}
private void OnL2Update(string data)
{
try
{
var message = JsonConvert.DeserializeObject<Messages.L2Update>(data);
var symbol = ConvertProductId(message.ProductId);
var orderBook = _orderBooks[symbol];
foreach (var row in message.Changes)
{
var side = row[0];
var price = Convert.ToDecimal(row[1], CultureInfo.InvariantCulture);
var size = decimal.Parse(row[2], NumberStyles.Float, CultureInfo.InvariantCulture);
if (side == "buy")
{
if (size == 0)
{
orderBook.RemoveBidRow(price);
}
else
{
orderBook.UpdateBidRow(price, size);
}
}
else if (side == "sell")
{
if (size == 0)
{
orderBook.RemoveAskRow(price);
}
else
{
orderBook.UpdateAskRow(price, size);
}
}
}
}
catch (Exception e)
{
Log.Error(e, "Data: " + data);
throw;
}
}
private void OrderMatch(string data)
{
// deserialize the current match (trade) message
var message = JsonConvert.DeserializeObject<Messages.Matched>(data, JsonSettings);
if (_isDataQueueHandler)
{
EmitTradeTick(message);
}
// check the list of currently active orders, if the current trade is ours we are either a maker or a taker
var currentOrder = CachedOrderIDs
.FirstOrDefault(o => o.Value.BrokerId.Contains(message.MakerOrderId) || o.Value.BrokerId.Contains(message.TakerOrderId));
if (_pendingGdaxMarketOrderId != null &&
// order fill for other users
(currentOrder.Value == null ||
// order fill for other order of ours (less likely but may happen)
currentOrder.Value.BrokerId[0] != _pendingGdaxMarketOrderId))
{
// process all fills for our pending market order
var fills = FillSplit[_pendingLeanMarketOrderId];
var fillMessages = fills.Messages;
for (var i = 0; i < fillMessages.Count; i++)
{
var fillMessage = fillMessages[i];
var isFinalFill = i == fillMessages.Count - 1;
// emit all order events with OrderStatus.PartiallyFilled except for the last one which has OrderStatus.Filled
EmitFillOrderEvent(fillMessage, fills.Order.Symbol, fills, isFinalFill);
}
// clear the pending market order
_pendingGdaxMarketOrderId = null;
_pendingLeanMarketOrderId = 0;
}
if (currentOrder.Value == null)
{
// not our order, nothing else to do here
return;
}
Log.Trace($"GDAXBrokerage.OrderMatch(): Match: {message.ProductId} {data}");
var order = currentOrder.Value;
if (order.Type == OrderType.Market)
{
// Fill events for this order will be delayed until we receive messages for a different order,
// so we can know which is the last fill.
// The market order total filled quantity can be less than the total order quantity,
// details here: https://github.com/QuantConnect/Lean/issues/1751
// do not process market order fills immediately, save off the order ids
_pendingGdaxMarketOrderId = order.BrokerId[0];
_pendingLeanMarketOrderId = order.Id;
}
if (!FillSplit.ContainsKey(order.Id))
{
FillSplit[order.Id] = new GDAXFill(order);
}
var split = FillSplit[order.Id];
split.Add(message);
if (order.Type != OrderType.Market)
{
var symbol = ConvertProductId(message.ProductId);
// is this the total order at once? Is this the last split fill?
var isFinalFill = Math.Abs(message.Size) == Math.Abs(order.Quantity) || Math.Abs(split.OrderQuantity) == Math.Abs(split.TotalQuantity);
EmitFillOrderEvent(message, symbol, split, isFinalFill);
}
}
private void EmitFillOrderEvent(Messages.Matched message, Symbol symbol, GDAXFill split, bool isFinalFill)
{
var order = split.Order;
var status = isFinalFill ? OrderStatus.Filled : OrderStatus.PartiallyFilled;
OrderDirection direction;
// Messages are always from the perspective of the market maker. Flip direction if executed as a taker.
if (order.BrokerId[0] == message.TakerOrderId)
{
direction = message.Side == "sell" ? OrderDirection.Buy : OrderDirection.Sell;
}
else
{
direction = message.Side == "sell" ? OrderDirection.Sell : OrderDirection.Buy;
}
var fillPrice = message.Price;
var fillQuantity = direction == OrderDirection.Sell ? -message.Size : message.Size;
var isMaker = order.BrokerId[0] == message.MakerOrderId;
var orderFee = GetFillFee(symbol, fillPrice, fillQuantity, isMaker);
var orderEvent = new OrderEvent
(
order.Id, symbol, message.Time, status,
direction, fillPrice, fillQuantity,
orderFee, $"GDAX Match Event {direction}"
);
// when the order is completely filled, we no longer need it in the active order list
if (orderEvent.Status == OrderStatus.Filled)
{
Order outOrder;
CachedOrderIDs.TryRemove(order.Id, out outOrder);
}
OnOrderEvent(orderEvent);
}
/// <summary>
/// Retrieves a price tick for a given symbol
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
public Tick GetTick(Symbol symbol)
{
var req = new RestRequest($"/products/{ConvertSymbol(symbol)}/ticker", Method.GET);
var response = ExecuteRestRequest(req, GdaxEndpointType.Public);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception($"GDAXBrokerage.GetTick: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
var tick = JsonConvert.DeserializeObject<Messages.Tick>(response.Content);
return new Tick(tick.Time, symbol, tick.Bid, tick.Ask) { Quantity = tick.Volume };
}
/// <summary>
/// Emits a new quote tick
/// </summary>
/// <param name="symbol">The symbol</param>
/// <param name="bidPrice">The bid price</param>
/// <param name="bidSize">The bid size</param>
/// <param name="askPrice">The ask price</param>
/// <param name="askSize">The ask price</param>
private void EmitQuoteTick(Symbol symbol, decimal bidPrice, decimal bidSize, decimal askPrice, decimal askSize)
{
lock (TickLocker)
{
Ticks.Add(new Tick
{
AskPrice = askPrice,
BidPrice = bidPrice,
Value = (askPrice + bidPrice) / 2m,
Time = DateTime.UtcNow,
Symbol = symbol,
TickType = TickType.Quote,
AskSize = askSize,
BidSize = bidSize
});
}
}
/// <summary>
/// Emits a new trade tick from a match message
/// </summary>
private void EmitTradeTick(Messages.Matched message)
{
var symbol = ConvertProductId(message.ProductId);
lock (TickLocker)
{
Ticks.Add(new Tick
{
Value = message.Price,
Time = DateTime.UtcNow,
Symbol = symbol,
TickType = TickType.Trade,
Quantity = message.Size
});
}
}
/// <summary>
/// Creates websocket message subscriptions for the supplied symbols
/// </summary>
public override void Subscribe(IEnumerable<Symbol> symbols)
{
foreach (var item in symbols)
{
if (item.Value.Contains("UNIVERSE") ||
item.SecurityType != SecurityType.Forex && item.SecurityType != SecurityType.Crypto)
{
continue;
}
if (!IsSubscribeAvailable(item))
{
//todo: refactor this outside brokerage
//alternative service: http://openexchangerates.org/latest.json
PollTick(item);
}
else
{
this.ChannelList[item.Value] = new Channel { Name = item.Value, Symbol = item.Value };
}
}
var products = ChannelList.Select(s => s.Value.Symbol.Substring(0, 3) + "-" + s.Value.Symbol.Substring(3)).ToArray();
var payload = new
{
type = "subscribe",
product_ids = products,
channels = ChannelNames
};
if (payload.product_ids.Length == 0)
{
return;
}
var token = GetAuthenticationToken(JsonConvert.SerializeObject(payload), "GET", "/users/self/verify");
var json = JsonConvert.SerializeObject(new
{
type = payload.type,
channels = payload.channels,
product_ids = payload.product_ids,
SignHeader = token.Signature,
KeyHeader = ApiKey,
PassHeader = _passPhrase,
TimeHeader = token.Timestamp
});
WebSocket.Send(json);
Log.Trace("GDAXBrokerage.Subscribe: Sent subscribe.");
}
/// <summary>
/// Poll for new tick to refresh conversion rate of non-USD denomination
/// </summary>
/// <param name="symbol"></param>
public void PollTick(Symbol symbol)
{
int delay = 36000000;
var token = _canceller.Token;
var listener = Task.Factory.StartNew(() =>
{
Log.Trace($"GDAXBrokerage.PollLatestTick: started polling for ticks: {symbol.Value}");
while (true)
{
var rate = GetConversionRate(symbol.Value.Replace("USD", ""));
lock (TickLocker)
{
var latest = new Tick
{
Value = rate,
Time = DateTime.UtcNow,
Symbol = symbol
};
Ticks.Add(latest);
}
Thread.Sleep(delay);
if (token.IsCancellationRequested) break;
}
Log.Trace($"PollLatestTick: stopped polling for ticks: {symbol.Value}");
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private decimal GetConversionRate(string currency)
{
var response = RateClient.Execute(new RestSharp.RestRequest(Method.GET));
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode, "GetConversionRate: error returned from conversion rate service."));
return 0;
}
var raw = JsonConvert.DeserializeObject<JObject>(response.Content);
var rate = raw.SelectToken("rates." + currency).Value<decimal>();
if (rate == 0)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode, "GetConversionRate: zero value returned from conversion rate service."));
return 0;
}
return 1m / rate;
}
private bool IsSubscribeAvailable(Symbol symbol)
{
return Regex.IsMatch(symbol.Value, SymbolMatching);
}
/// <summary>
/// Ends current subscriptions
/// </summary>
public void Unsubscribe(IEnumerable<Symbol> symbols)
{
if (WebSocket.IsOpen)
{
WebSocket.Send(JsonConvert.SerializeObject(new {type = "unsubscribe", channels = ChannelNames}));
}
}
/// <summary>
/// Returns the fee paid for a total or partial order fill
/// </summary>
public static decimal GetFillFee(Symbol symbol, decimal fillPrice, decimal fillQuantity, bool isMaker)
{
if (isMaker)
{
return 0;
}
return fillPrice * Math.Abs(fillQuantity) * GDAXFeeModel.TakerFee;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D08Level1111 (editable child object).<br/>
/// This is a generated base class of <see cref="D08Level1111"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="D09Level11111Objects"/> of type <see cref="D09Level11111Coll"/> (1:M relation to <see cref="D10Level11111"/>)<br/>
/// This class is an item of <see cref="D07Level1111Coll"/> collection.
/// </remarks>
[Serializable]
public partial class D08Level1111 : BusinessBase<D08Level1111>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_1_ID, "Level_1_1_1_1 ID");
/// <summary>
/// Gets the Level_1_1_1_1 ID.
/// </summary>
/// <value>The Level_1_1_1_1 ID.</value>
public int Level_1_1_1_1_ID
{
get { return GetProperty(Level_1_1_1_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_Name, "Level_1_1_1_1 Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1 Name.
/// </summary>
/// <value>The Level_1_1_1_1 Name.</value>
public string Level_1_1_1_1_Name
{
get { return GetProperty(Level_1_1_1_1_NameProperty); }
set { SetProperty(Level_1_1_1_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D09Level11111SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D09Level11111Child> D09Level11111SingleObjectProperty = RegisterProperty<D09Level11111Child>(p => p.D09Level11111SingleObject, "D09 Level11111 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D09 Level11111 Single Object ("self load" child property).
/// </summary>
/// <value>The D09 Level11111 Single Object.</value>
public D09Level11111Child D09Level11111SingleObject
{
get { return GetProperty(D09Level11111SingleObjectProperty); }
private set { LoadProperty(D09Level11111SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D09Level11111ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D09Level11111ReChild> D09Level11111ASingleObjectProperty = RegisterProperty<D09Level11111ReChild>(p => p.D09Level11111ASingleObject, "D09 Level11111 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D09 Level11111 ASingle Object ("self load" child property).
/// </summary>
/// <value>The D09 Level11111 ASingle Object.</value>
public D09Level11111ReChild D09Level11111ASingleObject
{
get { return GetProperty(D09Level11111ASingleObjectProperty); }
private set { LoadProperty(D09Level11111ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D09Level11111Objects"/> property.
/// </summary>
public static readonly PropertyInfo<D09Level11111Coll> D09Level11111ObjectsProperty = RegisterProperty<D09Level11111Coll>(p => p.D09Level11111Objects, "D09 Level11111 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the D09 Level11111 Objects ("self load" child property).
/// </summary>
/// <value>The D09 Level11111 Objects.</value>
public D09Level11111Coll D09Level11111Objects
{
get { return GetProperty(D09Level11111ObjectsProperty); }
private set { LoadProperty(D09Level11111ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D08Level1111"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D08Level1111"/> object.</returns>
internal static D08Level1111 NewD08Level1111()
{
return DataPortal.CreateChild<D08Level1111>();
}
/// <summary>
/// Factory method. Loads a <see cref="D08Level1111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="D08Level1111"/> object.</returns>
internal static D08Level1111 GetD08Level1111(SafeDataReader dr)
{
D08Level1111 obj = new D08Level1111();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D08Level1111"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private D08Level1111()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D08Level1111"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(D09Level11111SingleObjectProperty, DataPortal.CreateChild<D09Level11111Child>());
LoadProperty(D09Level11111ASingleObjectProperty, DataPortal.CreateChild<D09Level11111ReChild>());
LoadProperty(D09Level11111ObjectsProperty, DataPortal.CreateChild<D09Level11111Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D08Level1111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_1_ID"));
LoadProperty(Level_1_1_1_1_NameProperty, dr.GetString("Level_1_1_1_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(D09Level11111SingleObjectProperty, D09Level11111Child.GetD09Level11111Child(Level_1_1_1_1_ID));
LoadProperty(D09Level11111ASingleObjectProperty, D09Level11111ReChild.GetD09Level11111ReChild(Level_1_1_1_1_ID));
LoadProperty(D09Level11111ObjectsProperty, D09Level11111Coll.GetD09Level11111Coll(Level_1_1_1_1_ID));
}
/// <summary>
/// Inserts a new <see cref="D08Level1111"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD08Level1111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D08Level1111"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD08Level1111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="D08Level1111"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteD08Level1111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(D09Level11111SingleObjectProperty, DataPortal.CreateChild<D09Level11111Child>());
LoadProperty(D09Level11111ASingleObjectProperty, DataPortal.CreateChild<D09Level11111ReChild>());
LoadProperty(D09Level11111ObjectsProperty, DataPortal.CreateChild<D09Level11111Coll>());
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Collections;
// Change history
// 20-Aug-2008: Initialize the matchfound variable to false in the for loop to take care of the situation where a
// transaction is partially matched and no further matching transaction is found. In that case a
// NoMatchFound event should be raised for the balance quantity in the partially matched transaction.
namespace Helpers
{
public interface IStockMatch
{
// Called once before any matching is done
void BeginOperation();
// Called once for each stock before any matching is done
void BeginStock(string stock);
// Called once for each transaction for which a match will be searched.
void BeginMatch(SingleTransaction s);
// Called each time no match is found for a transaction
void NoMatchFound(SingleTransaction s);
// Called each time a matching transaction is found
void MatchFound(SingleTransaction first, SingleTransaction matched, bool firstPartialMatch, bool secondPartialMatch);
// Called once for each stock after all transactions are processed.
void EndStock(string stock);
// Called once when the operation is about to end.
void EndOperation();
}
/// <summary>
/// Summary description for SingleTransaction.
/// </summary>
public class SingleTransaction: IComparable
{
public enum eTransactionType
{
Buy = 0,
Add,
Remove,
Sell,
None,
MaxTranType};
internal eTransactionType transactionType;
internal DateTime transactionDate;
internal string transactionStockCode;
internal long transactionQty;
internal decimal transactionPrice;
internal decimal transactionCharges;
internal bool transactionReconciledFlag;
internal string transactionLotIdentifier;
public string StockCode
{
get
{
return transactionStockCode;
}
}
public decimal UnitCharges
{
get
{
return this.transactionCharges / this.transactionQty;
}
}
public decimal TransactionPrice
{
get
{
return transactionPrice;
}
}
public DateTime TransactionDate
{
get
{
return transactionDate;
}
}
public long TransactionQty
{
get
{
return transactionQty;
}
}
public SingleTransaction()
{
transactionType = SingleTransaction.eTransactionType.None;
transactionQty = 0;
transactionPrice = 0.0M;
transactionCharges = 0.0M;
transactionReconciledFlag = false;
transactionLotIdentifier = "";
transactionStockCode = "";
transactionDate = DateTime.Now;
}
public SingleTransaction(SingleTransaction.eTransactionType tType, DateTime tDate, string tStockCode, long tQty, decimal tPrice, decimal tCharges,string tlotId)
{
transactionType = tType;
transactionStockCode = tStockCode;
transactionQty = tQty;
transactionPrice = tPrice;
transactionCharges = tCharges;
transactionDate = tDate;
transactionReconciledFlag = false;
transactionLotIdentifier = tlotId;
Debug.WriteLine (this, "Constructor of SingleTransaction called");
}
public bool IsAcquisition()
{
return (transactionType == eTransactionType.Buy || transactionType == eTransactionType.Add);
}
public bool IsAddition()
{
return (transactionType == eTransactionType.Add);
}
public bool IsDisposal()
{
return (transactionType == eTransactionType.Sell || transactionType == eTransactionType.Remove);
}
public bool IsRemoval()
{
return (transactionType == eTransactionType.Remove);
}
public bool IsOppositeType(eTransactionType e)
{
return (((e == eTransactionType.Buy || e == eTransactionType.Add) && this.IsDisposal())||
((e == eTransactionType.Sell || e == eTransactionType.Remove) && this.IsAcquisition()));
}
public void Dump()
{
Console.WriteLine("{0,6} {1,15:d} {2,-6} {3,6} {4,20:f} {5,20:f} {6}", transactionStockCode, transactionDate, transactionType.ToString(), transactionQty, transactionPrice, transactionQty * transactionPrice + transactionCharges, transactionLotIdentifier);
}
#region IComparable Members
public int CompareTo(object obj)
{
if (obj is SingleTransaction)
{
SingleTransaction thisTrans = (SingleTransaction) obj;
if (transactionStockCode != thisTrans.transactionStockCode)
return transactionStockCode.CompareTo(thisTrans.transactionStockCode);
int ret = transactionDate.CompareTo(thisTrans.transactionDate);
if (ret != 0)
return ret;
ret = (int)transactionType - (int)thisTrans.transactionType;
if (ret != 0)
return ret;
return transactionLotIdentifier.CompareTo(thisTrans.transactionLotIdentifier);
}
throw new ArgumentException("Object is not SingleTransaction");
}
#endregion
};
public class Account
{
SingleTransaction[] acTransactions;
public Account(int numTrans)
{
if (0 == numTrans)
numTrans = 256;
acTransactions = (SingleTransaction[])Array.CreateInstance(typeof(SingleTransaction),numTrans);
}
int lastTransactionUsed = 0;
public int AddTransaction(SingleTransaction.eTransactionType ttype, DateTime tDate, string tStockCode, long tQty, decimal tPrice, decimal tCharges, string tlotId)
{
// Validations
// Create a new transaction
SingleTransaction thisTrans = new SingleTransaction(ttype,tDate,tStockCode,tQty, tPrice, tCharges, tlotId);
acTransactions[lastTransactionUsed++] = thisTrans;
if (lastTransactionUsed >= acTransactions.GetLength(0))
return -1;
return 0;
} // AddTransaction
public void Dump()
{
foreach (SingleTransaction s in acTransactions)
if (s != null)
s.Dump();
} // Dump
public ArrayList GetStockList()
{
int i = 0;
int numtrans = lastTransactionUsed;
ArrayList stocklist = new ArrayList();
string thisStockName = "";
for (i = 0; i < numtrans; i++)
{
SingleTransaction thisTrans = acTransactions[i];
bool bStockHasBeenProcessed = false;
if (thisStockName == "")
{
//Moving to new stock code. Check if this has been processed already
foreach (String s in stocklist)
{
if (thisTrans.transactionStockCode == s)
{
bStockHasBeenProcessed = true;
break;
}
}
}
if (bStockHasBeenProcessed)
continue;
// this stock has not been processed.
thisStockName = thisTrans.transactionStockCode;
// Done processing all transactions.
stocklist.Add(thisStockName);
thisStockName = "";
}
return stocklist;
} //GetStockList
public void StockTaking(DateTime asofDate, bool bShowZeroBalance)
{
int i = 0;
int numtrans = lastTransactionUsed;
ArrayList stocklist = new ArrayList();
string thisStockName = "";
for (i=0;i<numtrans;i++)
{
SingleTransaction thisTrans = acTransactions[i];
bool bStockHasBeenProcessed = false;
if (thisStockName == "")
{
//Moving to new stock code. Check if this has been processed already
foreach (String s in stocklist)
{
if (thisTrans.transactionStockCode == s)
{
bStockHasBeenProcessed = true;
break;
}
}
}
if (bStockHasBeenProcessed)
continue;
// this stock has not been processed.
thisStockName = thisTrans.transactionStockCode;
//Console.WriteLine("Processing stock {0}", thisStockName);
long nStockQty = 0;
if (thisTrans.transactionType == SingleTransaction.eTransactionType.Buy ||
thisTrans.transactionType == SingleTransaction.eTransactionType.Add )
nStockQty += thisTrans.transactionQty;
else
nStockQty -= thisTrans.transactionQty;
// go through the rest of the transactions
for (int j = i+1; j<numtrans; j++)
{
SingleTransaction thisNextTrans = acTransactions[j];
if (thisNextTrans.transactionStockCode != thisStockName)
continue; //ignore other stock code transactions
// check if the transaction happened before the asofDate
if (thisNextTrans.transactionDate > asofDate)
{
//Console.WriteLine("Transaction happened after as of date. Ignoring");
//thisNextTrans.Dump();
continue; // ignore transactions that happened after asofDate
}
if (thisNextTrans.transactionType == SingleTransaction.eTransactionType.Buy ||
thisNextTrans.transactionType == SingleTransaction.eTransactionType.Add )
nStockQty += thisNextTrans.transactionQty;
else
nStockQty -= thisNextTrans.transactionQty;
}
// Done processing all transactions.
stocklist.Add(thisStockName);
if (nStockQty == 0 && !bShowZeroBalance)
{
thisStockName = "";
continue;
}
Console.WriteLine("Stock balance for {0,6} as of {1,15:d} is {2,15}", thisStockName, asofDate, nStockQty);
thisStockName = "";
}
}// StockTaking
public void CapitalGains(System.DateTime fromdate, System.DateTime todate, int longtermdays)
{
// Sort transactions by stock code.
// Data structure is a Hashtable of StockCode (Key) to ArrayList of SingleTransaction (value)
Hashtable mystocktable = new Hashtable();
if (!SortTransactionsByStockCode(out mystocktable))
return;
decimal totallongterm = 0.0M;
decimal totalshortterm = 0.0M;
// Now process each stock
bool header = true;
bool bAtLeastOneTransForThisStock = false;
foreach (String stock in mystocktable.Keys)
{
ArrayList thisStockTransactions = (ArrayList)mystocktable[stock];
header = true;
bAtLeastOneTransForThisStock = false;
thisStockTransactions.Sort();
bool bfirst = true;
long nStockQty = 0;
decimal longterm = 0.0M;
decimal shortterm = 0.0M;
decimal sUnitBrokerage = 0.0M;
for (int i=0;i< thisStockTransactions.Count;i++)
{
SingleTransaction s = (SingleTransaction)thisStockTransactions[i];
if (s.transactionReconciledFlag)
continue;
sUnitBrokerage = s.transactionCharges/s.transactionQty;
if (bfirst)
{
bfirst = false;
if (!s.IsAcquisition())
Console.WriteLine("First transaction for {0} is not a BUY order. ref {1}", s.transactionStockCode, s.transactionLotIdentifier);
if (s.IsAcquisition())
nStockQty += s.transactionQty;
else
nStockQty -= s.transactionQty;
}
if (s.transactionReconciledFlag)
continue;
if (nStockQty != 0)
{
// find matching transaction
SingleTransaction.eTransactionType thisttype = s.transactionType;
bool restartloop = false;
do
{
restartloop = false;
decimal tlongterm = 0.0M;
decimal tshortterm = 0.0M;
for (int j=i+1; j<thisStockTransactions.Count;j++)
{
SingleTransaction snext = (SingleTransaction)thisStockTransactions[j];
if (snext.transactionReconciledFlag)
continue;
if (!snext.IsOppositeType(thisttype) )
continue;
if (SingleTransaction.ReferenceEquals(s,snext))
continue;
decimal spunit = 0.0M; decimal cpunit = 0.0M;decimal gainlossunit = 0.0M;
if (s.transactionDate.CompareTo(snext.transactionDate) < 0)
{
spunit = snext.transactionPrice - snext.transactionCharges/snext.transactionQty;
cpunit = s.transactionPrice + sUnitBrokerage;
}
else
{
spunit = s.transactionPrice - sUnitBrokerage;
cpunit = snext.transactionPrice + snext.transactionCharges/snext.transactionQty;
}
gainlossunit = spunit - cpunit;
if (nStockQty == snext.transactionQty)
{
SingleTransaction first = null;
if (nStockQty == s.transactionQty)
first = s;
else
first = new SingleTransaction(s.transactionType,s.transactionDate,s.transactionStockCode,nStockQty,s.transactionPrice,s.transactionCharges/s.transactionQty*nStockQty,s.transactionLotIdentifier);
SingleTransaction selltrans = null;
if (first.IsDisposal())
selltrans = first;
else
selltrans = snext;
if (selltrans.transactionDate.CompareTo(fromdate) >= 0 && selltrans.transactionDate.CompareTo(todate) <= 0)
{
TimeSpan ts = new TimeSpan();
ts = snext.transactionDate-first.transactionDate;
if (ts.Days < longtermdays)
{
tshortterm = gainlossunit*nStockQty;
shortterm += tshortterm;
totalshortterm += tshortterm;
tlongterm = 0.0M;
}
else
{
tlongterm = gainlossunit*nStockQty;
longterm += tlongterm;
totallongterm += tlongterm;
tshortterm = 0.0M;
}
Helpers.OutputHelper.PrintGains(first,snext,tshortterm,tlongterm,header);
header = false;
bAtLeastOneTransForThisStock = true;
}
s.transactionReconciledFlag = true;
snext.transactionReconciledFlag = true;
nStockQty = 0;
bfirst = true;
break;
}
else if (nStockQty > snext.transactionQty)
{
long qty = snext.transactionQty;
SingleTransaction first = new SingleTransaction(s.transactionType,s.transactionDate,s.transactionStockCode,qty,s.transactionPrice,s.transactionCharges/s.transactionQty*qty,s.transactionLotIdentifier);
SingleTransaction selltrans = null;
if (first.IsDisposal())
selltrans = first;
else
selltrans = snext;
if (selltrans.transactionDate.CompareTo(fromdate) >= 0 && selltrans.transactionDate.CompareTo(todate) <= 0)
{
TimeSpan ts = new TimeSpan();
ts = snext.transactionDate-first.transactionDate;
if (ts.Days < longtermdays)
{
tshortterm = gainlossunit*qty;
shortterm += tshortterm;
totalshortterm += tshortterm;
tlongterm = 0.0M;
}
else
{
tlongterm = gainlossunit*qty;
longterm += tlongterm;
totallongterm += tlongterm;
tshortterm = 0.0M;
}
Helpers.OutputHelper.PrintGains(first,snext,tshortterm,tlongterm,header);
header = false;
bAtLeastOneTransForThisStock = true;
}
nStockQty -= qty;
snext.transactionReconciledFlag = true;
}
else if (nStockQty < snext.transactionQty)
{
SingleTransaction first = new SingleTransaction(s.transactionType,s.transactionDate,s.transactionStockCode,nStockQty,s.transactionPrice,s.transactionCharges/s.transactionQty*nStockQty,s.transactionLotIdentifier);
SingleTransaction second = new SingleTransaction(snext.transactionType,snext.transactionDate,snext.transactionStockCode,nStockQty,snext.transactionPrice,snext.transactionCharges/snext.transactionQty*nStockQty,snext.transactionLotIdentifier);
SingleTransaction selltrans = null;
if (first.IsDisposal())
selltrans = first;
else
selltrans = second;
int nFrom = selltrans.transactionDate.CompareTo(fromdate);
int nTo = selltrans.transactionDate.CompareTo(todate);
if ( nFrom >= 0 && nTo <= 0)
{
TimeSpan ts = new TimeSpan();
ts = second.transactionDate-first.transactionDate;
if (ts.Days < longtermdays)
{
tshortterm = gainlossunit*nStockQty;
shortterm += tshortterm;
totalshortterm += tshortterm;
tlongterm = 0.0M;
}
else
{
tlongterm = gainlossunit*nStockQty;
longterm += tlongterm;
totallongterm += tlongterm;
tshortterm = 0.0M;
}
Helpers.OutputHelper.PrintGains(first,second,tshortterm,tlongterm,header);
header = false;
bAtLeastOneTransForThisStock = true;
}
nStockQty = snext.transactionQty - nStockQty;
s.transactionReconciledFlag = true;
s = snext;
sUnitBrokerage = s.transactionCharges/s.transactionQty;
thisttype = s.transactionType;
restartloop = true;
break;
}
}
}while (restartloop);
}
else
bfirst = true;
}
if (bAtLeastOneTransForThisStock)
{
Console.WriteLine("{0,110} {1,12:F2} {2,12:F2}", "", shortterm, longterm);
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
}
}
Console.WriteLine("{0,110} {1,12:F2} {2,12:F2}", "", totalshortterm, totallongterm);
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
return;
}// CapitalGains
internal void ResetMatchedTransactions()
{
for (int n = 0; n<lastTransactionUsed; n++)
{
SingleTransaction s = acTransactions[n];
s.transactionReconciledFlag = false;
}
}
public void MatchTransactions(string matchthis, IStockMatch eventSink)
{
ResetMatchedTransactions();
eventSink.BeginOperation();
Hashtable mystocktable;
if (!SortTransactionsByStockCode(out mystocktable))
return;
long nStockQty = 0;
foreach (String stock in mystocktable.Keys)
{
if (matchthis != "" && matchthis != stock)
continue;
ArrayList thisStockTransactions = (ArrayList)mystocktable[stock];
bool bfirst = true;
eventSink.BeginStock(stock);
for (int i = 0; i < thisStockTransactions.Count; i++)
{
SingleTransaction s = (SingleTransaction)thisStockTransactions[i];
if (s.transactionReconciledFlag)
continue;
if (bfirst)
{
bfirst = false;
nStockQty = s.transactionQty;
eventSink.BeginMatch(s);
}
if (s.transactionReconciledFlag)
continue;
if (nStockQty == 0)
continue;
// find matching transaction
SingleTransaction.eTransactionType thisttype = s.transactionType;
bool restartloop = false;
do
{
restartloop = false;
bool matchfound = false;
for (int j = i + 1; j < thisStockTransactions.Count; j++, matchfound = false)
{
SingleTransaction snext = (SingleTransaction)thisStockTransactions[j];
if (snext.transactionReconciledFlag)
continue;
if (!snext.IsOppositeType(thisttype))
continue;
if (SingleTransaction.ReferenceEquals(s, snext))
continue;
matchfound = true;
if (nStockQty == snext.transactionQty)
{
SingleTransaction first = null;
if (nStockQty == s.transactionQty)
first = s;
else
first = new SingleTransaction(s.transactionType, s.transactionDate, s.transactionStockCode, nStockQty, s.transactionPrice, s.transactionCharges / s.transactionQty * nStockQty, s.transactionLotIdentifier);
eventSink.MatchFound(first, snext, false, false);
s.transactionReconciledFlag = true;
snext.transactionReconciledFlag = true;
nStockQty = 0;
bfirst = true;
// A BUY transaction has been completely reconciled with one or more SELL transactions.
// Now we need to start with the next BUY transaction. Hence break out!
break;
}
else if (nStockQty > snext.transactionQty)
{
long qty = snext.transactionQty;
SingleTransaction first = new SingleTransaction(s.transactionType, s.transactionDate, s.transactionStockCode, qty, s.transactionPrice, s.transactionCharges / s.transactionQty * qty, s.transactionLotIdentifier);
eventSink.MatchFound(first, snext, true, false);
nStockQty -= qty;
snext.transactionReconciledFlag = true;
}
else if (nStockQty < snext.transactionQty)
{
SingleTransaction first = new SingleTransaction(s.transactionType, s.transactionDate, s.transactionStockCode, nStockQty, s.transactionPrice, s.transactionCharges / s.transactionQty * nStockQty, s.transactionLotIdentifier);
SingleTransaction second = new SingleTransaction(snext.transactionType, snext.transactionDate, snext.transactionStockCode, nStockQty, snext.transactionPrice, snext.transactionCharges / snext.transactionQty * nStockQty, snext.transactionLotIdentifier);
eventSink.MatchFound(first, second, false, true);
nStockQty = snext.transactionQty - nStockQty;
s.transactionReconciledFlag = true;
s = snext;
// Now the SELL transaction which is at a later date is left with some qty that is not matched. We need to find
// a matching BUY transaction from an earlier date to completely reconcile this SELL transaction. Hence start
// from the beginning of the transaction list.
SingleTransaction begin = new SingleTransaction(s.transactionType, s.transactionDate, s.transactionStockCode, nStockQty, s.transactionPrice, s.transactionCharges / s.transactionQty * nStockQty, s.transactionLotIdentifier);
eventSink.BeginMatch(begin);
thisttype = s.transactionType;
restartloop = true;
break;
}
} // loop on all transactions following the current one we are looking for a match for.
// if there is no matching transaction, the next transaction should still be considered a new one.
if (!matchfound)
{
SingleTransaction sUnmatched = new SingleTransaction(s.transactionType, s.transactionDate, s.transactionStockCode, nStockQty, s.transactionPrice, s.transactionCharges / s.transactionQty * nStockQty, s.transactionLotIdentifier);
s.transactionReconciledFlag = true;
eventSink.NoMatchFound(sUnmatched);
bfirst = true;
}
} while (restartloop);
} // loop on all transactions for current stock
eventSink.EndStock(stock);
} // loop on all stocks
eventSink.EndOperation();
}
private bool SortTransactionsByStockCode(out Hashtable mystocktable)
{
// Sort transactions by stock code.
// Data structure is a Hashtable of StockCode (Key) to ArrayList of SingleTransaction (value)
mystocktable = new Hashtable();
int i = 0;
bool retval = false;
int numtrans = lastTransactionUsed;
for (i = 0; i < numtrans; i++)
{
SingleTransaction thisTrans = acTransactions[i];
ArrayList thisStockTransactions = null;
String thisStockCode = thisTrans.transactionStockCode;
// check if this stock already has a hashtable entry.
if (!mystocktable.ContainsKey(thisTrans.transactionStockCode))
mystocktable.Add(thisTrans.transactionStockCode, (thisStockTransactions = new ArrayList()));
else
thisStockTransactions = (ArrayList)mystocktable[thisStockCode];
thisStockTransactions.Add(thisTrans);
retval = true;
} //for
return retval;
}
}
}
| |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing.Constraints;
using TestHelpers;
using Xunit;
public class FormTagHelperTests
{
[Theory]
[MemberData(nameof(MemberDataFactories.AreaInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.AreaInSubdomainTestData))]
public void CanCreateAreaInSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{area}",
"{controller=Home}/{action=Index}");
}, host, appRoot, controller, action, subdomain, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.ConstraintInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.ConstraintInSubdomainTestData))]
public void CanCreateInlineConstraintInSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{area:bool}",
"{controller=Home}/{action=Index}");
}, host, appRoot, controller, action, subdomain, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.ConstraintInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.ConstraintInSubdomainTestData))]
public void CanCreateParameterConstraintSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{area}",
"{controller=Home}/{action=Index}",
null,
new { area = new BoolRouteConstraint() });
}, host, appRoot, controller, action, subdomain, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.W3ConstraintInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.W3ConstraintInSubdomainTestData))]
public void CanCreateW3InlineConstraintInSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{area:bool}",
"{controller=Home}/{action=Index}");
}, host, appRoot, controller, action, subdomain, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.W3ConstraintInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.W3ConstraintInSubdomainTestData))]
public void CanCreateW3ParameterConstraintSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{area}",
"{controller=Home}/{action=Index}",
null,
new { area = new BoolRouteConstraint() });
}, host, appRoot, controller, action, subdomain, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.ControllerInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.ControllerInSubdomainTestData))]
public void CanCreateControllerInSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{controller}",
"{action=Index}");
}, host, appRoot, subdomain, action, null, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.ConstantSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.ConstantSubdomainTestData))]
public void CanCreateConstantSubdomainFormTagHelper(
string host,
string appRoot,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"constantsubdomain",
"{controller=Home}/{action=Index}");
}, host, appRoot, controller, action, null, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.W3AreaInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.W3AreaInSubdomainTestData))]
public void CanCreateW3AreaInSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{area}",
"{controller=Home}/{action=Index}");
}, host, appRoot, controller, action, subdomain, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.W3ControllerInSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.W3ControllerInSubdomainTestData))]
public void CanCreateW3ControllerInSubdomainFormTagHelper(
string host,
string appRoot,
string subdomain,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"{controller}",
"{action=Index}");
}, host, appRoot, subdomain, action, null, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
[Theory]
[MemberData(nameof(MemberDataFactories.W3ConstantSubdomainTestData.Generate), MemberType = typeof(MemberDataFactories.W3ConstantSubdomainTestData))]
public void CanCreateW3ConstantSubdomainFormTagHelper(
string host,
string appRoot,
string controller,
string action,
string expectedUrl)
{
// Arrange
var helper = ConfigurationFactories.TagHelperFactory.GetForm(routeBuilder =>
{
routeBuilder.MapSubdomainRoute(
new[] { "example.com" },
"default",
"constantsubdomain",
"{controller=Home}/{action=Index}");
}, host, appRoot, controller, action, null, expectedUrl);
var output = ConfigurationFactories.TagHelperOutputFactory.GetForm();
//Act
helper.Process(ConfigurationFactories.TagHelperContextFactory.Get(),
output);
//Assert
Assert.Empty(output.Content.GetContent());
Assert.Equal(expectedUrl, output.Attributes["action"].Value);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToNearestIntegerDouble()
{
var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToNearestIntegerDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static SimpleUnaryOpTest__RoundToNearestIntegerDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__RoundToNearestIntegerDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToNearestInteger(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToNearestInteger(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToNearestInteger(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestInteger), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestInteger), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestInteger), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToNearestInteger(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Sse41.RoundToNearestInteger(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToNearestInteger(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToNearestInteger(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble();
var result = Sse41.RoundToNearestInteger(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToNearestInteger(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[0], MidpointRounding.AwayFromZero)))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[i], MidpointRounding.AwayFromZero)))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestInteger)}<Double>(Vector128<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
#region Apache License, Version 2.0
//
// 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.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.BuildEngine;
using NPanday.ProjectImporter.Verifiers;
using NPanday.Utils;
using NPanday.ProjectImporter.Digest;
using NPanday.ProjectImporter.Digest.Model;
using NPanday.ProjectImporter.Parser;
using NPanday.ProjectImporter.Converter;
using NPanday.ProjectImporter.Converter.Algorithms;
using NPanday.ProjectImporter.Validator;
using NPanday.ProjectImporter.ImportProjectStructureAlgorithms;
using NPanday.ProjectImporter.Parser.SlnParser;
using System.Windows.Forms;
/// Author: Leopoldo Lee Agdeppa III
namespace NPanday.ProjectImporter
{
public class NPandayImporter
{
#region Import Project Type Strategy Pattern
// A strategy pattern with a twists, using c# delegates
delegate string[] ImportProjectTypeDelegate(ProjectDigest[] prjDigests, string solutionFile, string groupId, string artifactId, string version, string scmTag, bool writePom, List<Reference> missingReferences, List<string> nonPortableReferences);
static Dictionary<ProjectStructureType, ImportProjectTypeDelegate> _importProject;
/// <summary>
/// Used for registering the strategies (alogrithms) for importing project type
/// </summary>
static NPandayImporter()
{
// register the algorithms here
_importProject = new Dictionary<ProjectStructureType, ImportProjectTypeDelegate>();
_importProject.Add(ProjectStructureType.AbnormalProject, new AbnormalProject().ImportProjectType);
_importProject.Add(ProjectStructureType.FlatMultiModuleProject, new FlatMultiModuleProject().ImportProjectType);
_importProject.Add(ProjectStructureType.FlatSingleModuleProject, new FlatSingleModuleProject().ImportProjectType);
_importProject.Add(ProjectStructureType.NormalMultiModuleProject, new NormalMultiModuleProject().ImportProjectType);
_importProject.Add(ProjectStructureType.NormalSingleProject, new NormalSingleProject().ImportProjectType);
}
public static string[] ImportProjectType(ProjectStructureType structureType, ProjectDigest[] prjDigests, string solutionFile, string groupId, string artifactId, string version, string scmTag, List<Reference> missingReferences, List<string> nonPortableReferences)
{
return _importProject[structureType](prjDigests, solutionFile, groupId, artifactId, version, scmTag, true, missingReferences, nonPortableReferences);
}
#endregion
#region Import Project Entry
/// <summary>
/// Imports a specified Visual Studio Projects in a Solution to an NPanday Pom,
/// This is the Project-Importer Entry Method
/// </summary>
/// <param name="solutionFile">Path to your Visual Studio Solution File *.sln </param>
/// <param name="groupId">Project Group ID, for maven groupId</param>
/// <param name="artifactId">Project Parent Pom Artifact ID, used as a maven artifact ID for the parent pom.xml</param>
/// <param name="version">Project version, used as a maven version for the entire pom.xmls</param>
/// <returns>An array of generated pom.xml filenames</returns>
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, ref string warningMsg)
{
return ImportProject(solutionFile, groupId, artifactId, version, string.Empty, true, ref warningMsg);
}
/// <summary>
/// Imports a specified Visual Studio Projects in a Solution to an NPanday Pom,
/// This is the Project-Importer Entry Method
/// </summary>
/// <param name="solutionFile">Path to your Visual Studio Solution File *.sln </param>
/// <param name="groupId">Project Group ID, for maven groupId</param>
/// <param name="artifactId">Project Parent Pom Artifact ID, used as a maven artifact ID for the parent pom.xml</param>
/// <param name="version">Project version, used as a maven version for the entire pom.xmls</param>
/// <param name="verifyTests">if true, a dialog box for verifying tests will show up and requires user interaction</param>
/// <param name="scmTag">generates scm tags if txtboxfield is not empty or null</param>
/// <returns>An array of generated pom.xml filenames</returns>
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, string scmTag, bool verifyTests, ref string warningMsg)
{
return ImportProject(solutionFile, groupId, artifactId, version, scmTag, verifyTests, false, ref warningMsg);
}
/// <summary>
/// Imports a specified Visual Studio Projects in a Solution to an NPanday Pom,
/// This is the Project-Importer Entry Method
/// </summary>
/// <param name="solutionFile">Path to your Visual Studio Solution File *.sln </param>
/// <param name="groupId">Project Group ID, for maven groupId</param>
/// <param name="artifactId">Project Parent Pom Artifact ID, used as a maven artifact ID for the parent pom.xml</param>
/// <param name="version">Project version, used as a maven version for the entire pom.xmls</param>
/// <param name="verifyTests">if true, a dialog box for verifying tests will show up and requires user interaction</param>
/// <param name="scmTag">generates scm tags if txtboxfield is not empty or null</param>
/// <returns>An array of generated pom.xml filenames</returns>
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, string scmTag, bool verifyTests, bool useMsDeploy, ref string warningMsg)
{
return ImportProject(solutionFile, groupId, artifactId, version, scmTag, verifyTests, useMsDeploy, null, null, null, ref warningMsg);
}
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, string scmTag, bool verifyTests, bool useMsDeploy, string configuration, string cloudConfig, DependencySearchConfiguration depSearchConfig, ref string warningMsg)
{
return ImportProject(solutionFile, groupId, artifactId, version, scmTag, verifyTests, useMsDeploy, configuration, cloudConfig, depSearchConfig, null, ref warningMsg);
}
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, string scmTag, bool verifyTests, bool useMsDeploy, string configuration, string cloudConfig, DependencySearchConfiguration depSearchConfig, Dictionary<string, string> globalProperties, ref string warningMsg)
{
VerifyProjectToImport method = verifyTests ? VerifyUnitTestsToUser.VerifyTests : (VerifyProjectToImport)null;
return ImportProject(solutionFile, groupId, artifactId, version, scmTag, method, useMsDeploy, configuration, cloudConfig, depSearchConfig, globalProperties, ref warningMsg);
}
/// <summary>
/// Delegate Alogrithm for Verifying Project To Import
/// </summary>
/// <param name="projectDigests"></param>
/// <param name="structureType"></param>
/// <param name="solutionFile"></param>
/// <param name="groupId"></param>
/// <param name="artifactId"></param>
/// <param name="version"></param>
public delegate void VerifyProjectToImport(ref ProjectDigest[] projectDigests, ProjectStructureType structureType, string solutionFile, ref string groupId,ref string artifactId,ref string version);
private static void HasValidFolderStructure(List<Dictionary<string, object>> projectList)
{
string errorProject = string.Empty;
foreach (Dictionary<string,object> project in projectList)
{
string holder;
if (project.ContainsKey("ProjectFullPath"))
{
holder = (string)project["ProjectFullPath"];
if (holder.Contains("..\\"))
{
throw new Exception("Project Importer failed with project \""+ holder
+ "\". Project directory structure may not be supported.");
}
}
}
}
/// <summary>
/// Imports a specified Visual Studio Projects in a Solution to an NPanday Pom,
/// This is the Project-Importer Entry Method,
/// This method accepts a delegate to use as A project Verifier algorithm
/// </summary>
/// <param name="solutionFile">Path to your Visual Studio Solution File *.sln </param>
/// <param name="groupId">Project Group ID, for maven groupId</param>
/// <param name="artifactId">Project Parent Pom Artifact ID, used as a maven artifact ID for the parent pom.xml</param>
/// <param name="version">Project version, used as a maven version for the entire pom.xmls</param>
/// <param name="verifyProjectToImport">A delegate That will Accept a method for verifying Projects To Import</param>
/// <param name="scmTag">adds scm tags to parent pom.xml if not string.empty or null</param>
/// <returns>An array of generated pom.xml filenames</returns>
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, string scmTag, VerifyProjectToImport verifyProjectToImport, ref string warningMsg)
{
return ImportProject(solutionFile, groupId, artifactId, version, scmTag, verifyProjectToImport, false, null, null, null, null, ref warningMsg);
}
/// <summary>
/// Imports a specified Visual Studio Projects in a Solution to an NPanday Pom,
/// This is the Project-Importer Entry Method,
/// This method accepts a delegate to use as A project Verifier algorithm
/// </summary>
/// <param name="solutionFile">Path to your Visual Studio Solution File *.sln </param>
/// <param name="groupId">Project Group ID, for maven groupId</param>
/// <param name="artifactId">Project Parent Pom Artifact ID, used as a maven artifact ID for the parent pom.xml</param>
/// <param name="version">Project version, used as a maven version for the entire pom.xmls</param>
/// <param name="verifyProjectToImport">A delegate That will Accept a method for verifying Projects To Import</param>
/// <param name="scmTag">adds scm tags to parent pom.xml if not string.empty or null</param>
/// <returns>An array of generated pom.xml filenames</returns>
public static string[] ImportProject(string solutionFile, string groupId, string artifactId, string version, string scmTag, VerifyProjectToImport verifyProjectToImport, bool useMsDeploy, string configuration, string cloudConfig, DependencySearchConfiguration depSearchConfig, Dictionary<string, string> globalProperties, ref string warningMsg)
{
string[] result = null;
if (depSearchConfig == null)
depSearchConfig = new DependencySearchConfiguration();
FileInfo solutionFileInfo = new FileInfo(solutionFile);
List<Dictionary<string, object>> list = ParseSolution(solutionFileInfo, globalProperties, ref warningMsg);
if (configuration != null)
{
foreach (Dictionary<string, object> projectMap in list)
{
projectMap.Add("Configuration", configuration);
}
}
//Checks for Invalid folder structure
HasValidFolderStructure(list);
ProjectDigest[] prjDigests = DigestProjects(list, depSearchConfig, ref warningMsg);
ProjectStructureType structureType = GetProjectStructureType(solutionFile, prjDigests);
// Filtering of unsupported project types.
String UnsupportedProjectsMessage = string.Empty;
List<ProjectDigest> filteredPrjDigests = new List<ProjectDigest>();
foreach (ProjectDigest pDigest in prjDigests)
{
if (PomConverter.__converterAlgorithms.ContainsKey(pDigest.ProjectType))
{
// set the project flag so that converters can look at it later
pDigest.UseMsDeploy = useMsDeploy;
pDigest.CloudConfig = cloudConfig;
pDigest.DependencySearchConfig = depSearchConfig;
filteredPrjDigests.Add(pDigest);
}
else
{
if (UnsupportedProjectsMessage == string.Empty)
{
UnsupportedProjectsMessage += pDigest.FullFileName;
}
else
{
UnsupportedProjectsMessage += ", " + pDigest.FullFileName;
}
}
}
if (!string.Empty.Equals(UnsupportedProjectsMessage))
{
warningMsg = string.Format("{0}\n Unsupported Projects: {1}", warningMsg, UnsupportedProjectsMessage);
}
prjDigests = filteredPrjDigests.ToArray();
if (verifyProjectToImport != null && filteredPrjDigests.Count > 0)
{
verifyProjectToImport(ref prjDigests, structureType, solutionFile, ref groupId, ref artifactId, ref version);
}
List<Reference> missingReferences = new List<Reference>();
List<string> nonPortableReferences = new List<string>();
result = ImportProjectType(structureType, filteredPrjDigests.ToArray(), solutionFile, groupId, artifactId, version, scmTag, missingReferences, nonPortableReferences);
if (missingReferences.Count > 0)
{
warningMsg += "\nThe following references could not be resolved from Maven or the GAC:";
foreach (Reference missingReference in missingReferences)
{
warningMsg += "\n\t" + missingReference.Name + " (" + missingReference.Version + ")";
}
warningMsg += "\nPlease update the defaults in pom.xml and re-sync references, or re-add them using 'Add Maven Artifact'.";
}
if (nonPortableReferences.Count > 0)
{
if (depSearchConfig.CopyToMaven)
{
warningMsg += "The following artifacts were copied to the local Maven repository:";
}
else
{
warningMsg += "\nThe build may not be portable if local references are used:";
}
warningMsg += "\n\t" + string.Join("\n\t", nonPortableReferences.ToArray())
+ "\nDeploying the reference to a Repository will make the code portable to other machines.";
}
return result;
}
#endregion
#region Re-Import Project Entry
public static string[] ReImportProject(string solutionFile, ref string warningMsg)
{
return ImportProject(solutionFile, null, null, null, null, VerifyProjectImportSyncronization.SyncronizePomValues, ref warningMsg);
}
#endregion
/// <summary>
/// Facade for Parsing A solution File to get its projects
/// calls NPanday.ProjectImporter.Parser.SlnParserParser.ParseSolution(FileInfo)
/// </summary>
/// <param name="solutionFile">the full path of the *.sln (visual studio solution) file you want to parse</param>
/// <returns></returns>
public static List<Dictionary<string, object>> ParseSolution(FileInfo solutionFile, Dictionary<string, string> globalProperties, ref string warningMsg)
{
return SolutionParser.ParseSolution(solutionFile, globalProperties, ref warningMsg);
}
/// <summary>
/// Facade for Digesting parsed projects
/// calls NPanday.ProjectImporter.Digest.ProjectDigester.DigestProjects(List<Dictionary<string, object>>)
/// </summary>
/// <param name="projects">list retured from ParseSolution</param>
/// <returns></returns>
public static ProjectDigest[] DigestProjects(List<Dictionary<string, object>> projects, DependencySearchConfiguration depSearchConfig, ref string warningMsg)
{
return ProjectDigester.DigestProjects(projects, depSearchConfig, ref warningMsg);
}
/// <summary>
/// Facade for Getting the Project Type.
/// calls NPanday.ProjectImporter.Validator.ProjectValidator.GetProjectStructureType(...)
/// </summary>
/// <param name="solutionFile">the full path of the *.sln (visual studio solution) file you want to import</param>
/// <param name="projectDigests">Digested Projects</param>
/// <returns></returns>
public static ProjectStructureType GetProjectStructureType(string solutionFile, ProjectDigest[] projectDigests)
{
return ProjectValidator.GetProjectStructureType(solutionFile, projectDigests);
}
}
}
| |
/*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace TypeSql.Antlr.Runtime
{
using NonSerialized = System.NonSerializedAttribute;
using Regex = System.Text.RegularExpressions.Regex;
using Serializable = System.SerializableAttribute;
[Serializable]
public class CommonToken : IToken
{
int type;
int line;
int charPositionInLine = -1; // set to invalid position
int channel = TokenChannels.Default;
[NonSerialized]
ICharStream input;
/** <summary>
* We need to be able to change the text once in a while. If
* this is non-null, then getText should return this. Note that
* start/stop are not affected by changing this.
* </summary>
*/
string text;
/** <summary>What token number is this from 0..n-1 tokens; < 0 implies invalid index</summary> */
int index = -1;
/** <summary>The char position into the input buffer where this token starts</summary> */
int start;
/** <summary>The char position into the input buffer where this token stops</summary> */
int stop;
public CommonToken()
{
}
public CommonToken( int type )
{
this.type = type;
}
public CommonToken( ICharStream input, int type, int channel, int start, int stop )
{
this.input = input;
this.type = type;
this.channel = channel;
this.start = start;
this.stop = stop;
}
public CommonToken( int type, string text )
{
this.type = type;
this.channel = TokenChannels.Default;
this.text = text;
}
public CommonToken( IToken oldToken )
{
text = oldToken.Text;
type = oldToken.Type;
line = oldToken.Line;
index = oldToken.TokenIndex;
charPositionInLine = oldToken.CharPositionInLine;
channel = oldToken.Channel;
input = oldToken.InputStream;
if ( oldToken is CommonToken )
{
start = ( (CommonToken)oldToken ).start;
stop = ( (CommonToken)oldToken ).stop;
}
}
#region IToken Members
public string Text
{
get
{
if ( text != null )
return text;
if ( input == null )
return null;
if (start <= stop && stop < input.Count)
return input.Substring( start, stop - start + 1 );
return "<EOF>";
}
set
{
/** Override the text for this token. getText() will return this text
* rather than pulling from the buffer. Note that this does not mean
* that start/stop indexes are not valid. It means that that input
* was converted to a new string in the token object.
*/
text = value;
}
}
public int Type
{
get
{
return type;
}
set
{
type = value;
}
}
public int Line
{
get
{
return line;
}
set
{
line = value;
}
}
public int CharPositionInLine
{
get
{
return charPositionInLine;
}
set
{
charPositionInLine = value;
}
}
public int Channel
{
get
{
return channel;
}
set
{
channel = value;
}
}
public int StartIndex
{
get
{
return start;
}
set
{
start = value;
}
}
public int StopIndex
{
get
{
return stop;
}
set
{
stop = value;
}
}
public int TokenIndex
{
get
{
return index;
}
set
{
index = value;
}
}
public ICharStream InputStream
{
get
{
return input;
}
set
{
input = value;
}
}
#endregion
public override string ToString()
{
string channelStr = "";
if ( channel > 0 )
{
channelStr = ",channel=" + channel;
}
string txt = Text;
if ( txt != null )
{
txt = Regex.Replace( txt, "\n", "\\\\n" );
txt = Regex.Replace( txt, "\r", "\\\\r" );
txt = Regex.Replace( txt, "\t", "\\\\t" );
}
else
{
txt = "<no text>";
}
return "[@" + TokenIndex + "," + start + ":" + stop + "='" + txt + "',<" + type + ">" + channelStr + "," + line + ":" + CharPositionInLine + "]";
}
[System.Runtime.Serialization.OnSerializing]
internal void OnSerializing( System.Runtime.Serialization.StreamingContext context )
{
if ( text == null )
text = Text;
}
}
}
| |
// <copyright file="HttpClientTests.netcore31.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if NETCOREAPP3_1_OR_GREATER
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json;
using OpenTelemetry.Metrics;
using OpenTelemetry.Tests;
using OpenTelemetry.Trace;
using Xunit;
namespace OpenTelemetry.Instrumentation.Http.Tests
{
public partial class HttpClientTests
{
public static int Counter;
public static IEnumerable<object[]> TestData => HttpTestData.ReadTestCases();
[Theory]
[MemberData(nameof(TestData))]
public async Task HttpOutCallsAreCollectedSuccessfullyAsync(HttpTestData.HttpOutTestCase tc)
{
var serverLifeTime = TestHttpServer.RunServer(
(ctx) =>
{
ctx.Response.StatusCode = tc.ResponseCode == 0 ? 200 : tc.ResponseCode;
ctx.Response.OutputStream.Close();
},
out var host,
out var port);
var processor = new Mock<BaseProcessor<Activity>>();
tc.Url = HttpTestData.NormalizeValues(tc.Url, host, port);
var metrics = new List<Metric>();
var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddHttpClientInstrumentation()
.AddInMemoryExporter(metrics)
.Build();
using (serverLifeTime)
using (Sdk.CreateTracerProviderBuilder()
.AddHttpClientInstrumentation((opt) =>
{
opt.SetHttpFlavor = tc.SetHttpFlavor;
opt.Enrich = ActivityEnrichment;
opt.RecordException = tc.RecordException.HasValue ? tc.RecordException.Value : false;
})
.AddProcessor(processor.Object)
.Build())
{
try
{
using var c = new HttpClient();
var request = new HttpRequestMessage
{
RequestUri = new Uri(tc.Url),
Method = new HttpMethod(tc.Method),
Version = new Version(2, 0),
};
if (tc.Headers != null)
{
foreach (var header in tc.Headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
await c.SendAsync(request);
}
catch (Exception)
{
// test case can intentionally send request that will result in exception
}
}
meterProvider.Dispose();
var requestMetrics = metrics
.Where(metric => metric.Name == "http.client.duration")
.ToArray();
Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called.
var activity = (Activity)processor.Invocations[2].Arguments[0];
Assert.Equal(ActivityKind.Client, activity.Kind);
Assert.Equal(tc.SpanName, activity.DisplayName);
// Assert.Equal(tc.SpanStatus, d[span.Status.CanonicalCode]);
Assert.Equal(
tc.SpanStatus,
activity.GetTagValue(SpanAttributeConstants.StatusCodeKey) as string);
if (tc.SpanStatusHasDescription.HasValue)
{
var desc = activity.GetTagValue(SpanAttributeConstants.StatusDescriptionKey) as string;
Assert.Equal(tc.SpanStatusHasDescription.Value, !string.IsNullOrEmpty(desc));
}
var normalizedAttributes = activity.TagObjects.Where(kv => !kv.Key.StartsWith("otel.")).ToImmutableSortedDictionary(x => x.Key, x => x.Value.ToString());
var normalizedAttributesTestCase = tc.SpanAttributes.ToDictionary(x => x.Key, x => HttpTestData.NormalizeValues(x.Value, host, port));
Assert.Equal(normalizedAttributesTestCase.Count, normalizedAttributes.Count);
foreach (var kv in normalizedAttributesTestCase)
{
Assert.Contains(activity.TagObjects, i => i.Key == kv.Key && i.Value.ToString().Equals(kv.Value, StringComparison.InvariantCultureIgnoreCase));
}
if (tc.RecordException.HasValue && tc.RecordException.Value)
{
Assert.Single(activity.Events.Where(evt => evt.Name.Equals("exception")));
}
if (tc.ResponseExpected)
{
Assert.Single(requestMetrics);
var metric = requestMetrics[0];
Assert.NotNull(metric);
Assert.True(metric.MetricType == MetricType.Histogram);
var metricPoints = new List<MetricPoint>();
foreach (var p in metric.GetMetricPoints())
{
metricPoints.Add(p);
}
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
var count = metricPoint.GetHistogramCount();
var sum = metricPoint.GetHistogramSum();
Assert.Equal(1L, count);
Assert.Equal(activity.Duration.TotalMilliseconds, sum);
var attributes = new KeyValuePair<string, object>[metricPoint.Tags.Count];
int i = 0;
foreach (var tag in metricPoint.Tags)
{
attributes[i++] = tag;
}
var method = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpMethod, tc.Method);
var scheme = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpScheme, "http");
var statusCode = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpStatusCode, tc.ResponseCode == 0 ? 200 : tc.ResponseCode);
var flavor = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpFlavor, "2.0");
Assert.Contains(method, attributes);
Assert.Contains(scheme, attributes);
Assert.Contains(statusCode, attributes);
Assert.Contains(flavor, attributes);
Assert.Equal(4, attributes.Length);
}
else
{
Assert.Empty(requestMetrics);
}
}
[Fact]
public async Task DebugIndividualTestAsync()
{
var serializer = new JsonSerializer();
var input = serializer.Deserialize<HttpTestData.HttpOutTestCase[]>(new JsonTextReader(new StringReader(@"
[
{
""name"": ""Response code: 399"",
""method"": ""GET"",
""url"": ""http://{host}:{port}/"",
""responseCode"": 399,
""responseExpected"": true,
""spanName"": ""HTTP GET"",
""spanStatus"": ""UNSET"",
""spanKind"": ""Client"",
""spanAttributes"": {
""http.method"": ""GET"",
""http.host"": ""{host}:{port}"",
""http.status_code"": ""399"",
""http.url"": ""http://{host}:{port}/""
}
}
]
")));
var t = (Task)this.GetType().InvokeMember(nameof(this.HttpOutCallsAreCollectedSuccessfullyAsync), BindingFlags.InvokeMethod, null, this, HttpTestData.GetArgumentsFromTestCaseObject(input).First());
await t;
}
[Fact]
public async Task CheckEnrichmentWhenSampling()
{
await CheckEnrichment(new AlwaysOffSampler(), 0, this.url).ConfigureAwait(false);
await CheckEnrichment(new AlwaysOnSampler(), 2, this.url).ConfigureAwait(false);
}
private static async Task CheckEnrichment(Sampler sampler, int expect, string url)
{
Counter = 0;
var processor = new Mock<BaseProcessor<Activity>>();
using (Sdk.CreateTracerProviderBuilder()
.SetSampler(sampler)
.AddHttpClientInstrumentation(options => options.Enrich = ActivityEnrichmentCounter)
.AddProcessor(processor.Object)
.Build())
{
using var c = new HttpClient();
using var r = await c.GetAsync(url).ConfigureAwait(false);
}
Assert.Equal(expect, Counter);
}
private static void ActivityEnrichmentCounter(Activity activity, string method, object obj)
{
Counter++;
}
}
}
#endif
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Editor.Core;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.InterpreterList;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools {
public static class Extensions {
internal static bool IsAppxPackageableProject(this ProjectNode projectNode) {
var appxProp = projectNode.BuildProject.GetPropertyValue(ProjectFileConstants.AppxPackage);
var containerProp = projectNode.BuildProject.GetPropertyValue(ProjectFileConstants.WindowsAppContainer);
var appxFlag = false;
var containerFlag = false;
if (bool.TryParse(appxProp, out appxFlag) && bool.TryParse(containerProp, out containerFlag)) {
return appxFlag && containerFlag;
} else {
return false;
}
}
public static StandardGlyphGroup ToGlyphGroup(this PythonMemberType objectType) {
StandardGlyphGroup group;
switch (objectType) {
case PythonMemberType.Class: group = StandardGlyphGroup.GlyphGroupClass; break;
case PythonMemberType.DelegateInstance:
case PythonMemberType.Delegate: group = StandardGlyphGroup.GlyphGroupDelegate; break;
case PythonMemberType.Enum: group = StandardGlyphGroup.GlyphGroupEnum; break;
case PythonMemberType.Namespace: group = StandardGlyphGroup.GlyphGroupNamespace; break;
case PythonMemberType.Multiple: group = StandardGlyphGroup.GlyphGroupOverload; break;
case PythonMemberType.Field: group = StandardGlyphGroup.GlyphGroupField; break;
case PythonMemberType.Module: group = StandardGlyphGroup.GlyphGroupModule; break;
case PythonMemberType.Property: group = StandardGlyphGroup.GlyphGroupProperty; break;
case PythonMemberType.Instance: group = StandardGlyphGroup.GlyphGroupVariable; break;
case PythonMemberType.Constant: group = StandardGlyphGroup.GlyphGroupVariable; break;
case PythonMemberType.EnumInstance: group = StandardGlyphGroup.GlyphGroupEnumMember; break;
case PythonMemberType.Event: group = StandardGlyphGroup.GlyphGroupEvent; break;
case PythonMemberType.Keyword: group = StandardGlyphGroup.GlyphKeyword; break;
case PythonMemberType.Function:
case PythonMemberType.Method:
default:
group = StandardGlyphGroup.GlyphGroupMethod;
break;
}
return group;
}
internal static bool CanComplete(this ClassificationSpan token) {
return token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) |
token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier);
}
/// <summary>
/// Returns the span to use for the provided intellisense session.
/// </summary>
/// <returns>A tracking span. The span may be of length zero if there
/// is no suitable token at the trigger point.</returns>
internal static ITrackingSpan GetApplicableSpan(this IIntellisenseSession session, ITextBuffer buffer) {
var snapshot = buffer.CurrentSnapshot;
var triggerPoint = session.GetTriggerPoint(buffer);
var span = snapshot.GetApplicableSpan(triggerPoint);
if (span != null) {
return span;
}
return snapshot.CreateTrackingSpan(triggerPoint.GetPosition(snapshot), 0, SpanTrackingMode.EdgeInclusive);
}
/// <summary>
/// Returns the applicable span at the provided position.
/// </summary>
/// <returns>A tracking span, or null if there is no token at the
/// provided position.</returns>
internal static ITrackingSpan GetApplicableSpan(this ITextSnapshot snapshot, ITrackingPoint point) {
return snapshot.GetApplicableSpan(point.GetPosition(snapshot));
}
/// <summary>
/// Returns the applicable span at the provided position.
/// </summary>
/// <returns>A tracking span, or null if there is no token at the
/// provided position.</returns>
internal static ITrackingSpan GetApplicableSpan(this ITextSnapshot snapshot, int position) {
var classifier = snapshot.TextBuffer.GetPythonClassifier();
var line = snapshot.GetLineFromPosition(position);
if (classifier == null || line == null) {
return null;
}
var spanLength = position - line.Start.Position;
// Increase position by one to include 'fob' in: "abc.|fob"
if (spanLength < line.Length) {
spanLength += 1;
}
var classifications = classifier.GetClassificationSpans(new SnapshotSpan(line.Start, spanLength));
// Handle "|"
if (classifications == null || classifications.Count == 0) {
return null;
}
var lastToken = classifications[classifications.Count - 1];
// Handle "fob |"
if (lastToken == null || position > lastToken.Span.End) {
return null;
}
if (position > lastToken.Span.Start) {
if (lastToken.CanComplete()) {
// Handle "fo|o"
return snapshot.CreateTrackingSpan(lastToken.Span, SpanTrackingMode.EdgeInclusive);
} else {
// Handle "<|="
return null;
}
}
var secondLastToken = classifications.Count >= 2 ? classifications[classifications.Count - 2] : null;
if (lastToken.Span.Start == position && lastToken.CanComplete() &&
(secondLastToken == null || // Handle "|fob"
position > secondLastToken.Span.End || // Handle "if |fob"
!secondLastToken.CanComplete())) { // Handle "abc.|fob"
return snapshot.CreateTrackingSpan(lastToken.Span, SpanTrackingMode.EdgeInclusive);
}
// Handle "abc|."
// ("ab|c." would have been treated as "ab|c")
if (secondLastToken != null && secondLastToken.Span.End == position && secondLastToken.CanComplete()) {
return snapshot.CreateTrackingSpan(secondLastToken.Span, SpanTrackingMode.EdgeInclusive);
}
return null;
}
internal static ITrackingSpan CreateTrackingSpan(this IQuickInfoSession session, ITextBuffer buffer) {
var triggerPoint = session.GetTriggerPoint(buffer);
var position = triggerPoint.GetPosition(buffer.CurrentSnapshot);
if (position == buffer.CurrentSnapshot.Length) {
return ((IIntellisenseSession)session).GetApplicableSpan(buffer);
}
return buffer.CurrentSnapshot.CreateTrackingSpan(position, 1, SpanTrackingMode.EdgeInclusive);
}
#pragma warning disable 0618
// TODO: Switch from smart tags to Light Bulb: http://go.microsoft.com/fwlink/?LinkId=394601
internal static ITrackingSpan CreateTrackingSpan(this ISmartTagSession session, ITextBuffer buffer) {
var triggerPoint = session.GetTriggerPoint(buffer);
var position = triggerPoint.GetPosition(buffer.CurrentSnapshot);
if (position == buffer.CurrentSnapshot.Length) {
return ((IIntellisenseSession)session).GetApplicableSpan(buffer);
}
var triggerChar = triggerPoint.GetCharacter(buffer.CurrentSnapshot);
if (position != 0 && !char.IsLetterOrDigit(triggerChar)) {
// end of line, back up one char as we may have an identifier
return buffer.CurrentSnapshot.CreateTrackingSpan(position - 1, 1, SpanTrackingMode.EdgeInclusive);
}
return buffer.CurrentSnapshot.CreateTrackingSpan(position, 1, SpanTrackingMode.EdgeInclusive);
}
#pragma warning restore 0618
public static IPythonInterpreterFactory GetPythonInterpreterFactory(this IVsHierarchy self) {
var node = (self.GetProject().GetCommonProject() as PythonProjectNode);
if (node != null) {
return node.GetInterpreterFactory();
}
return null;
}
public static IEnumerable<IVsProject> EnumerateLoadedProjects(this IVsSolution solution) {
var guid = new Guid(PythonConstants.ProjectFactoryGuid);
IEnumHierarchies hierarchies;
ErrorHandler.ThrowOnFailure((solution.GetProjectEnum(
(uint)(__VSENUMPROJFLAGS.EPF_MATCHTYPE | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION),
ref guid,
out hierarchies)));
IVsHierarchy[] hierarchy = new IVsHierarchy[1];
uint fetched;
while (ErrorHandler.Succeeded(hierarchies.Next(1, hierarchy, out fetched)) && fetched == 1) {
var project = hierarchy[0] as IVsProject;
if (project != null) {
yield return project;
}
}
}
internal static IEnumerable<PythonProjectNode> EnumerateLoadedPythonProjects(this IVsSolution solution) {
return EnumerateLoadedProjects(solution)
.Select(p => p.GetPythonProject())
.Where(p => p != null);
}
public static IModuleContext GetModuleContext(this ITextBuffer buffer, IServiceProvider serviceProvider) {
if (buffer == null) {
return null;
}
var analyzer = buffer.GetAnalyzer(serviceProvider);
if (analyzer == null) {
return null;
}
var path = buffer.GetFilePath();
if (string.IsNullOrEmpty(path)) {
return null;
}
var entry = analyzer.GetEntryFromFile(path);
if (entry == null) {
return null;
}
return entry.AnalysisContext;
}
internal static PythonProjectNode GetPythonProject(this IVsProject project) {
return ((IVsHierarchy)project).GetProject().GetCommonProject() as PythonProjectNode;
}
internal static PythonProjectNode GetPythonProject(this EnvDTE.Project project) {
return project.GetCommonProject() as PythonProjectNode;
}
internal static void GotoSource(this LocationInfo location, IServiceProvider serviceProvider) {
string zipFileName = VsProjectAnalyzer.GetZipFileName(location.ProjectEntry);
if (zipFileName == null) {
PythonToolsPackage.NavigateTo(
serviceProvider,
location.FilePath,
Guid.Empty,
location.Line - 1,
location.Column - 1);
}
}
internal static bool TryGetProjectEntry(this ITextBuffer buffer, out IProjectEntry entry) {
return buffer.Properties.TryGetProperty<IProjectEntry>(typeof(IProjectEntry), out entry);
}
internal static bool TryGetPythonProjectEntry(this ITextBuffer buffer, out IPythonProjectEntry entry) {
IProjectEntry e;
if (buffer.TryGetProjectEntry(out e) && (entry = e as IPythonProjectEntry) != null) {
return true;
}
entry = null;
return false;
}
internal static IProjectEntry GetProjectEntry(this ITextBuffer buffer) {
IProjectEntry res;
buffer.TryGetProjectEntry(out res);
return res;
}
internal static IPythonProjectEntry GetPythonProjectEntry(this ITextBuffer buffer) {
IPythonProjectEntry res;
buffer.TryGetPythonProjectEntry(out res);
return res;
}
internal static PythonProjectNode GetProject(this ITextBuffer buffer, IServiceProvider serviceProvider) {
var path = buffer.GetFilePath();
if (path != null) {
var sln = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
if (sln != null) {
foreach (var proj in sln.EnumerateLoadedPythonProjects()) {
int found;
var priority = new VSDOCUMENTPRIORITY[1];
uint itemId;
ErrorHandler.ThrowOnFailure(proj.IsDocumentInProject(path, out found, priority, out itemId));
if (found != 0) {
return proj;
}
}
}
}
return null;
}
internal static VsProjectAnalyzer GetAnalyzer(this ITextView textView, IServiceProvider serviceProvider) {
PythonReplEvaluator evaluator;
if (textView.Properties.TryGetProperty<PythonReplEvaluator>(typeof(PythonReplEvaluator), out evaluator)) {
return evaluator.ReplAnalyzer;
}
return textView.TextBuffer.GetAnalyzer(serviceProvider);
}
internal static SnapshotPoint? GetCaretPosition(this ITextView view) {
return view.BufferGraph.MapDownToFirstMatch(
new SnapshotPoint(view.TextBuffer.CurrentSnapshot, view.Caret.Position.BufferPosition),
PointTrackingMode.Positive,
EditorExtensions.IsPythonContent,
PositionAffinity.Successor
);
}
internal static ExpressionAnalysis GetExpressionAnalysis(this ITextView view, IServiceProvider serviceProvider) {
ITrackingSpan span = GetCaretSpan(view);
return span.TextBuffer.CurrentSnapshot.AnalyzeExpression(serviceProvider, span, false);
}
internal static ITrackingSpan GetCaretSpan(this ITextView view) {
var caretPoint = view.GetCaretPosition();
Debug.Assert(caretPoint != null);
var snapshot = caretPoint.Value.Snapshot;
var caretPos = caretPoint.Value.Position;
// fob(
// ^
// +--- Caret here
//
// We want to lookup fob, not fob(
//
ITrackingSpan span;
if (caretPos != snapshot.Length) {
string curChar = snapshot.GetText(caretPos, 1);
if (!IsIdentifierChar(curChar[0]) && caretPos > 0) {
string prevChar = snapshot.GetText(caretPos - 1, 1);
if (IsIdentifierChar(prevChar[0])) {
caretPos--;
}
}
span = snapshot.CreateTrackingSpan(
caretPos,
1,
SpanTrackingMode.EdgeInclusive
);
} else {
span = snapshot.CreateTrackingSpan(
caretPos,
0,
SpanTrackingMode.EdgeInclusive
);
}
return span;
}
private static bool IsIdentifierChar(char curChar) {
return Char.IsLetterOrDigit(curChar) || curChar == '_';
}
/// <summary>
/// Reads a string from the socket which is encoded as:
/// U, byte count, bytes
/// A, byte count, ASCII
///
/// Which supports either UTF-8 or ASCII strings.
/// </summary>
internal static string ReadString(this Socket socket) {
byte[] cmd_buffer = new byte[4];
if (socket.Receive(cmd_buffer, 1, SocketFlags.None) == 1) {
bool isUnicode = cmd_buffer[0] == 'U';
if (socket.Receive(cmd_buffer) == 4) {
int filenameLen = BitConverter.ToInt32(cmd_buffer, 0);
byte[] buffer = new byte[filenameLen];
if (filenameLen != 0) {
int bytesRead = 0;
do {
bytesRead += socket.Receive(buffer, bytesRead, filenameLen - bytesRead, SocketFlags.None);
} while (bytesRead != filenameLen);
}
if (isUnicode) {
return Encoding.UTF8.GetString(buffer);
} else {
char[] chars = new char[buffer.Length];
for (int i = 0; i < buffer.Length; i++) {
chars[i] = (char)buffer[i];
}
return new string(chars);
}
} else {
Debug.Assert(false, "Failed to read length");
}
} else {
Debug.Assert(false, "Failed to read unicode/ascii byte");
}
return null;
}
internal static int ReadInt(this Socket socket) {
byte[] cmd_buffer = new byte[4];
if (socket.Receive(cmd_buffer) == 4) {
return BitConverter.ToInt32(cmd_buffer, 0);
}
throw new InvalidOperationException();
}
internal static VsProjectAnalyzer GetAnalyzer(this ITextBuffer buffer, IServiceProvider serviceProvider) {
PythonProjectNode pyProj;
if (!buffer.Properties.TryGetProperty<PythonProjectNode>(typeof(PythonProjectNode), out pyProj)) {
pyProj = buffer.GetProject(serviceProvider);
if (pyProj != null) {
buffer.Properties.AddProperty(typeof(PythonProjectNode), pyProj);
}
}
if (pyProj != null) {
return pyProj.GetAnalyzer();
}
VsProjectAnalyzer analyzer;
// exists for tests where we don't run in VS and for the existing changes preview
if (buffer.Properties.TryGetProperty<VsProjectAnalyzer>(typeof(VsProjectAnalyzer), out analyzer)) {
return analyzer;
}
return serviceProvider.GetPythonToolsService().DefaultAnalyzer;
}
internal static PythonToolsService GetPythonToolsService(this IServiceProvider serviceProvider) {
if (serviceProvider == null) {
return null;
}
return (PythonToolsService)serviceProvider.GetService(typeof(PythonToolsService));
}
internal static IComponentModel GetComponentModel(this IServiceProvider serviceProvider) {
if (serviceProvider == null) {
return null;
}
return (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
}
public static string BrowseForFileSave(this IServiceProvider provider, IntPtr owner, string filter, string initialPath = null) {
if (string.IsNullOrEmpty(initialPath)) {
initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
}
IVsUIShell uiShell = provider.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (null == uiShell) {
using (var sfd = new System.Windows.Forms.SaveFileDialog()) {
sfd.AutoUpgradeEnabled = true;
sfd.Filter = filter;
sfd.FileName = Path.GetFileName(initialPath);
sfd.InitialDirectory = Path.GetDirectoryName(initialPath);
DialogResult result;
if (owner == IntPtr.Zero) {
result = sfd.ShowDialog();
} else {
result = sfd.ShowDialog(NativeWindow.FromHandle(owner));
}
if (result == DialogResult.OK) {
return sfd.FileName;
} else {
return null;
}
}
}
if (owner == IntPtr.Zero) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
}
VSSAVEFILENAMEW[] saveInfo = new VSSAVEFILENAMEW[1];
saveInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSSAVEFILENAMEW));
saveInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0";
saveInfo[0].hwndOwner = owner;
saveInfo[0].nMaxFileName = 260;
var pFileName = Marshal.AllocCoTaskMem(520);
saveInfo[0].pwzFileName = pFileName;
saveInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();
Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
try {
int hr = uiShell.GetSaveFileNameViaDlg(saveInfo);
if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return null;
}
ErrorHandler.ThrowOnFailure(hr);
return Marshal.PtrToStringAuto(saveInfo[0].pwzFileName);
} finally {
if (pFileName != IntPtr.Zero) {
Marshal.FreeCoTaskMem(pFileName);
}
}
}
public static string BrowseForFileOpen(this IServiceProvider serviceProvider, IntPtr owner, string filter, string initialPath = null) {
if (string.IsNullOrEmpty(initialPath)) {
initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
}
IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (null == uiShell) {
using (var sfd = new System.Windows.Forms.OpenFileDialog()) {
sfd.AutoUpgradeEnabled = true;
sfd.Filter = filter;
sfd.FileName = Path.GetFileName(initialPath);
sfd.InitialDirectory = Path.GetDirectoryName(initialPath);
DialogResult result;
if (owner == IntPtr.Zero) {
result = sfd.ShowDialog();
} else {
result = sfd.ShowDialog(NativeWindow.FromHandle(owner));
}
if (result == DialogResult.OK) {
return sfd.FileName;
} else {
return null;
}
}
}
if (owner == IntPtr.Zero) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
}
VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1];
openInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
openInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0";
openInfo[0].hwndOwner = owner;
openInfo[0].nMaxFileName = 260;
var pFileName = Marshal.AllocCoTaskMem(520);
openInfo[0].pwzFileName = pFileName;
openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();
Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
try {
int hr = uiShell.GetOpenFileNameViaDlg(openInfo);
if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return null;
}
ErrorHandler.ThrowOnFailure(hr);
return Marshal.PtrToStringAuto(openInfo[0].pwzFileName);
} finally {
if (pFileName != IntPtr.Zero) {
Marshal.FreeCoTaskMem(pFileName);
}
}
}
internal static IContentType GetPythonContentType(this IServiceProvider provider) {
return provider.GetComponentModel().GetService<IContentTypeRegistryService>().GetContentType(PythonCoreConstants.ContentType);
}
internal static EnvDTE.DTE GetDTE(this IServiceProvider provider) {
return (EnvDTE.DTE)provider.GetService(typeof(EnvDTE.DTE));
}
internal static SolutionEventsListener GetSolutionEvents(this IServiceProvider serviceProvider) {
return (SolutionEventsListener)serviceProvider.GetService(typeof(SolutionEventsListener));
}
internal static void GlobalInvoke(this IServiceProvider serviceProvider, CommandID cmdID) {
OleMenuCommandService mcs = serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
mcs.GlobalInvoke(cmdID);
}
internal static void GlobalInvoke(this IServiceProvider serviceProvider, CommandID cmdID, object arg) {
OleMenuCommandService mcs = serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
mcs.GlobalInvoke(cmdID, arg);
}
internal static void ShowOptionsPage(this IServiceProvider serviceProvider, Type optionsPageType) {
CommandID cmd = new CommandID(VSConstants.GUID_VSStandardCommandSet97, VSConstants.cmdidToolsOptions);
serviceProvider.GlobalInvoke(
cmd,
optionsPageType.GUID.ToString()
);
}
internal static void ShowInterpreterList(this IServiceProvider serviceProvider) {
serviceProvider.ShowWindowPane(typeof(InterpreterListToolWindow), true);
}
internal static void ShowWindowPane(this IServiceProvider serviceProvider, Type windowPane, bool focus) {
var toolWindowService = (IPythonToolsToolWindowService)serviceProvider.GetService(typeof(IPythonToolsToolWindowService));
toolWindowService.ShowWindowPane(windowPane, focus);
}
public static string BrowseForDirectory(this IServiceProvider provider, IntPtr owner, string initialDirectory = null) {
IVsUIShell uiShell = provider.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (null == uiShell) {
using (var ofd = new FolderBrowserDialog()) {
ofd.RootFolder = Environment.SpecialFolder.Desktop;
ofd.ShowNewFolderButton = false;
DialogResult result;
if (owner == IntPtr.Zero) {
result = ofd.ShowDialog();
} else {
result = ofd.ShowDialog(NativeWindow.FromHandle(owner));
}
if (result == DialogResult.OK) {
return ofd.SelectedPath;
} else {
return null;
}
}
}
if (owner == IntPtr.Zero) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
}
VSBROWSEINFOW[] browseInfo = new VSBROWSEINFOW[1];
browseInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSBROWSEINFOW));
browseInfo[0].pwzInitialDir = initialDirectory;
browseInfo[0].hwndOwner = owner;
browseInfo[0].nMaxDirName = 260;
IntPtr pDirName = Marshal.AllocCoTaskMem(520);
browseInfo[0].pwzDirName = pDirName;
try {
int hr = uiShell.GetDirectoryViaBrowseDlg(browseInfo);
if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return null;
}
ErrorHandler.ThrowOnFailure(hr);
return Marshal.PtrToStringAuto(browseInfo[0].pwzDirName);
} finally {
if (pDirName != IntPtr.Zero) {
Marshal.FreeCoTaskMem(pDirName);
}
}
}
/// <summary>
/// Checks to see if this is a REPL buffer starting with a extensible command such as %cls, %load, etc...
/// </summary>
internal static bool IsReplBufferWithCommand(this ITextSnapshot snapshot) {
return snapshot.TextBuffer.Properties.ContainsProperty(typeof(IInteractiveEvaluator)) &&
snapshot.Length != 0 &&
(snapshot[0] == '%' || snapshot[0] == '$'); // IPython and normal repl commands
}
internal static bool IsAnalysisCurrent(this IPythonInterpreterFactory factory) {
var interpFact = factory as IPythonInterpreterFactoryWithDatabase;
if (interpFact != null) {
return interpFact.IsCurrent;
}
return true;
}
internal static bool IsOpenGrouping(this ClassificationSpan span) {
return span.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Grouping) &&
span.Span.Length == 1 &&
(span.Span.GetText() == "{" || span.Span.GetText() == "[" || span.Span.GetText() == "(");
}
internal static bool IsCloseGrouping(this ClassificationSpan span) {
return span.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Grouping) &&
span.Span.Length == 1 &&
(span.Span.GetText() == "}" || span.Span.GetText() == "]" || span.Span.GetText() == ")");
}
internal static T Pop<T>(this List<T> list) {
if (list.Count == 0) {
throw new InvalidOperationException();
}
var res = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
return res;
}
internal static T Peek<T>(this List<T> list) {
if (list.Count == 0) {
throw new InvalidOperationException();
}
return list[list.Count - 1];
}
internal static System.Threading.Tasks.Task StartNew(this TaskScheduler scheduler, Action func) {
return System.Threading.Tasks.Task.Factory.StartNew(func, default(CancellationToken), TaskCreationOptions.None, scheduler);
}
internal static int GetStartIncludingIndentation(this Node self, PythonAst ast) {
return self.StartIndex - (self.GetIndentationLevel(ast) ?? "").Length;
}
internal static string LimitLines(
this string str,
int maxLines = 30,
int charsPerLine = 200,
bool ellipsisAtEnd = true,
bool stopAtFirstBlankLine = false
) {
if (string.IsNullOrEmpty(str)) {
return str;
}
int lineCount = 0;
var prettyPrinted = new StringBuilder();
bool wasEmpty = true;
using (var reader = new StringReader(str)) {
for (var line = reader.ReadLine(); line != null && lineCount < maxLines; line = reader.ReadLine()) {
if (string.IsNullOrWhiteSpace(line)) {
if (wasEmpty) {
continue;
}
wasEmpty = true;
if (stopAtFirstBlankLine) {
lineCount = maxLines;
break;
}
lineCount += 1;
prettyPrinted.AppendLine();
} else {
wasEmpty = false;
lineCount += (line.Length / charsPerLine) + 1;
prettyPrinted.AppendLine(line);
}
}
}
if (ellipsisAtEnd && lineCount >= maxLines) {
prettyPrinted.AppendLine("...");
}
return prettyPrinted.ToString().Trim();
}
}
}
| |
// <copyright file="ChromeDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using OpenQA.Selenium.Remote;
using System.Collections.Generic;
namespace OpenQA.Selenium.Chrome
{
/// <summary>
/// Provides a mechanism to write tests against Chrome
/// </summary>
/// <example>
/// <code>
/// [TestFixture]
/// public class Testing
/// {
/// private IWebDriver driver;
/// <para></para>
/// [SetUp]
/// public void SetUp()
/// {
/// driver = new ChromeDriver();
/// }
/// <para></para>
/// [Test]
/// public void TestGoogle()
/// {
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// /*
/// * Rest of the test
/// */
/// }
/// <para></para>
/// [TearDown]
/// public void TearDown()
/// {
/// driver.Quit();
/// }
/// }
/// </code>
/// </example>
public class ChromeDriver : RemoteWebDriver
{
/// <summary>
/// Accept untrusted SSL Certificates
/// </summary>
public static readonly bool AcceptUntrustedCertificates = true;
private const string GetNetworkConditionsCommand = "getNetworkConditions";
private const string SetNetworkConditionsCommand = "setNetworkConditions";
private const string DeleteNetworkConditionsCommand = "deleteNetworkConditions";
private const string SendChromeCommand = "sendChromeCommand";
private const string SendChromeCommandWithResult = "sendChromeCommandWithResult";
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class.
/// </summary>
public ChromeDriver()
: this(new ChromeOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified options.
/// </summary>
/// <param name="options">The <see cref="ChromeOptions"/> to be used with the Chrome driver.</param>
public ChromeDriver(ChromeOptions options)
: this(ChromeDriverService.CreateDefaultService(), options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified driver service.
/// </summary>
/// <param name="service">The <see cref="ChromeDriverService"/> used to initialize the driver.</param>
public ChromeDriver(ChromeDriverService service)
: this(service, new ChromeOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified path
/// to the directory containing ChromeDriver.exe.
/// </summary>
/// <param name="chromeDriverDirectory">The full path to the directory containing ChromeDriver.exe.</param>
public ChromeDriver(string chromeDriverDirectory)
: this(chromeDriverDirectory, new ChromeOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified path
/// to the directory containing ChromeDriver.exe and options.
/// </summary>
/// <param name="chromeDriverDirectory">The full path to the directory containing ChromeDriver.exe.</param>
/// <param name="options">The <see cref="ChromeOptions"/> to be used with the Chrome driver.</param>
public ChromeDriver(string chromeDriverDirectory, ChromeOptions options)
: this(chromeDriverDirectory, options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified path
/// to the directory containing ChromeDriver.exe, options, and command timeout.
/// </summary>
/// <param name="chromeDriverDirectory">The full path to the directory containing ChromeDriver.exe.</param>
/// <param name="options">The <see cref="ChromeOptions"/> to be used with the Chrome driver.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public ChromeDriver(string chromeDriverDirectory, ChromeOptions options, TimeSpan commandTimeout)
: this(ChromeDriverService.CreateDefaultService(chromeDriverDirectory), options, commandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified
/// <see cref="ChromeDriverService"/> and options.
/// </summary>
/// <param name="service">The <see cref="ChromeDriverService"/> to use.</param>
/// <param name="options">The <see cref="ChromeOptions"/> used to initialize the driver.</param>
public ChromeDriver(ChromeDriverService service, ChromeOptions options)
: this(service, options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriver"/> class using the specified <see cref="ChromeDriverService"/>.
/// </summary>
/// <param name="service">The <see cref="ChromeDriverService"/> to use.</param>
/// <param name="options">The <see cref="ChromeOptions"/> to be used with the Chrome driver.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public ChromeDriver(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
: base(new DriverServiceCommandExecutor(service, commandTimeout), ConvertOptionsToCapabilities(options))
{
// Add the custom commands unique to Chrome
this.AddCustomChromeCommand(GetNetworkConditionsCommand, CommandInfo.GetCommand, "/session/{sessionId}/chromium/network_conditions");
this.AddCustomChromeCommand(SetNetworkConditionsCommand, CommandInfo.PostCommand, "/session/{sessionId}/chromium/network_conditions");
this.AddCustomChromeCommand(DeleteNetworkConditionsCommand, CommandInfo.DeleteCommand, "/session/{sessionId}/chromium/network_conditions");
this.AddCustomChromeCommand(SendChromeCommand, CommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command");
this.AddCustomChromeCommand(SendChromeCommandWithResult, CommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command_and_get_result");
}
/// <summary>
/// Gets or sets the <see cref="IFileDetector"/> responsible for detecting
/// sequences of keystrokes representing file paths and names.
/// </summary>
/// <remarks>The Chrome driver does not allow a file detector to be set,
/// as the server component of the Chrome driver (ChromeDriver.exe) only
/// allows uploads from the local computer environment. Attempting to set
/// this property has no effect, but does not throw an exception. If you
/// are attempting to run the Chrome driver remotely, use <see cref="RemoteWebDriver"/>
/// in conjunction with a standalone WebDriver server.</remarks>
public override IFileDetector FileDetector
{
get { return base.FileDetector; }
set { }
}
/// <summary>
/// Gets or sets the network condition emulation for Chrome.
/// </summary>
public ChromeNetworkConditions NetworkConditions
{
get
{
Response response = this.Execute(GetNetworkConditionsCommand, null);
return ChromeNetworkConditions.FromDictionary(response.Value as Dictionary<string, object>);
}
set
{
if (value == null)
{
throw new ArgumentNullException("value", "value must not be null");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["network_conditions"] = value.ToDictionary();
this.Execute(SetNetworkConditionsCommand, parameters);
}
}
/// <summary>
/// Executes a custom Chrome command.
/// </summary>
/// <param name="commandName">Name of the command to execute.</param>
/// <param name="commandParameters">Parameters of the command to execute.</param>
public void ExecuteChromeCommand(string commandName, Dictionary<string, object> commandParameters)
{
if (commandName == null)
{
throw new ArgumentNullException("commandName", "commandName must not be null");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["cmd"] = commandName;
parameters["params"] = commandParameters;
this.Execute(SendChromeCommand, parameters);
}
public object ExecuteChromeCommandWithResult(string commandName, Dictionary<string, object> commandParameters)
{
if (commandName == null)
{
throw new ArgumentNullException("commandName", "commandName must not be null");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["cmd"] = commandName;
parameters["params"] = commandParameters;
Response response = this.Execute(SendChromeCommandWithResult, parameters);
return response.Value;
}
private static ICapabilities ConvertOptionsToCapabilities(ChromeOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options", "options must not be null");
}
return options.ToCapabilities();
}
private void AddCustomChromeCommand(string commandName, string method, string resourcePath)
{
CommandInfo commandInfoToAdd = new CommandInfo(method, resourcePath);
this.CommandExecutor.CommandInfoRepository.TryAddCommand(commandName, commandInfoToAdd);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Hosting;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Transactions;
namespace Orleans.Runtime
{
internal class Message : IOutgoingMessage
{
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
#region metadata
[NonSerialized]
private string _targetHistory;
[NonSerialized]
private DateTime? _queuedTime;
[NonSerialized]
private int? _retryCount;
[NonSerialized]
private int? _maxRetries;
public string TargetHistory
{
get { return _targetHistory; }
set { _targetHistory = value; }
}
public DateTime? QueuedTime
{
get { return _queuedTime; }
set { _queuedTime = value; }
}
public int? RetryCount
{
get { return _retryCount; }
set { _retryCount = value; }
}
public int? MaxRetries
{
get { return _maxRetries; }
set { _maxRetries = value; }
}
#endregion
/// <summary>
/// NOTE: The contents of bodyBytes should never be modified
/// </summary>
private List<ArraySegment<byte>> bodyBytes;
private List<ArraySegment<byte>> headerBytes;
private object bodyObject;
// Cache values of TargetAddess and SendingAddress as they are used very frequently
private ActivationAddress targetAddress;
private ActivationAddress sendingAddress;
static Message()
{
}
public enum Categories
{
Ping,
System,
Application,
}
public enum Directions
{
Request,
Response,
OneWay
}
public enum ResponseTypes
{
Success,
Error,
Rejection
}
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
}
internal HeadersContainer Headers { get; set; } = new HeadersContainer();
public Categories Category
{
get { return Headers.Category; }
set { Headers.Category = value; }
}
public Directions Direction
{
get { return Headers.Direction ?? default(Directions); }
set { Headers.Direction = value; }
}
public bool HasDirection => Headers.Direction.HasValue;
public bool IsReadOnly
{
get { return Headers.IsReadOnly; }
set { Headers.IsReadOnly = value; }
}
public bool IsAlwaysInterleave
{
get { return Headers.IsAlwaysInterleave; }
set { Headers.IsAlwaysInterleave = value; }
}
public bool IsUnordered
{
get { return Headers.IsUnordered; }
set { Headers.IsUnordered = value; }
}
public bool IsReturnedFromRemoteCluster
{
get { return Headers.IsReturnedFromRemoteCluster; }
set { Headers.IsReturnedFromRemoteCluster = value; }
}
public bool IsTransactionRequired
{
get { return Headers.IsTransactionRequired; }
set { Headers.IsTransactionRequired = value; }
}
public CorrelationId Id
{
get { return Headers.Id; }
set { Headers.Id = value; }
}
public int ResendCount
{
get { return Headers.ResendCount; }
set { Headers.ResendCount = value; }
}
public int ForwardCount
{
get { return Headers.ForwardCount; }
set { Headers.ForwardCount = value; }
}
public SiloAddress TargetSilo
{
get { return Headers.TargetSilo; }
set
{
Headers.TargetSilo = value;
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return Headers.TargetGrain; }
set
{
Headers.TargetGrain = value;
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return Headers.TargetActivation; }
set
{
Headers.TargetActivation = value;
targetAddress = null;
}
}
public ActivationAddress TargetAddress
{
get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); }
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public GuidId TargetObserverId
{
get { return Headers.TargetObserverId; }
set
{
Headers.TargetObserverId = value;
targetAddress = null;
}
}
public SiloAddress SendingSilo
{
get { return Headers.SendingSilo; }
set
{
Headers.SendingSilo = value;
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return Headers.SendingGrain; }
set
{
Headers.SendingGrain = value;
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return Headers.SendingActivation; }
set
{
Headers.SendingActivation = value;
sendingAddress = null;
}
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return Headers.IsNewPlacement; }
set
{
Headers.IsNewPlacement = value;
}
}
public bool IsUsingInterfaceVersions
{
get { return Headers.IsUsingIfaceVersion; }
set
{
Headers.IsUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return Headers.Result; }
set { Headers.Result = value; }
}
public TimeSpan? TimeToLive
{
get { return Headers.TimeToLive; }
set { Headers.TimeToLive = value; }
}
public bool IsExpired
{
get
{
if (!TimeToLive.HasValue)
return false;
return TimeToLive <= TimeSpan.Zero;
}
}
public bool IsExpirableMessage(bool dropExpiredMessages)
{
if (!dropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id == null) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget && !Constants.IsSystemGrain(id);
}
public ITransactionInfo TransactionInfo
{
get { return Headers.TransactionInfo; }
set { Headers.TransactionInfo = value; }
}
public string DebugContext
{
get { return GetNotNullString(Headers.DebugContext); }
set { Headers.DebugContext = value; }
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return Headers.CacheInvalidationHeader; }
set { Headers.CacheInvalidationHeader = value; }
}
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (CacheInvalidationHeader != null)
{
list.AddRange(CacheInvalidationHeader);
}
list.Add(address);
CacheInvalidationHeader = list;
}
// Resends are used by the sender, usualy due to en error to send or due to a transient rejection.
public bool MayResend(int maxResendCount)
{
return ResendCount < maxResendCount;
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return GetNotNullString(Headers.NewGrainType); }
set { Headers.NewGrainType = value; }
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return GetNotNullString(Headers.GenericGrainType); }
set { Headers.GenericGrainType = value; }
}
public RejectionTypes RejectionType
{
get { return Headers.RejectionType; }
set { Headers.RejectionType = value; }
}
public string RejectionInfo
{
get { return GetNotNullString(Headers.RejectionInfo); }
set { Headers.RejectionInfo = value; }
}
public Dictionary<string, object> RequestContextData
{
get { return Headers.RequestContextData; }
set { Headers.RequestContextData = value; }
}
public object GetDeserializedBody(SerializationManager serializationManager)
{
if (this.bodyObject != null) return this.bodyObject;
try
{
this.bodyObject = DeserializeBody(serializationManager, this.bodyBytes);
}
finally
{
if (this.bodyBytes != null)
{
BufferPool.GlobalPool.Release(bodyBytes);
this.bodyBytes = null;
}
}
return this.bodyObject;
}
public object BodyObject
{
set
{
bodyObject = value;
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
private static object DeserializeBody(SerializationManager serializationManager, List<ArraySegment<byte>> bytes)
{
if (bytes == null)
{
return null;
}
var stream = new BinaryTokenStreamReader(bytes);
return serializationManager.Deserialize(stream);
}
public Message()
{
bodyObject = null;
bodyBytes = null;
headerBytes = null;
}
/// <summary>
/// Clears the current body and sets the serialized body contents to the provided value.
/// </summary>
/// <param name="body">The serialized body contents.</param>
public void SetBodyBytes(List<ArraySegment<byte>> body)
{
// Dispose of the current body.
this.BodyObject = null;
this.bodyBytes = body;
}
/// <summary>
/// Deserializes the provided value into this instance's <see cref="BodyObject"/>.
/// </summary>
/// <param name="serializationManager">The serialization manager.</param>
/// <param name="body">The serialized body contents.</param>
public void DeserializeBodyObject(SerializationManager serializationManager, List<ArraySegment<byte>> body)
{
this.BodyObject = DeserializeBody(serializationManager, body);
}
public void ClearTargetAddress()
{
targetAddress = null;
}
private static string GetNotNullString(string s)
{
return s ?? string.Empty;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
#region Serialization
public List<ArraySegment<byte>> Serialize(SerializationManager serializationManager, out int headerLengthOut, out int bodyLengthOut)
{
var context = new SerializationContext(serializationManager)
{
StreamWriter = new BinaryTokenStreamWriter()
};
SerializationManager.SerializeMessageHeaders(Headers, context);
if (bodyBytes == null)
{
var bodyStream = new BinaryTokenStreamWriter();
serializationManager.Serialize(bodyObject, bodyStream);
// We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
// being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
// serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
// pretty high (an array allocation plus a bunch of copying).
bodyBytes = bodyStream.ToBytes();
}
if (headerBytes != null)
{
BufferPool.GlobalPool.Release(headerBytes);
}
headerBytes = context.StreamWriter.ToBytes();
int headerLength = context.StreamWriter.CurrentOffset;
int bodyLength = BufferLength(bodyBytes);
var bytes = new List<ArraySegment<byte>>();
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength)));
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength)));
bytes.AddRange(headerBytes);
bytes.AddRange(bodyBytes);
headerLengthOut = headerLength;
bodyLengthOut = bodyLength;
return bytes;
}
public void ReleaseBodyAndHeaderBuffers()
{
ReleaseHeadersOnly();
ReleaseBodyOnly();
}
public void ReleaseHeadersOnly()
{
if (headerBytes == null) return;
BufferPool.GlobalPool.Release(headerBytes);
headerBytes = null;
}
public void ReleaseBodyOnly()
{
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
#endregion
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
string debugContex = DebugContext;
if (!string.IsNullOrEmpty(debugContex))
{
// if DebugContex is present, print it first.
sb.Append(debugContex).Append(".");
}
AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader);
AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category);
AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction);
AppendIfExists(HeadersContainer.Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive);
AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount);
AppendIfExists(HeadersContainer.Headers.GENERIC_GRAIN_TYPE, sb, (m) => m.GenericGrainType);
AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id);
AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave);
AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement);
AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster);
AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly);
AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered);
AppendIfExists(HeadersContainer.Headers.NEW_GRAIN_TYPE, sb, (m) => m.NewGrainType);
AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo);
AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType);
AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData);
AppendIfExists(HeadersContainer.Headers.RESEND_COUNT, sb, (m) => m.ResendCount);
AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result);
AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation);
AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain);
AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo);
AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation);
AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain);
AppendIfExists(HeadersContainer.Headers.TARGET_OBSERVER, sb, (m) => m.TargetObserverId);
AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo);
return sb.ToString();
}
private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider)
{
// used only under log3 level
if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE)
{
sb.AppendFormat("{0}={1};", header, valueProvider(this));
sb.AppendLine();
}
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5
String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6
Id, //7
ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9
DebugContext); //10
}
internal void SetTargetPlacement(PlacementResult value)
{
TargetActivation = value.Activation;
TargetSilo = value.Silo;
if (value.IsNewPlacement)
IsNewPlacement = true;
if (!String.IsNullOrEmpty(value.GrainType))
NewGrainType = value.GrainType;
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (TargetSilo != null)
{
history.Append(TargetSilo).Append(":");
}
if (TargetGrain != null)
{
history.Append(TargetGrain).Append(":");
}
if (TargetActivation != null)
{
history.Append(TargetActivation);
}
history.Append(">");
if (!string.IsNullOrEmpty(TargetHistory))
{
history.Append(" ").Append(TargetHistory);
}
return history.ToString();
}
public bool IsSameDestination(IOutgoingMessage other)
{
var msg = (Message)other;
return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
}
// For statistical measuring of time spent in queues.
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed
{
get { return timeInterval.Elapsed; }
}
public static Message CreatePromptExceptionResponse(Message request, Exception exception)
{
return new Message
{
Category = request.Category,
Direction = Message.Directions.Response,
Result = Message.ResponseTypes.Error,
BodyObject = Response.ExceptionResponse(exception)
};
}
internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase)
{
MessagingStatisticsGroup.OnMessageExpired(phase);
ReleaseBodyAndHeaderBuffers();
}
private static int BufferLength(List<ArraySegment<byte>> buffer)
{
var result = 0;
for (var i = 0; i < buffer.Count; i++)
{
result += buffer[i].Count;
}
return result;
}
[Serializable]
public class HeadersContainer
{
[Flags]
public enum Headers
{
NONE = 0,
ALWAYS_INTERLEAVE = 1 << 0,
CACHE_INVALIDATION_HEADER = 1 << 1,
CATEGORY = 1 << 2,
CORRELATION_ID = 1 << 3,
DEBUG_CONTEXT = 1 << 4,
DIRECTION = 1 << 5,
TIME_TO_LIVE = 1 << 6,
FORWARD_COUNT = 1 << 7,
NEW_GRAIN_TYPE = 1 << 8,
GENERIC_GRAIN_TYPE = 1 << 9,
RESULT = 1 << 10,
REJECTION_INFO = 1 << 11,
REJECTION_TYPE = 1 << 12,
READ_ONLY = 1 << 13,
RESEND_COUNT = 1 << 14,
SENDING_ACTIVATION = 1 << 15,
SENDING_GRAIN = 1 <<16,
SENDING_SILO = 1 << 17,
IS_NEW_PLACEMENT = 1 << 18,
TARGET_ACTIVATION = 1 << 19,
TARGET_GRAIN = 1 << 20,
TARGET_SILO = 1 << 21,
TARGET_OBSERVER = 1 << 22,
IS_UNORDERED = 1 << 23,
REQUEST_CONTEXT = 1 << 24,
IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25,
IS_USING_INTERFACE_VERSION = 1 << 26,
// transactions
TRANSACTION_INFO = 1 << 27,
IS_TRANSACTION_REQUIRED = 1 << 28,
// Do not add over int.MaxValue of these.
}
private Categories _category;
private Directions? _direction;
private bool _isReadOnly;
private bool _isAlwaysInterleave;
private bool _isUnordered;
private bool _isReturnedFromRemoteCluster;
private bool _isTransactionRequired;
private CorrelationId _id;
private int _resendCount;
private int _forwardCount;
private SiloAddress _targetSilo;
private GrainId _targetGrain;
private ActivationId _targetActivation;
private GuidId _targetObserverId;
private SiloAddress _sendingSilo;
private GrainId _sendingGrain;
private ActivationId _sendingActivation;
private bool _isNewPlacement;
private bool _isUsingIfaceVersion;
private ResponseTypes _result;
private ITransactionInfo _transactionInfo;
private TimeSpan? _timeToLive;
private string _debugContext;
private List<ActivationAddress> _cacheInvalidationHeader;
private string _newGrainType;
private string _genericGrainType;
private RejectionTypes _rejectionType;
private string _rejectionInfo;
private Dictionary<string, object> _requestContextData;
private readonly DateTime _localCreationTime;
public HeadersContainer()
{
_localCreationTime = DateTime.UtcNow;
}
public Categories Category
{
get { return _category; }
set
{
_category = value;
}
}
public Directions? Direction
{
get { return _direction; }
set
{
_direction = value;
}
}
public bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
}
}
public bool IsAlwaysInterleave
{
get { return _isAlwaysInterleave; }
set
{
_isAlwaysInterleave = value;
}
}
public bool IsUnordered
{
get { return _isUnordered; }
set
{
_isUnordered = value;
}
}
public bool IsReturnedFromRemoteCluster
{
get { return _isReturnedFromRemoteCluster; }
set
{
_isReturnedFromRemoteCluster = value;
}
}
public bool IsTransactionRequired
{
get { return _isTransactionRequired; }
set
{
_isTransactionRequired = value;
}
}
public CorrelationId Id
{
get { return _id; }
set
{
_id = value;
}
}
public int ResendCount
{
get { return _resendCount; }
set
{
_resendCount = value;
}
}
public int ForwardCount
{
get { return _forwardCount; }
set
{
_forwardCount = value;
}
}
public SiloAddress TargetSilo
{
get { return _targetSilo; }
set
{
_targetSilo = value;
}
}
public GrainId TargetGrain
{
get { return _targetGrain; }
set
{
_targetGrain = value;
}
}
public ActivationId TargetActivation
{
get { return _targetActivation; }
set
{
_targetActivation = value;
}
}
public GuidId TargetObserverId
{
get { return _targetObserverId; }
set
{
_targetObserverId = value;
}
}
public SiloAddress SendingSilo
{
get { return _sendingSilo; }
set
{
_sendingSilo = value;
}
}
public GrainId SendingGrain
{
get { return _sendingGrain; }
set
{
_sendingGrain = value;
}
}
public ActivationId SendingActivation
{
get { return _sendingActivation; }
set
{
_sendingActivation = value;
}
}
public bool IsNewPlacement
{
get { return _isNewPlacement; }
set
{
_isNewPlacement = value;
}
}
public bool IsUsingIfaceVersion
{
get { return _isUsingIfaceVersion; }
set
{
_isUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return _result; }
set
{
_result = value;
}
}
public ITransactionInfo TransactionInfo
{
get { return _transactionInfo; }
set
{
_transactionInfo = value;
}
}
public TimeSpan? TimeToLive
{
get
{
return _timeToLive - (DateTime.UtcNow - _localCreationTime);
}
set
{
_timeToLive = value;
}
}
public string DebugContext
{
get { return _debugContext; }
set
{
_debugContext = value;
}
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return _cacheInvalidationHeader; }
set
{
_cacheInvalidationHeader = value;
}
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return _newGrainType; }
set
{
_newGrainType = value;
}
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return _genericGrainType; }
set
{
_genericGrainType = value;
}
}
public RejectionTypes RejectionType
{
get { return _rejectionType; }
set
{
_rejectionType = value;
}
}
public string RejectionInfo
{
get { return _rejectionInfo; }
set
{
_rejectionInfo = value;
}
}
public Dictionary<string, object> RequestContextData
{
get { return _requestContextData; }
set
{
_requestContextData = value;
}
}
internal Headers GetHeadersMask()
{
Headers headers = Headers.NONE;
if(Category != default(Categories))
headers = headers | Headers.CATEGORY;
headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION;
if (IsReadOnly)
headers = headers | Headers.READ_ONLY;
if (IsAlwaysInterleave)
headers = headers | Headers.ALWAYS_INTERLEAVE;
if(IsUnordered)
headers = headers | Headers.IS_UNORDERED;
headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID;
if (_resendCount != default(int))
headers = headers | Headers.RESEND_COUNT;
if(_forwardCount != default (int))
headers = headers | Headers.FORWARD_COUNT;
headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO;
headers = _targetGrain == null ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN;
headers = _targetActivation == null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION;
headers = _targetObserverId == null ? headers & ~Headers.TARGET_OBSERVER : headers | Headers.TARGET_OBSERVER;
headers = _sendingSilo == null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO;
headers = _sendingGrain == null ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN;
headers = _sendingActivation == null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION;
headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT;
headers = _isReturnedFromRemoteCluster == default(bool) ? headers & ~Headers.IS_RETURNED_FROM_REMOTE_CLUSTER : headers | Headers.IS_RETURNED_FROM_REMOTE_CLUSTER;
headers = _isUsingIfaceVersion == default(bool) ? headers & ~Headers.IS_USING_INTERFACE_VERSION : headers | Headers.IS_USING_INTERFACE_VERSION;
headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT;
headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE;
headers = string.IsNullOrEmpty(_debugContext) ? headers & ~Headers.DEBUG_CONTEXT : headers | Headers.DEBUG_CONTEXT;
headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER;
headers = string.IsNullOrEmpty(_newGrainType) ? headers & ~Headers.NEW_GRAIN_TYPE : headers | Headers.NEW_GRAIN_TYPE;
headers = string.IsNullOrEmpty(GenericGrainType) ? headers & ~Headers.GENERIC_GRAIN_TYPE : headers | Headers.GENERIC_GRAIN_TYPE;
headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE;
headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO;
headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT;
headers = IsTransactionRequired ? headers | Headers.IS_TRANSACTION_REQUIRED : headers & ~Headers.IS_TRANSACTION_REQUIRED;
headers = _transactionInfo == null ? headers & ~Headers.TRANSACTION_INFO : headers | Headers.TRANSACTION_INFO;
return headers;
}
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
return original;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
HeadersContainer input = (HeadersContainer)untypedInput;
var headers = input.GetHeadersMask();
var writer = context.StreamWriter;
writer.Write((int)headers);
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var count = input.CacheInvalidationHeader.Count;
writer.Write(input.CacheInvalidationHeader.Count);
for (int i = 0; i < count; i++)
{
WriteObj(context, typeof(ActivationAddress), input.CacheInvalidationHeader[i]);
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
{
writer.Write((byte)input.Category);
}
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
writer.Write(input.DebugContext);
if ((headers & Headers.DIRECTION) != Headers.NONE)
writer.Write((byte)input.Direction.Value);
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
writer.Write(input.TimeToLive.Value);
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
writer.Write(input.ForwardCount);
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.GenericGrainType);
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
writer.Write(input.Id);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
writer.Write(input.IsAlwaysInterleave);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
writer.Write(input.IsNewPlacement);
if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE)
writer.Write(input.IsReturnedFromRemoteCluster);
// Nothing to do with Headers.IS_USING_INTERFACE_VERSION since the value in
// the header is sufficient
if ((headers & Headers.READ_ONLY) != Headers.NONE)
writer.Write(input.IsReadOnly);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
writer.Write(input.IsUnordered);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.NewGrainType);
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
writer.Write(input.RejectionInfo);
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
writer.Write((byte)input.RejectionType);
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var requestData = input.RequestContextData;
var count = requestData.Count;
writer.Write(count);
foreach (var d in requestData)
{
writer.Write(d.Key);
SerializationManager.SerializeInner(d.Value, context, typeof(object));
}
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
writer.Write(input.ResendCount);
if ((headers & Headers.RESULT) != Headers.NONE)
writer.Write((byte)input.Result);
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
{
writer.Write(input.SendingActivation);
}
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
{
writer.Write(input.SendingGrain);
}
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
{
writer.Write(input.SendingSilo);
}
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
{
writer.Write(input.TargetActivation);
}
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
{
writer.Write(input.TargetGrain);
}
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
{
WriteObj(context, typeof(GuidId), input.TargetObserverId);
}
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
{
writer.Write(input.TargetSilo);
}
if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE)
SerializationManager.SerializeInner(input.TransactionInfo, context, typeof(ITransactionInfo));
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
var result = new HeadersContainer();
var reader = context.StreamReader;
context.RecordObject(result);
var headers = (Headers)reader.ReadInt();
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var n = reader.ReadInt();
if (n > 0)
{
var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n);
for (int i = 0; i < n; i++)
{
list.Add((ActivationAddress)ReadObj(typeof(ActivationAddress), context));
}
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
result.Category = (Categories)reader.ReadByte();
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
result.DebugContext = reader.ReadString();
if ((headers & Headers.DIRECTION) != Headers.NONE)
result.Direction = (Message.Directions)reader.ReadByte();
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
result.TimeToLive = reader.ReadTimeSpan();
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
result.ForwardCount = reader.ReadInt();
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
result.GenericGrainType = reader.ReadString();
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
result.Id = (Orleans.Runtime.CorrelationId)ReadObj(typeof(Orleans.Runtime.CorrelationId), context);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
result.IsAlwaysInterleave = ReadBool(reader);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
result.IsNewPlacement = ReadBool(reader);
if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE)
result.IsReturnedFromRemoteCluster = ReadBool(reader);
if ((headers & Headers.IS_USING_INTERFACE_VERSION) != Headers.NONE)
result.IsUsingIfaceVersion = true;
if ((headers & Headers.READ_ONLY) != Headers.NONE)
result.IsReadOnly = ReadBool(reader);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
result.IsUnordered = ReadBool(reader);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
result.NewGrainType = reader.ReadString();
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
result.RejectionInfo = reader.ReadString();
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
result.RejectionType = (RejectionTypes)reader.ReadByte();
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var c = reader.ReadInt();
var requestData = new Dictionary<string, object>(c);
for (int i = 0; i < c; i++)
{
requestData[reader.ReadString()] = SerializationManager.DeserializeInner(null, context);
}
result.RequestContextData = requestData;
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
result.ResendCount = reader.ReadInt();
if ((headers & Headers.RESULT) != Headers.NONE)
result.Result = (Orleans.Runtime.Message.ResponseTypes)reader.ReadByte();
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
result.SendingActivation = reader.ReadActivationId();
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
result.SendingGrain = reader.ReadGrainId();
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
result.SendingSilo = reader.ReadSiloAddress();
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
result.TargetActivation = reader.ReadActivationId();
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
result.TargetGrain = reader.ReadGrainId();
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
result.TargetObserverId = (Orleans.Runtime.GuidId)ReadObj(typeof(Orleans.Runtime.GuidId), context);
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
result.TargetSilo = reader.ReadSiloAddress();
result.IsTransactionRequired = (headers & Headers.IS_TRANSACTION_REQUIRED) != Headers.NONE;
if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE)
result.TransactionInfo = SerializationManager.DeserializeInner<ITransactionInfo>(context);
return result;
}
private static bool ReadBool(IBinaryTokenStreamReader stream)
{
return stream.ReadByte() == (byte) SerializationTokenType.True;
}
private static void WriteObj(ISerializationContext context, Type type, object input)
{
var ser = context.GetSerializationManager().GetSerializer(type);
ser.Invoke(input, context, type);
}
private static object ReadObj(Type t, IDeserializationContext context)
{
var des = context.GetSerializationManager().GetDeserializer(t);
return des.Invoke(t, context);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// UAudioManagerBase provides the base functionality for UAudioManager classes.
/// </summary>
/// <typeparam name="TEvent">The type of AudioEvent being managed.</typeparam>
/// <remarks>The TEvent type specified must derive from AudioEvent.</remarks>
public partial class UAudioManagerBase<TEvent> : MonoBehaviour where TEvent : AudioEvent, new()
{
[SerializeField]
protected TEvent[] events = null;
protected const float InfiniteLoop = -1;
protected List<ActiveEvent> activeEvents;
#if UNITY_EDITOR
public TEvent[] EditorEvents { get { return events; } set { events = value; } }
public List<ActiveEvent> ProfilerEvents { get { return activeEvents; } }
#endif
protected void Awake()
{
activeEvents = new List<ActiveEvent>();
}
private void Update()
{
UpdateEmitterVolumes();
}
protected void OnDestroy()
{
StopAllEvents();
}
/// <summary>
/// Stops all ActiveEvents
/// </summary>
public void StopAllEvents()
{
for (int i = activeEvents.Count - 1; i >= 0; i--)
{
StopEvent(activeEvents[i]);
}
}
/// <summary>
/// Fades out all of the events over fadeTime and stops once completely faded out.
/// </summary>
/// <param name="fadeTime">The amount of time, in seconds, to fade between current volume and 0.</param>
public void StopAllEvents(float fadeTime)
{
for (int i = activeEvents.Count - 1; i >= 0; i--)
{
StartCoroutine(StopEventWithFadeCoroutine(activeEvents[i], fadeTime));
}
}
/// <summary>
/// Stops all events on a single emitter.
/// </summary>
public void StopAllEvents(GameObject emitter)
{
for (int i = activeEvents.Count - 1; i >= 0; i--)
{
if (activeEvents[i].AudioEmitter == emitter)
{
StopEvent(activeEvents[i]);
}
}
}
/// <summary>
/// Stops all events on one AudioSource.
/// </summary>
public void StopAllEvents(AudioSource emitter)
{
for (int i = activeEvents.Count - 1; i >= 0; i--)
{
if (activeEvents[i].PrimarySource == emitter)
{
StopEvent(activeEvents[i]);
}
}
}
/// <summary>
/// Linearly interpolates the volume property on all of the AudioSource components in the ActiveEvents.
/// </summary>
private void UpdateEmitterVolumes()
{
// Move through each active event and change the settings for the AudioSource components to smoothly fade volumes.
for (int i = 0; i < activeEvents.Count; i++)
{
ActiveEvent currentEvent = this.activeEvents[i];
// If we have a secondary source (for crossfades) adjust the volume based on the current fade time for each active event.
if (currentEvent.SecondarySource != null && currentEvent.SecondarySource.volume != currentEvent.altVolDest)
{
if (Mathf.Abs(currentEvent.altVolDest - currentEvent.SecondarySource.volume) < Time.deltaTime / currentEvent.currentFade)
{
currentEvent.SecondarySource.volume = currentEvent.altVolDest;
}
else
{
currentEvent.SecondarySource.volume += (currentEvent.altVolDest - currentEvent.SecondarySource.volume) * Time.deltaTime / currentEvent.currentFade;
}
}
// Adjust the volume of the main source based on the current fade time for each active event.
if (currentEvent.PrimarySource != null && currentEvent.PrimarySource.volume != currentEvent.volDest)
{
if (Mathf.Abs(currentEvent.volDest - currentEvent.PrimarySource.volume) < Time.deltaTime / currentEvent.currentFade)
{
currentEvent.PrimarySource.volume = currentEvent.volDest;
}
else
{
currentEvent.PrimarySource.volume += (currentEvent.volDest - currentEvent.PrimarySource.volume) * Time.deltaTime / currentEvent.currentFade;
}
}
// If there is no time left in the fade, make sure we are set to the destination volume.
if (currentEvent.currentFade > 0)
{
currentEvent.currentFade -= Time.deltaTime;
}
}
}
/// <summary>
/// Determine which rules to follow for container playback, and begin the appropriate function.
/// </summary>
/// <param name="activeEvent">The event to play.</param>
protected void PlayContainer(ActiveEvent activeEvent)
{
if (activeEvent.audioEvent.container.sounds.Length == 0)
{
Debug.LogErrorFormat(this, "Trying to play container \"{0}\" with no clips.", activeEvent.audioEvent.container);
// Clean up the ActiveEvent before we discard it, so it will release its AudioSource(s).
activeEvent.Dispose();
return;
}
switch (activeEvent.audioEvent.container.containerType)
{
case AudioContainerType.Random:
StartOneOffEvent(activeEvent);
break;
case AudioContainerType.Simultaneous:
StartOneOffEvent(activeEvent);
break;
case AudioContainerType.Sequence:
StartOneOffEvent(activeEvent);
break;
case AudioContainerType.ContinuousSequence:
PlayContinuousSequenceContainer(activeEvent.audioEvent.container, activeEvent.PrimarySource, activeEvent);
break;
case AudioContainerType.ContinuousRandom:
PlayContinuousRandomContainer(activeEvent.audioEvent.container, activeEvent.PrimarySource, activeEvent);
break;
default:
Debug.LogErrorFormat(this, "Trying to play container \"{0}\" with an unknown AudioContainerType \"{1}\".", activeEvent.audioEvent.container, activeEvent.audioEvent.container.containerType);
// Clean up the ActiveEvent before we discard it, so it will release its AudioSource(s).
activeEvent.Dispose();
break;
}
}
/// <summary>
/// Begin playing a non-continuous container, loop if applicable.
/// </summary>
private void StartOneOffEvent(ActiveEvent activeEvent)
{
if (activeEvent.audioEvent.container.looping)
{
StartCoroutine(PlayLoopingOneOffContainerCoroutine(activeEvent));
activeEvent.activeTime = InfiniteLoop;
}
else
{
PlayOneOffContainer(activeEvent);
}
StartCoroutine(RecordEventInstanceCoroutine(activeEvent));
}
/// <summary>
/// Play a non-continuous container.
/// </summary>
private float PlayOneOffContainer(ActiveEvent activeEvent)
{
AudioContainer currentContainer = activeEvent.audioEvent.container;
// Fading or looping overrides immediate volume settings.
if (activeEvent.audioEvent.fadeInTime == 0 && !activeEvent.audioEvent.container.looping)
{
activeEvent.volDest = activeEvent.PrimarySource.volume;
}
// Simultaneous sounds.
float clipTime = 0;
if (currentContainer.containerType == AudioContainerType.Simultaneous)
{
clipTime = PlaySimultaneousClips(currentContainer, activeEvent);
}
// Sequential and Random sounds.
else
{
clipTime = PlaySingleClip(currentContainer, activeEvent);
}
activeEvent.activeTime = clipTime;
return clipTime;
}
/// <summary>
/// Play all clips in container simultaneously
/// </summary>
private float PlaySimultaneousClips(AudioContainer currentContainer, ActiveEvent activeEvent)
{
float tempDelay = 0;
float finalActiveTime = 0f;
if (currentContainer.looping)
{
finalActiveTime = InfiniteLoop;
}
for (int i = 0; i < currentContainer.sounds.Length; i++)
{
tempDelay = PlayClipAndGetTime(currentContainer.sounds[i], activeEvent.PrimarySource, activeEvent);
if (finalActiveTime != InfiniteLoop)
{
float estimatedActiveTimeNeeded = GetActiveTimeEstimate(currentContainer.sounds[i], activeEvent, tempDelay);
if (estimatedActiveTimeNeeded == InfiniteLoop || estimatedActiveTimeNeeded > finalActiveTime)
{
finalActiveTime = estimatedActiveTimeNeeded;
}
}
}
return finalActiveTime;
}
/// <summary>
/// Play one sound from a container based on container behavior.
/// </summary>
/// <param name="currentContainer"></param>
/// <param name="activeEvent"></param>
/// <returns>The estimated ActiveTime for the clip, or InfiniteLoop if the container and/or clip are set to loop.</returns>
private float PlaySingleClip(AudioContainer currentContainer, ActiveEvent activeEvent)
{
float tempDelay = 0;
if (currentContainer.containerType == AudioContainerType.Random)
{
currentContainer.currentClip = Random.Range(0, currentContainer.sounds.Length);
}
UAudioClip currentClip = currentContainer.sounds[currentContainer.currentClip];
// Trigger sound and save the delay (in seconds) to add to the total amount of time the event will be considered active.
tempDelay = PlayClipAndGetTime(currentClip, activeEvent.PrimarySource, activeEvent);
// Ready the next clip in the series if sequence container.
if (currentContainer.containerType == AudioContainerType.Sequence)
{
currentContainer.currentClip++;
if (currentContainer.currentClip >= currentContainer.sounds.Length)
{
currentContainer.currentClip = 0;
}
}
// Return active time based on looping or clip time.
return GetActiveTimeEstimate(currentClip, activeEvent, tempDelay);
}
/// <summary>
/// Repeatedly trigger the one-off container based on the loop time.
/// </summary>
private IEnumerator PlayLoopingOneOffContainerCoroutine(ActiveEvent activeEvent)
{
while (!activeEvent.cancelEvent)
{
float tempLoopTime = PlayOneOffContainer(activeEvent);
float eventLoopTime = activeEvent.audioEvent.container.loopTime;
// Protect against containers looping every frame by defaulting to the length of the audio clip.
if (eventLoopTime != 0)
{
tempLoopTime = eventLoopTime;
}
yield return new WaitForSeconds(tempLoopTime);
}
}
/// <summary>
/// Choose a random sound from a container and play, calling the looping coroutine to constantly choose new audio clips when current clip ends.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
private void PlayContinuousRandomContainer(AudioContainer audioContainer, AudioSource emitter, ActiveEvent activeEvent)
{
audioContainer.currentClip = Random.Range(0, audioContainer.sounds.Length);
UAudioClip tempClip = audioContainer.sounds[audioContainer.currentClip];
activeEvent.PrimarySource.volume = 0f;
activeEvent.volDest = activeEvent.audioEvent.volumeCenter;
activeEvent.altVolDest = 0f;
activeEvent.currentFade = audioContainer.crossfadeTime;
float waitTime = (tempClip.sound.length / emitter.pitch) - activeEvent.audioEvent.container.crossfadeTime;
// Ignore clip delay since container is continuous.
PlayClipAndGetTime(tempClip, emitter, activeEvent);
activeEvent.activeTime = InfiniteLoop;
StartCoroutine(RecordEventInstanceCoroutine(activeEvent));
audioContainer.currentClip++;
if (audioContainer.currentClip >= audioContainer.sounds.Length)
{
audioContainer.currentClip = 0;
}
StartCoroutine(ContinueRandomContainerCoroutine(audioContainer, activeEvent, waitTime));
}
/// <summary>
/// Coroutine for "continuous" random containers that alternates between two sources to crossfade clips for continuous playlist looping.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <param name="waitTime">The time in seconds to wait before switching AudioSources for crossfading.</param>
/// <returns>The coroutine.</returns>
private IEnumerator ContinueRandomContainerCoroutine(AudioContainer audioContainer, ActiveEvent activeEvent, float waitTime)
{
while (!activeEvent.cancelEvent)
{
yield return new WaitForSeconds(waitTime);
audioContainer.currentClip = Random.Range(0, audioContainer.sounds.Length);
UAudioClip tempClip = audioContainer.sounds[audioContainer.currentClip];
// Play on primary source.
if (activeEvent.playingAlt)
{
activeEvent.PrimarySource.volume = 0f;
activeEvent.volDest = activeEvent.audioEvent.volumeCenter;
activeEvent.altVolDest = 0f;
activeEvent.currentFade = audioContainer.crossfadeTime;
waitTime = (tempClip.sound.length / activeEvent.PrimarySource.pitch) - audioContainer.crossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.PrimarySource, activeEvent);
}
// Play on secondary source.
else
{
activeEvent.SecondarySource.volume = 0f;
activeEvent.altVolDest = activeEvent.audioEvent.volumeCenter;
activeEvent.volDest = 0f;
activeEvent.currentFade = audioContainer.crossfadeTime;
waitTime = (tempClip.sound.length / activeEvent.SecondarySource.pitch) - audioContainer.crossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.SecondarySource, activeEvent);
}
activeEvent.playingAlt = !activeEvent.playingAlt;
}
}
/// <summary>
/// Play the current clip in a container, and call the coroutine to constantly choose new audio clips when the current clip ends.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
private void PlayContinuousSequenceContainer(AudioContainer audioContainer, AudioSource emitter, ActiveEvent activeEvent)
{
UAudioClip tempClip = audioContainer.sounds[audioContainer.currentClip];
activeEvent.PrimarySource.volume = 0f;
activeEvent.volDest = activeEvent.audioEvent.volumeCenter;
activeEvent.altVolDest = 0f;
activeEvent.currentFade = audioContainer.crossfadeTime;
float waitTime = (tempClip.sound.length / emitter.pitch) - activeEvent.audioEvent.container.crossfadeTime;
// Ignore clip delay since the container is continuous.
PlayClipAndGetTime(tempClip, emitter, activeEvent);
activeEvent.activeTime = InfiniteLoop;
StartCoroutine(RecordEventInstanceCoroutine(activeEvent));
audioContainer.currentClip++;
if (audioContainer.currentClip >= audioContainer.sounds.Length)
{
audioContainer.currentClip = 0;
}
StartCoroutine(ContinueSequenceContainerCoroutine(audioContainer, activeEvent, waitTime));
}
/// <summary>
/// Coroutine for "continuous" sequence containers that alternates between two sources to crossfade clips for continuous playlist looping.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <param name="waitTime">The time in seconds to wait before switching AudioSources to crossfading.</param>
/// <returns>The coroutine.</returns>
private IEnumerator ContinueSequenceContainerCoroutine(AudioContainer audioContainer, ActiveEvent activeEvent, float waitTime)
{
while (!activeEvent.cancelEvent)
{
yield return new WaitForSeconds(waitTime);
UAudioClip tempClip = audioContainer.sounds[audioContainer.currentClip];
if (tempClip.sound == null)
{
Debug.LogErrorFormat(this, "Sound clip in event \"{0}\" is null!", activeEvent.audioEvent.name);
waitTime = 0;
}
else
{
// Play on primary source.
if (activeEvent.playingAlt)
{
activeEvent.PrimarySource.volume = 0f;
activeEvent.volDest = activeEvent.audioEvent.volumeCenter;
activeEvent.altVolDest = 0f;
activeEvent.currentFade = audioContainer.crossfadeTime;
waitTime = (tempClip.sound.length / activeEvent.PrimarySource.pitch) - audioContainer.crossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.PrimarySource, activeEvent);
}
// Play on secondary source.
else
{
activeEvent.SecondarySource.volume = 0f;
activeEvent.altVolDest = activeEvent.audioEvent.volumeCenter;
activeEvent.volDest = 0f;
activeEvent.currentFade = audioContainer.crossfadeTime;
waitTime = (tempClip.sound.length / activeEvent.SecondarySource.pitch) - audioContainer.crossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.SecondarySource, activeEvent);
}
}
audioContainer.currentClip++;
if (audioContainer.currentClip >= audioContainer.sounds.Length)
{
audioContainer.currentClip = 0;
}
activeEvent.playingAlt = !activeEvent.playingAlt;
}
}
/// <summary>
/// Play a single clip on an AudioSource; if looping forever, return InfiniteLoop for the event time.
/// </summary>
/// <param name="audioClip">The audio clip to play.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <returns>The amount of delay, if any, we are waiting before playing the clip. A looping clip will always return InfiniteLoop.</returns>
private float PlayClipAndGetTime(UAudioClip audioClip, AudioSource emitter, ActiveEvent activeEvent)
{
if (audioClip.delayCenter == 0)
{
emitter.PlayClip(audioClip.sound, audioClip.looping);
if (audioClip.looping)
{
return InfiniteLoop;
}
return 0;
}
else
{
float rndDelay = Random.Range(audioClip.delayCenter - audioClip.delayRandomization, audioClip.delayCenter + audioClip.delayRandomization);
StartCoroutine(PlayClipDelayedCoroutine(audioClip, emitter, rndDelay, activeEvent));
if (audioClip.looping)
{
return InfiniteLoop;
}
return rndDelay;
}
}
/// <summary>
/// Coroutine for playing a clip after a delay (in seconds).
/// </summary>
/// <param name="audioClip">The clip to play.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="delay">The amount of time in seconds to wait before playing audio clip.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <returns>The coroutine.</returns>
private IEnumerator PlayClipDelayedCoroutine(UAudioClip audioClip, AudioSource emitter, float delay, ActiveEvent activeEvent)
{
yield return new WaitForSeconds(delay);
if (this.activeEvents.Contains(activeEvent))
{
emitter.PlayClip(audioClip.sound, audioClip.looping);
}
}
/// <summary>
/// Stop audio sources in an event, and clean up instance references.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
protected void StopEvent(ActiveEvent activeEvent)
{
if (activeEvent.PrimarySource != null)
{
activeEvent.PrimarySource.Stop();
}
if (activeEvent.SecondarySource != null)
{
activeEvent.SecondarySource.Stop();
}
activeEvent.cancelEvent = true;
RemoveEventInstance(activeEvent);
}
/// <summary>
/// Coroutine for fading out an AudioSource, and stopping the event once fade is complete.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <param name="fadeTime">The amount of time, in seconds, to completely fade out the sound.</param>
/// <returns>The coroutine.</returns>
protected IEnumerator StopEventWithFadeCoroutine(ActiveEvent activeEvent, float fadeTime)
{
if (activeEvent.isStoppable)
{
activeEvent.isStoppable = false;
activeEvent.volDest = 0f;
activeEvent.altVolDest = 0f;
activeEvent.currentFade = fadeTime;
yield return new WaitForSeconds(fadeTime);
if (activeEvent.PrimarySource != null)
{
activeEvent.PrimarySource.Stop();
}
if (activeEvent.SecondarySource != null)
{
activeEvent.SecondarySource.Stop();
}
activeEvent.cancelEvent = true;
RemoveEventInstance(activeEvent);
}
}
/// <summary>
/// Keep an event in the "activeEvents" list for the amount of time we think it will be playing, plus the instance buffer.
/// This is mostly done for instance limiting purposes.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <returns>The coroutine.</returns>
private IEnumerator RecordEventInstanceCoroutine(ActiveEvent activeEvent)
{
// Unity has no callback for an audioclip ending, so we have to estimate it ahead of time.
// Changing the pitch during playback will alter actual playback time.
activeEvents.Add(activeEvent);
// Only return active time if sound is not looping/continuous.
if (activeEvent.activeTime > 0)
{
yield return new WaitForSeconds(activeEvent.activeTime);
// Mark this event so it no longer counts against the instance limit.
activeEvent.isActiveTimeComplete = true;
// Since the activeTime estimate may not be enough time to complete the clip (due to pitch changes during playback, or a negative instanceBuffer value, for example)
// wait here until it is finished, so that we don't cut off the end.
if (activeEvent.IsPlaying)
{
yield return null;
}
}
// Otherwise, continue at next frame.
else
{
yield return null;
}
if (activeEvent.activeTime != InfiniteLoop)
{
RemoveEventInstance(activeEvent);
}
}
/// <summary>
/// Remove event from the currently active events.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
private void RemoveEventInstance(ActiveEvent activeEvent)
{
activeEvents.Remove(activeEvent);
activeEvent.Dispose();
}
/// <summary>
/// Return the number of instances matching the name eventName for instance limiting check.
/// </summary>
/// <param name="eventName">The name of the event to check.</param>
/// <returns>The number of instances of that event currently active.</returns>
protected int GetInstances(string eventName)
{
int tempInstances = 0;
for (int i = 0; i < activeEvents.Count; i++)
{
var eventInstance = activeEvents[i];
if (!eventInstance.isActiveTimeComplete && eventInstance.audioEvent.name == eventName)
{
tempInstances++;
}
}
return tempInstances;
}
/// <summary>
/// Calculates the estimated active time for an ActiveEvent playing the given clip.
/// </summary>
/// <param name="audioClip">The clip being played.</param>
/// <param name="activeEvent">The event being played.</param>
/// <param name="additionalDelay">The delay before playing in seconds.</param>
/// <returns>The estimated active time of the event based on looping or clip time. If looping, this will return InfiniteLoop.</returns>
private static float GetActiveTimeEstimate(UAudioClip audioClip, ActiveEvent activeEvent, float additionalDelay)
{
if (audioClip.looping || activeEvent.audioEvent.container.looping || additionalDelay == InfiniteLoop)
{
return InfiniteLoop;
}
else
{
float pitchAdjustedClipLength = activeEvent.PrimarySource.pitch != 0 ? (audioClip.sound.length / activeEvent.PrimarySource.pitch) : 0;
// Restrict non-looping ActiveTime values to be non-negative.
return Mathf.Max(0.0f, pitchAdjustedClipLength + activeEvent.audioEvent.instanceTimeBuffer + additionalDelay);
}
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class SingleSingleOrDefaultTests
{
public static IEnumerable<object[]> SingleSpecificData(int[] counts)
{
Func<int, IEnumerable<int>> positions = x => new[] { 0, x / 2, Math.Max(0, x - 1) }.Distinct();
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), positions)) yield return results;
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), positions)) yield return results;
}
public static IEnumerable<object[]> SingleData(int[] elements, int[] counts)
{
foreach (int element in elements)
{
foreach (object[] results in UnorderedSources.Ranges(element, counts.Cast<int>()))
{
yield return new object[] { results[0], results[1], element };
}
foreach (object[] results in Sources.Ranges(element, counts.Cast<int>()))
{
yield return new object[] { results[0], results[1], element };
}
}
}
//
// Single and SingleOrDefault
//
[Theory]
[MemberData(nameof(SingleData), new int[] { 0, 2, 16, 1024 * 1024 }, new int[] { 1 })]
public static void Single(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(element, query.Single());
Assert.Equal(element, query.Single(x => true));
}
[Theory]
[MemberData(nameof(SingleData), new int[] { 0, 2, 16, 1024 * 1024 }, new int[] { 0, 1 })]
public static void SingleOrDefault(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault());
Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault(x => true));
}
[Theory]
[MemberData(nameof(SingleData), new int[] { 0, 1024 * 1024 }, new int[] { 0 })]
public static void Single_Empty(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<InvalidOperationException>(() => query.Single());
Assert.Throws<InvalidOperationException>(() => query.Single(x => true));
}
[Theory]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 0, 1, 2, 16 })]
public static void Single_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Throws<InvalidOperationException>(() => query.Single(x => !seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void Single_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
Single_NoMatch(labeled, count, element);
}
[Theory]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 0, 1, 2, 16 })]
public static void SingleOrDefault_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(default(int), query.SingleOrDefault(x => !seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void SingleOrDefault_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
SingleOrDefault_NoMatch(labeled, count, element);
}
[Theory]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 2, 16 })]
public static void Single_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<InvalidOperationException>(() => query.Single(x => true));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void Single_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
Single_AllMatch(labeled, count, element);
}
[Theory]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 2, 16 })]
public static void SingleOrDefault_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<InvalidOperationException>(() => query.SingleOrDefault(x => true));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleData), new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void SingleOrDefault_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
SingleOrDefault_AllMatch(labeled, count, element);
}
[Theory]
[MemberData(nameof(SingleSpecificData), (object)(new int[] { 1, 2, 16 }))]
public static void Single_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(element, query.Single(x => seen.Add(x) && x == element));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleSpecificData), (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Single_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
Single_OneMatch(labeled, count, element);
}
[Theory]
[MemberData(nameof(SingleSpecificData), (object)(new int[] { 0, 1, 2, 16 }))]
public static void SingleOrDefault_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(element, query.SingleOrDefault(x => seen.Add(x) && x == element));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleSpecificData), (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void SingleOrDefault_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
SingleOrDefault_OneMatch(labeled, count, element);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void Single_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Single());
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Single(x => true));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).SingleOrDefault());
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).SingleOrDefault(x => true));
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void Single_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Single(x => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.SingleOrDefault(x => { throw new DeliberateTestException(); }));
}
[Fact]
public static void Single_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Single());
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SingleOrDefault());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().Single(null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().SingleOrDefault(null));
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// 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
[assembly: Elmah.Scc("$Id: JsonTextWriter.cs 640 2009-06-01 17:22:02Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Xml;
#endregion
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only
/// way of generating streams or files containing JSON Text according
/// to the grammar rules laid out in
/// <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>.
/// </summary>
/// <remarks>
/// This class supports ELMAH and is not intended to be used directly
/// from your code. It may be modified or removed in the future without
/// notice. It has public accessibility for testing purposes. If you
/// need a general-purpose JSON Text encoder, consult
/// <a href="http://www.json.org/">JSON.org</a> for implementations
/// or use classes available from the Microsoft .NET Framework.
/// </remarks>
public sealed class JsonTextWriter
{
private readonly TextWriter _writer;
private readonly int[] _counters;
private readonly char[] _terminators;
private string _memberName;
public JsonTextWriter(TextWriter writer)
{
Debug.Assert(writer != null);
_writer = writer;
const int levels = 10 + /* root */ 1;
_counters = new int[levels];
_terminators = new char[levels];
}
public int Depth { get; private set; }
private int ItemCount
{
get { return _counters[Depth]; }
set { _counters[Depth] = value; }
}
private char Terminator
{
get { return _terminators[Depth]; }
set { _terminators[Depth] = value; }
}
public JsonTextWriter Object()
{
return StartStructured("{", "}");
}
public JsonTextWriter EndObject()
{
return Pop();
}
public JsonTextWriter Array()
{
return StartStructured("[", "]");
}
public JsonTextWriter EndArray()
{
return Pop();
}
public JsonTextWriter Pop()
{
return EndStructured();
}
public JsonTextWriter Member(string name)
{
if (name == null) throw new ArgumentNullException("name");
if (_memberName != null) throw new InvalidOperationException("Missing member value.");
_memberName = name;
return this;
}
private JsonTextWriter Write(string text)
{
return WriteImpl(text, /* raw */ false);
}
private JsonTextWriter WriteEnquoted(string text)
{
return WriteImpl(text, /* raw */ true);
}
private JsonTextWriter WriteImpl(string text, bool raw)
{
Debug.Assert(raw || !string.IsNullOrEmpty(text));
if (Depth == 0 && (text.Length > 1 || (text[0] != '{' && text[0] != '[')))
throw new InvalidOperationException();
var writer = _writer;
if (ItemCount > 0)
writer.Write(',');
var name = _memberName;
_memberName = null;
if (name != null)
{
writer.Write(' ');
Enquote(name, writer);
writer.Write(':');
}
if (Depth > 0)
writer.Write(' ');
if (raw)
Enquote(text, writer);
else
writer.Write(text);
ItemCount = ItemCount + 1;
return this;
}
public JsonTextWriter Number(int value)
{
return Write(value.ToString(CultureInfo.InvariantCulture));
}
public JsonTextWriter String(string str)
{
return str == null ? Null() : WriteEnquoted(str);
}
public JsonTextWriter Null()
{
return Write("null");
}
public JsonTextWriter Boolean(bool value)
{
return Write(value ? "true" : "false");
}
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public JsonTextWriter Number(DateTime time)
{
var seconds = time.ToUniversalTime().Subtract(Epoch).TotalSeconds;
return Write(seconds.ToString(CultureInfo.InvariantCulture));
}
public JsonTextWriter String(DateTime time)
{
return String(XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc));
}
private JsonTextWriter StartStructured(string start, string end)
{
if (Depth + 1 == _counters.Length)
throw new Exception();
Write(start);
Depth++;
Terminator = end[0];
return this;
}
private JsonTextWriter EndStructured()
{
if (Depth - 1 < 0)
throw new Exception();
_writer.Write(' ');
_writer.Write(Terminator);
ItemCount = 0;
Depth--;
return this;
}
private static void Enquote(string s, TextWriter writer)
{
Debug.Assert(writer != null);
var length = (s ?? string.Empty).Length;
writer.Write('"');
var ch = '\0';
for (var index = 0; index < length; index++)
{
var last = ch;
Debug.Assert(s != null);
ch = s[index];
switch (ch)
{
case '\\':
case '"':
{
writer.Write('\\');
writer.Write(ch);
break;
}
case '/':
{
if (last == '<')
writer.Write('\\');
writer.Write(ch);
break;
}
case '\b': writer.Write("\\b"); break;
case '\t': writer.Write("\\t"); break;
case '\n': writer.Write("\\n"); break;
case '\f': writer.Write("\\f"); break;
case '\r': writer.Write("\\r"); break;
default:
{
if (ch < ' ')
{
writer.Write("\\u");
writer.Write(((int)ch).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
writer.Write(ch);
}
break;
}
}
}
writer.Write('"');
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaModuloNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableInt(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableLong(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableShort(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableULong(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal?
private static void VerifyModuloNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
bool divideByZero;
decimal? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1");
// verify with parameters supplied
Expression<Func<decimal?>> e1 =
Expression.Lambda<Func<decimal?>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 =
Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>(
Expression.Lambda<Func<decimal?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 =
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal?, decimal?>>> e6 =
Expression.Lambda<Func<Func<decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal?)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double?
private static void VerifyModuloNullableDouble(double? a, double? b, bool useInterpreter)
{
double? expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1");
// verify with parameters supplied
Expression<Func<double?>> e1 =
Expression.Lambda<Func<double?>>(
Expression.Invoke(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))
}),
Enumerable.Empty<ParameterExpression>());
Func<double?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double?, double?, Func<double?>>> e2 =
Expression.Lambda<Func<double?, double?, Func<double?>>>(
Expression.Lambda<Func<double?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double?, double?, double?>>> e3 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double?, double?, double?>>> e4 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double?, Func<double?, double?>>> e5 =
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double?, double?>>> e6 =
Expression.Lambda<Func<Func<double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double?)) }),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float?
private static void VerifyModuloNullableFloat(float? a, float? b, bool useInterpreter)
{
float? expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1");
// verify with parameters supplied
Expression<Func<float?>> e1 =
Expression.Lambda<Func<float?>>(
Expression.Invoke(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))
}),
Enumerable.Empty<ParameterExpression>());
Func<float?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float?, float?, Func<float?>>> e2 =
Expression.Lambda<Func<float?, float?, Func<float?>>>(
Expression.Lambda<Func<float?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float?, float?, float?>>> e3 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float?, float?, float?>>> e4 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float?, Func<float?, float?>>> e5 =
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float?, float?>>> e6 =
Expression.Lambda<Func<Func<float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float?)) }),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int?
private static void VerifyModuloNullableInt(int? a, int? b, bool useInterpreter)
{
ResultType outcome;
int? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1");
// verify with parameters supplied
Expression<Func<int?>> e1 =
Expression.Lambda<Func<int?>>(
Expression.Invoke(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))
}),
Enumerable.Empty<ParameterExpression>());
Func<int?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int?, int?, Func<int?>>> e2 =
Expression.Lambda<Func<int?, int?, Func<int?>>>(
Expression.Lambda<Func<int?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int?, int?, int?>>> e3 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int?, int?, int?>>> e4 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int?, Func<int?, int?>>> e5 =
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int?, int?>>> e6 =
Expression.Lambda<Func<Func<int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int?)) }),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long?
private static void VerifyModuloNullableLong(long? a, long? b, bool useInterpreter)
{
ResultType outcome;
long? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1");
// verify with parameters supplied
Expression<Func<long?>> e1 =
Expression.Lambda<Func<long?>>(
Expression.Invoke(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))
}),
Enumerable.Empty<ParameterExpression>());
Func<long?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long?, long?, Func<long?>>> e2 =
Expression.Lambda<Func<long?, long?, Func<long?>>>(
Expression.Lambda<Func<long?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter);
long? f2Result = default(long?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<long?, long?, long?>>> e3 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify as a function generator
Expression<Func<Func<long?, long?, long?>>> e4 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify with currying
Expression<Func<long?, Func<long?, long?>>> e5 =
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with one parameter
Expression<Func<Func<long?, long?>>> e6 =
Expression.Lambda<Func<Func<long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long?)) }),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
}
#endregion
#region Verify short?
private static void VerifyModuloNullableShort(short? a, short? b, bool useInterpreter)
{
bool divideByZero;
short? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (short?)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1");
// verify with parameters supplied
Expression<Func<short?>> e1 =
Expression.Lambda<Func<short?>>(
Expression.Invoke(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))
}),
Enumerable.Empty<ParameterExpression>());
Func<short?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short?, short?, Func<short?>>> e2 =
Expression.Lambda<Func<short?, short?, Func<short?>>>(
Expression.Lambda<Func<short?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short?, short?, short?>>> e3 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short?, short?, short?>>> e4 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short?, Func<short?, short?>>> e5 =
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short?, short?>>> e6 =
Expression.Lambda<Func<Func<short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short?)) }),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint?
private static void VerifyModuloNullableUInt(uint? a, uint? b, bool useInterpreter)
{
bool divideByZero;
uint? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1");
// verify with parameters supplied
Expression<Func<uint?>> e1 =
Expression.Lambda<Func<uint?>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint?, uint?, Func<uint?>>> e2 =
Expression.Lambda<Func<uint?, uint?, Func<uint?>>>(
Expression.Lambda<Func<uint?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint?, uint?, uint?>>> e3 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint?, uint?, uint?>>> e4 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint?, Func<uint?, uint?>>> e5 =
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint?, uint?>>> e6 =
Expression.Lambda<Func<Func<uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint?)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong?
private static void VerifyModuloNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
bool divideByZero;
ulong? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1");
// verify with parameters supplied
Expression<Func<ulong?>> e1 =
Expression.Lambda<Func<ulong?>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 =
Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>(
Expression.Lambda<Func<ulong?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 =
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong?, ulong?>>> e6 =
Expression.Lambda<Func<Func<ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort?
private static void VerifyModuloNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
bool divideByZero;
ushort? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (ushort?)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1");
// verify with parameters supplied
Expression<Func<ushort?>> e1 =
Expression.Lambda<Func<ushort?>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 =
Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>(
Expression.Lambda<Func<ushort?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 =
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort?, ushort?>>> e6 =
Expression.Lambda<Func<Func<ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
public partial class UserDefinedFunctions
{
/// <summary>
/// Formateren van een datum
/// </summary>
/// <param name="Value"></param>
/// <param name="Format"></param>
/// <returns></returns>
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
[return: SqlFacet(MaxSize = 64)]
public static SqlString fnDateTime_Format(SqlDateTime dt, [SqlFacet(MaxSize = 64)] SqlString format, [SqlFacet(MaxSize = 20)] SqlString cultureName)
{
CultureInfo ci;
int lcid;
if (dt.IsNull)
{
return SqlString.Null;
}
if (cultureName.IsNull)
{
ci = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
}
else
{
if (int.TryParse(cultureName.Value, out lcid) == false)
{
ci = new CultureInfo(cultureName.Value);
}
else
{
ci = new CultureInfo(lcid);
}
}
if (format.IsNull)
{
return new SqlString(dt.Value.ToString(ci));
}
else
{
return new SqlString(dt.Value.ToString(format.Value, ci));
}
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_Create(SqlInt32 year, SqlInt32 month, SqlInt32 day)
{
if (day.IsNull || month.IsNull || year.IsNull)
{
return SqlDateTime.Null;
}
try
{
return new SqlDateTime(year.Value, month.Value, day.Value);
}
catch
{
return SqlDateTime.Null;
}
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_Merge(SqlDateTime dt, SqlInt32 time)
{
if (dt.IsNull || time.IsNull)
{
return SqlDateTime.Null;
}
try
{
return new SqlDateTime(dt.Value.Date.Add(new TimeSpan(time.Value / 100, time.Value % 100, 0)));
}
catch (Exception)
{
return SqlDateTime.Null;
}
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_FirstOfMonth(SqlInt32 year, SqlInt32 month)
{
return UserDefinedFunctions.fnDateTime_Create(year.Value, month.Value, 1);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_LastOfMonth(SqlInt32 year, SqlInt32 month)
{
return UserDefinedFunctions.fnDateTime_Create(year.Value, month.Value, DateTime.DaysInMonth(year.Value, month.Value));
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_FirstOfYear(SqlInt32 year)
{
return UserDefinedFunctions.fnDateTime_Create(year.Value, 1, 1);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_LastOfYear(SqlInt32 year)
{
return UserDefinedFunctions.fnDateTime_Create(year.Value, 12, 31);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_StripTime(SqlDateTime dt)
{
return dt.IsNull ? SqlDateTime.Null : new SqlDateTime(dt.Value.Date);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_StripHour(SqlDateTime dt)
{
return dt.IsNull ? SqlDateTime.Null : new SqlDateTime(dt.Value.Year, dt.Value.Month, dt.Value.Day, dt.Value.Hour, 0, 0);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_StripMinute(SqlDateTime dt)
{
return dt.IsNull ? SqlDateTime.Null : new SqlDateTime(dt.Value.Year, dt.Value.Month, dt.Value.Day, dt.Value.Hour, dt.Value.Minute, 0);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_Today()
{
return new SqlDateTime(DateTime.Today);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_Yesterday()
{
return new SqlDateTime(DateTime.Today.AddDays(-1));
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_Tomorrow()
{
return new SqlDateTime(DateTime.Today.AddDays(1));
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlInt32 fnDateTime_DaysInMonth(SqlInt32 year, SqlInt32 month)
{
if (month.IsNull || year.IsNull)
{
return SqlInt32.Null;
}
try
{
return new SqlInt32(DateTime.DaysInMonth(year.Value, month.Value));
}
catch
{
return SqlInt32.Null;
}
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_MaxDate(SqlDateTime dt1, SqlDateTime dt2)
{
if (dt1.IsNull || dt2.IsNull)
{
return SqlDateTime.Null;
}
return new SqlDateTime(dt1.Value < dt2.Value ? dt2.Value : dt1.Value);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_MinDate(SqlDateTime dt1, SqlDateTime dt2)
{
if (dt1.IsNull || dt2.IsNull)
{
return SqlDateTime.Null;
}
return new SqlDateTime(dt1.Value > dt2.Value ? dt2.Value : dt1.Value);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlDateTime fnDateTime_AddWorkingDays(SqlDateTime dt, SqlInt32 nrWorkingDays)
{
if (dt.IsNull || nrWorkingDays.IsNull || nrWorkingDays.Value <= 0)
{
return SqlDateTime.Null;
}
DateTime aDateTime = dt.Value;
Int32 NrWorkingDays = nrWorkingDays.Value;
while (NrWorkingDays > 0)
{
aDateTime = aDateTime.AddDays(1);
while (aDateTime.DayOfWeek == DayOfWeek.Saturday || aDateTime.DayOfWeek == DayOfWeek.Sunday)
{
aDateTime = aDateTime.AddDays(1);
}
NrWorkingDays--;
}
return new SqlDateTime(aDateTime);
}
[Microsoft.SqlServer.Server.SqlFunction(
DataAccess = DataAccessKind.None,
IsDeterministic = true)]
public static SqlInt32 fnDateTime_WorkingDaysBetween(SqlDateTime startDate, SqlDateTime endDate)
{
if (startDate.IsNull || endDate.IsNull)
{
return SqlInt32.Null;
}
DateTime StartDate = startDate.Value.Date;
DateTime EndDate = endDate.Value.Date;
if (StartDate == EndDate)
{
return new SqlInt32(0);
}
else if (StartDate > EndDate)
{
return SqlInt32.Null;
}
Int32 Result = 0;
StartDate = StartDate.AddDays(1);
while (StartDate < EndDate)
{
while (StartDate.DayOfWeek == DayOfWeek.Saturday || StartDate.DayOfWeek == DayOfWeek.Sunday)
{
StartDate = StartDate.AddDays(1);
}
if (StartDate < EndDate)
{
StartDate = StartDate.AddDays(1);
Result++;
}
}
return new SqlInt32(Result);
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.Modules;
namespace OrchardCore.ContentManagement.Handlers
{
/// <summary>
/// This component coordinates how parts are affecting content items.
/// </summary>
public class ContentPartHandlerCoordinator : ContentHandlerBase
{
private readonly IContentPartHandlerResolver _contentPartHandlerResolver;
private readonly ITypeActivatorFactory<ContentPart> _contentPartFactory;
private readonly IEnumerable<IContentPartHandler> _partHandlers;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ITypeActivatorFactory<ContentField> _contentFieldFactory;
private readonly ILogger _logger;
public ContentPartHandlerCoordinator(
IContentPartHandlerResolver contentPartHandlerResolver,
ITypeActivatorFactory<ContentPart> contentPartFactory,
IEnumerable<IContentPartHandler> partHandlers,
ITypeActivatorFactory<ContentField> contentFieldFactory,
IContentDefinitionManager contentDefinitionManager,
ILogger<ContentPartHandlerCoordinator> logger)
{
_contentPartHandlerResolver = contentPartHandlerResolver;
_contentPartFactory = contentPartFactory;
_contentFieldFactory = contentFieldFactory;
_partHandlers = partHandlers;
_contentDefinitionManager = contentDefinitionManager;
foreach (var element in partHandlers.Select(x => x.GetType()))
{
logger.LogWarning("The content part handler '{ContentPartHandler}' should not be registered in DI. Use AddHandler<T> instead.", element);
}
_logger = logger;
}
public override async Task ActivatingAsync(ActivatingContentContext context)
{
// This method is called on New()
// Adds all the parts to a content item based on the content type definition.
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
// We create the part from it's known type or from a generic one
var part = _contentPartFactory.GetTypeActivator(partName).CreateInstance();
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ActivatingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ActivatingAsync(context, part), context, part, _logger);
context.Builder.Weld(typePartDefinition.Name, part);
}
}
public override async Task ActivatedAsync(ActivatedContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, partName) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ActivatedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ActivatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task CreatingAsync(CreateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.CreatingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.CreatingAsync(context, part), context, part, _logger);
}
}
}
public override async Task CreatedAsync(CreateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.CreatedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.CreatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task ImportingAsync(ImportContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ImportingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iteratate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ImportingAsync(context, part), context, part, _logger);
}
}
}
public override async Task ImportedAsync(ImportContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ImportedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iteratate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ImportedAsync(context, part), context, part, _logger);
}
}
}
public override async Task InitializingAsync(InitializingContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.InitializingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.InitializingAsync(context, part), context, part, _logger);
}
}
}
public override async Task InitializedAsync(InitializingContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.InitializedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.InitializedAsync(context, part), context, part, _logger);
}
}
}
public override async Task LoadingAsync(LoadContentContext context)
{
// This method is called on Get()
// Adds all the missing parts to a content item based on the content type definition.
// A part is missing if the content type is changed and an old content item is loaded,
// like edited.
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
{
return;
}
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
// If no existing part was not found in the content item, create a new one
if (part == null)
{
part = activator.CreateInstance();
context.ContentItem.Weld(typePartDefinition.Name, part);
}
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.LoadingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.LoadingAsync(context, part), context, part, _logger);
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.Name;
if (!part.Has(fieldName))
{
var fieldActivator = _contentFieldFactory.GetTypeActivator(partFieldDefinition.FieldDefinition.Name);
context.ContentItem.Get<ContentPart>(typePartDefinition.Name).Weld(fieldName, fieldActivator.CreateInstance());
}
}
}
}
public override async Task LoadedAsync(LoadContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.LoadedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.LoadedAsync(context, part), context, part, _logger);
}
}
}
public override async Task ValidatingAsync(ValidateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ValidatingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iteratate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ValidatingAsync(context, part), context, part, _logger);
}
}
}
public override async Task ValidatedAsync(ValidateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ValidatedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iteratate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ValidatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task PublishingAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.PublishingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.PublishingAsync(context, part), context, part, _logger);
}
}
}
public override async Task PublishedAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.PublishedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.PublishedAsync(context, part), context, part, _logger);
}
}
}
public override async Task RemovingAsync(RemoveContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.RemovingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.RemovingAsync(context, part), context, part, _logger);
}
}
}
public override async Task RemovedAsync(RemoveContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.RemovedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.RemovedAsync(context, part), context, part, _logger);
}
}
}
public override async Task UnpublishingAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UnpublishingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.UnpublishingAsync(context, part), context, part, _logger);
}
}
}
public override async Task UnpublishedAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UnpublishedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.UnpublishedAsync(context, part), context, part, _logger);
}
}
}
public override async Task UpdatingAsync(UpdateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UpdatingAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.UpdatingAsync(context, part), context, part, _logger);
}
}
}
public override async Task UpdatedAsync(UpdateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UpdatedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.UpdatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task VersioningAsync(VersionContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var buildingPart = context.BuildingContentItem.Get(activator.Type, partName) as ContentPart;
var existingPart = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (buildingPart != null && existingPart != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, existingPart, buildingPart) => handler.VersioningAsync(context, existingPart, buildingPart), context, existingPart, buildingPart, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, existingPart, buildingPart) => handler.VersioningAsync(context, existingPart, buildingPart), context, existingPart, buildingPart, _logger);
}
}
}
public override async Task VersionedAsync(VersionContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var buildingPart = (ContentPart)context.BuildingContentItem.Get(activator.Type, partName);
var existingPart = (ContentPart)context.ContentItem.Get(activator.Type, typePartDefinition.Name);
if (buildingPart != null && existingPart != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, existingPart, buildingPart) => handler.VersionedAsync(context, existingPart, buildingPart), context, existingPart, buildingPart, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, existingPart, buildingPart) => handler.VersionedAsync(context, existingPart, buildingPart), context, existingPart, buildingPart, _logger);
}
}
}
public override async Task GetContentItemAspectAsync(ContentItemAspectContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.GetContentItemAspectAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.GetContentItemAspectAsync(context, part), context, part, _logger);
}
}
}
public override async Task ClonedAsync(CloneContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ClonedAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.
await _partHandlers.InvokeAsync((handler, context, part) => handler.ClonedAsync(context, part), context, part, _logger);
}
}
}
public override async Task CloningAsync(CloneContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.CloningAsync(context, part), context, part, _logger);
// TODO: This can be removed in a future release as the recommended way is to use ContentOptions.
// Iterate existing handler registrations as multiple handlers maybe not be registered with ContentOptions.=
await _partHandlers.InvokeAsync((handler, context, part) => handler.CloningAsync(context, part), context, part, _logger);
}
}
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
namespace Bam.Core
{
/// <summary>
/// Generic wrapper around a List, with set functionality.
/// </summary>
public class Array<T> :
System.Collections.Generic.ICollection<T>
{
/// <summary>
/// The underlying list storage, initialized to an empty list.
/// </summary>
protected System.Collections.Generic.List<T> list = new System.Collections.Generic.List<T>();
private void
AddToEnd(
T item)
{
if (null == item)
{
throw new Exception("Cannot add a null item to the end of an array");
}
this.list.Add(item);
}
private void
AddMultipleToEnd(
System.Collections.Generic.IEnumerable<T> items)
{
foreach (var item in items)
{
this.AddToEnd(item);
}
}
/// <summary>
/// Default constructor. The list is empty.
/// </summary>
public
Array()
{}
/// <summary>
/// Create a list from an array of objects.
/// </summary>
/// <param name="itemsToAdd">Array of objects to add to the list.</param>
public
Array(
params T[] itemsToAdd) => this.AddMultipleToEnd(itemsToAdd);
/// <summary>
/// Create a list from an enumeration of objects.
/// </summary>
/// <param name="items">IEnumerable of objects to add to the list.</param>
public
Array(
System.Collections.Generic.IEnumerable<T> items) => this.AddMultipleToEnd(items);
/// <summary>
/// Add a single object to the end of an existing list.
/// Virtual as can be overridden in subclasses.
/// </summary>
/// <param name="item">Object to be added</param>
public virtual void
Add(
T item) => this.AddToEnd(item);
/// <summary>
/// Add a single object to the end of an existing list, if that list does not already contain it.
/// </summary>
/// <param name="item">Object to be added uniquely.</param>
public void
AddUnique(
T item)
{
if (this.Contains(item))
{
return;
}
this.AddToEnd(item);
}
/// <summary>
/// Add an array of objects to the end of an existing list.
/// </summary>
/// <param name="itemsToAdd">Array of objects to add.</param>
public void
AddRange(
T[] itemsToAdd) => this.AddMultipleToEnd(itemsToAdd);
/// <summary>
/// Append an existing Array to the end of an existing list.
/// </summary>
/// <param name="array">Array of objects to add.</param>
public void
AddRange(
Array<T> array)
{
if (this == array)
{
throw new Exception("Cannot add an array to itself");
}
foreach (var item in array)
{
this.AddToEnd(item);
}
}
/// <summary>
/// Append an enumeration of objects to the end of an existing list.
/// </summary>
/// <param name="items">An enumeration of objects to add.</param>
public void
AddRange(
System.Collections.Generic.IEnumerable<T> items) => this.AddMultipleToEnd(items);
/// <summary>
/// Appends the contents of an existing Array to the end of an existing list, if they are not already in that list.
/// </summary>
/// <param name="array">Array of objects to add uniquely.</param>
public void
AddRangeUnique(
Array<T> array)
{
if (this == array)
{
throw new Exception("Cannot add an array to itself");
}
foreach (var item in array)
{
if (this.Contains(item))
{
continue;
}
this.AddToEnd(item);
}
}
/// <summary>
/// Appends an enumeration of objects to the end of an existing list, if they are not already in that list.
/// </summary>
/// <param name="list">Enumeration of objects to add uniquely.</param>
public void
AddRangeUnique(
System.Collections.Generic.IEnumerable<T> list)
{
foreach (var item in list)
{
if (this.Contains(item))
{
continue;
}
this.AddToEnd(item);
}
}
/// <summary>
/// Insert an object into the specified position in the existing list.
/// Any objects in the list at, or subsequent, to this index are moved to accomodate the new object.
/// </summary>
/// <param name="index">Zero-based index to insert the new object.</param>
/// <param name="item">Object to insert into the list.</param>
public void
Insert(
int index,
T item)
{
if (null == item)
{
throw new Exception($"Cannot insert null at index {index}");
}
this.list.Insert(index, item);
}
/// <summary>
/// Remove all objects from the list.
/// </summary>
public void
Clear() => this.list.Clear();
/// <summary>
/// Determine whether an item is stored in the list.
/// Virtual so that sub classes can override the behaviour.
/// </summary>
/// <param name="item">Object to check whether it is contained in the list.</param>
/// <returns><c>true</c> if the object is in the list. <c>false</c> otherwise.</returns>
public virtual bool
Contains(
T item) => this.list.Contains(item);
/// <summary>
/// Copy a number of elements, starting from the index, to the specified array.
/// </summary>
/// <param name="array">Array to receive the sub-section of the list.</param>
/// <param name="arrayIndex">Index of the list to being copying.</param>
public void
CopyTo(
T[] array,
int arrayIndex) => this.list.CopyTo(array, arrayIndex);
/// <summary>
/// Determine the number of elements in the list.
/// </summary>
/// <value>An integer count of the list size.</value>
public int Count => this.list.Count;
/// <summary>
/// Is the list readonly? Required by the ICollection interface.
/// </summary>
/// <value>Always <c>false</c>.</value>
public bool IsReadOnly => false;
/// <summary>
/// Remove the specified object from the list if it is contained within it.
/// </summary>
/// <param name="item">Object to remove from the list.</param>
/// <returns><c>true</c> if the object was removed. <c>false</c> if the object was not removed, or not found.</returns>
public bool
Remove(
T item) => this.list.Remove(item);
/// <summary>
/// Removes all objects from the list if they are contained within it.
/// </summary>
/// <returns><c>true</c>, if all objects were removed, <c>false</c> if not all objects were removed, or not found.</returns>
/// <param name="items">Array of objects to remove.</param>
public bool
RemoveAll(
Array<T> items)
{
var success = true;
foreach (var item in items)
{
success &= this.list.Remove(item);
}
return success;
}
/// <summary>
/// Part of the IEnumerable interface.
/// </summary>
/// <returns>The enumerator.</returns>
public System.Collections.Generic.IEnumerator<T>
GetEnumerator() => this.list.GetEnumerator();
/// <summary>
/// Part of the IEnumerable interface.
/// </summary>
/// <returns>The enumerator.</returns>
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator() => this.list.GetEnumerator();
/// <summary>
/// Gets the object specified by the given index.
/// </summary>
/// <param name="index">Index of the object in the list desired.</param>
/// <value>Object at the given index.</value>
public T this[int index] => list[index];
/// <summary>
/// Convert the list to an array.
/// </summary>
/// <returns>An array containing the elements of the list.</returns>
public T[]
ToArray() => this.list.ToArray();
/// <summary>
/// String conversion of the array.
/// </summary>
/// <returns>A <see cref="string"/> of all items in the array separated by a space.</returns>
public override string
ToString() => this.ToString(" ");
/// <summary>
/// String conversion of the array, with a custom separator.
/// Virtual to allow sub-classes to override the behaviour.
/// </summary>
/// <returns>A <see cref="string"/> of all items in the array separated by the given separator string.</returns>
/// <param name="separator">The separator between each element of the array in the returned string.</param>
public virtual string
ToString(
string separator)
{
var builder = new System.Text.StringBuilder();
foreach (var item in this.list)
{
if (null == item)
{
throw new Exception("Item in array was null");
}
builder.Append($"{item.ToString()}{separator}");
}
// remove the trailing separator
var output = builder.ToString().TrimEnd(separator.ToCharArray());
return output;
}
/// <summary>
/// String conversion of the array, with a custom single character separator.
/// Virtual to allow sub-classes to override the behaviour.
/// </summary>
/// <returns>A <see cref="string"/> of all items in the array separated by the given character.</returns>
/// <param name="separator">The single character separator between each element of the array in the returned string.</param>
public virtual string
ToString(
char separator)
{
var builder = new System.Text.StringBuilder();
foreach (var item in this.list)
{
builder.Append($"{item.ToString()}{separator}");
}
// remove the trailing separator
var output = builder.ToString().TrimEnd(separator);
return output;
}
/// <summary>
/// Sorts the list, in place, using the default comparer for the type.
/// </summary>
public void
Sort() => this.list.Sort();
/// <summary>
/// Combine the elements of two lists uniquely.
/// </summary>
/// <param name="other">The second list to union with.</param>
/// <returns>The array containing the combination of all elements of the arrays.</returns>
public Array<T>
Union(
Array<T> other)
{
var union = new Array<T>();
union.AddRangeUnique(this);
union.AddRangeUnique(other);
return union;
}
/// <summary>
/// Find all elements that exist in two lists.
/// </summary>
/// <param name="other">The second list to intersect with.</param>
/// <returns>The array containing just those elements in both arrays.</returns>
public Array<T>
Intersect(
Array<T> other)
{
var intersect = new Array<T>();
foreach (var item in this.list)
{
if (!other.Contains(item))
{
continue;
}
intersect.AddToEnd(item);
}
return intersect;
}
/// <summary>
/// Find all elements in this but not in <paramref name="other"/>
/// </summary>
/// <param name="other">The other list</param>
/// <returns>The array containing the complement of the two arrays.</returns>
public Array<T>
Complement(
Array<T> other)
{
var complement = new Array<T>();
foreach (var item in this.list)
{
if (other.Contains(item))
{
continue;
}
complement.AddToEnd(item);
}
return complement;
}
/// <summary>
/// Do the two arrays contain exactly the same elements?
/// </summary>
/// <param name="obj">The other array to compare against</param>
/// <returns><c>true</c> if the two arrays contain the same elements. <c>false</c> otherwise.</returns>
public override bool
Equals(
object obj)
{
var other = obj as Array<T>;
if (this.list.Count != other.list.Count)
{
return false;
}
foreach (var item in this.list)
{
if (!other.Contains(item))
{
return false;
}
}
return true;
}
/// <summary>
/// Return the hash code of the list within.
/// Required by overriding Equals.
/// </summary>
/// <returns>Hash code of the internal list.</returns>
public override int
GetHashCode() => this.list.GetHashCode();
/// <summary>
/// Extracts part of the existing array into another.
/// </summary>
/// <returns>The sub-array</returns>
/// <param name="firstIndex">First index of the existing array to start at.</param>
/// <param name="count">Number of elements to extract.</param>
public Array<T>
SubArray(
int firstIndex,
int count)
{
var newArray = new Array<T>();
int lastIndex = firstIndex + count;
for (int index = firstIndex; index < lastIndex; ++index)
{
newArray.Add(this[index]);
}
return newArray;
}
/// <summary>
/// Convert the internal list into a ReadOnlyCollection/>
/// </summary>
/// <returns>A read-only version of the internal list.</returns>
public System.Collections.ObjectModel.ReadOnlyCollection<T>
ToReadOnlyCollection() => new System.Collections.ObjectModel.ReadOnlyCollection<T>(this.list);
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Microsoft.PythonTools.Debugger.DebugEngine {
// This class implements IDebugThread2 which represents a thread running in a program.
class AD7Thread : IDisposable, IDebugThread2, IDebugThread100 {
private readonly AD7Engine _engine;
private readonly PythonThread _debuggedThread;
private readonly uint _vsTid;
public AD7Thread(AD7Engine engine, PythonThread debuggedThread) {
_engine = engine;
_debuggedThread = debuggedThread;
_vsTid = engine.RegisterThreadId(debuggedThread.Id);
}
public void Dispose() {
_engine.UnregisterThreadId(_vsTid);
}
private string GetCurrentLocation(bool fIncludeModuleName) {
if (_debuggedThread.Frames != null && _debuggedThread.Frames.Count > 0) {
return _debuggedThread.Frames[0].FunctionName;
}
return "<unknown location, not in Python code>";
}
internal PythonThread GetDebuggedThread() {
return _debuggedThread;
}
private string Name {
get {
string result = _debuggedThread.Name;
// If our fake ID is actually different from the real ID, prepend real ID info to thread name so that user can see it somewhere.
if (_vsTid != _debuggedThread.Id) {
result = "[" + _debuggedThread.Id + "] " + result;
}
return result;
}
}
#region IDebugThread2 Members
// Determines whether the next statement can be set to the given stack frame and code context.
// We need to try the step to verify it accurately so we allow say ok here.
int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) {
return VSConstants.S_OK;
}
// Retrieves a list of the stack frames for this thread.
// We currently call into the process and get the frames. We might want to cache the frame info.
int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject) {
var stackFrames = _debuggedThread.Frames;
if (stackFrames == null) {
enumObject = null;
return VSConstants.E_FAIL;
}
int numStackFrames = stackFrames.Count;
FRAMEINFO[] frameInfoArray;
frameInfoArray = new FRAMEINFO[numStackFrames];
for (int i = 0; i < numStackFrames; i++) {
AD7StackFrame frame = new AD7StackFrame(_engine, this, stackFrames[i]);
frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i]);
}
enumObject = new AD7FrameInfoEnum(frameInfoArray);
return VSConstants.S_OK;
}
// Get the name of the thread.
int IDebugThread2.GetName(out string threadName) {
threadName = Name;
return VSConstants.S_OK;
}
// Return the program that this thread belongs to.
int IDebugThread2.GetProgram(out IDebugProgram2 program) {
program = _engine;
return VSConstants.S_OK;
}
// Gets the system thread identifier.
int IDebugThread2.GetThreadId(out uint threadId) {
threadId = _vsTid;
return VSConstants.S_OK;
}
// Gets properties that describe a thread.
int IDebugThread2.GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] propertiesArray) {
THREADPROPERTIES props = new THREADPROPERTIES();
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0) {
props.dwThreadId = _vsTid;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0) {
// sample debug engine doesn't support suspending threads
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0) {
props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0) {
props.bstrPriority = "Normal";
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0) {
props.bstrName = Name;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0) {
props.bstrLocation = GetCurrentLocation(true);
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION;
}
propertiesArray[0] = props;
return VSConstants.S_OK;
}
// Resume a thread.
// This is called when the user chooses "Unfreeze" from the threads window when a thread has previously been frozen.
int IDebugThread2.Resume(out uint suspendCount) {
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
internal const int E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = unchecked((int)0x80040105);
// Sets the next statement to the given stack frame and code context.
int IDebugThread2.SetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) {
var frame = (AD7StackFrame)stackFrame;
var context = (AD7MemoryAddress)codeContext;
if (frame.StackFrame.SetLineNumber((int)context.LineNumber + 1)) {
return VSConstants.S_OK;
} else if (frame.StackFrame.Thread.Process.StoppedForException) {
return E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION;
}
return VSConstants.E_FAIL;
}
// suspend a thread.
// This is called when the user chooses "Freeze" from the threads window
int IDebugThread2.Suspend(out uint suspendCount) {
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IDebugThread100 Members
int IDebugThread100.SetThreadDisplayName(string name) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadDisplayName(out string name) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM, which calls GetThreadProperties100()
name = "";
return VSConstants.E_NOTIMPL;
}
// Returns whether this thread can be used to do function/property evaluation.
int IDebugThread100.CanDoFuncEval() {
return VSConstants.S_FALSE;
}
int IDebugThread100.SetFlags(uint flags) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetFlags(out uint flags) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
flags = 0;
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadProperties100(uint dwFields, THREADPROPERTIES100[] props) {
int hRes = VSConstants.S_OK;
// Invoke GetThreadProperties to get the VS7/8/9 properties
THREADPROPERTIES[] props90 = new THREADPROPERTIES[1];
enum_THREADPROPERTY_FIELDS dwFields90 = (enum_THREADPROPERTY_FIELDS)(dwFields & 0x3f);
hRes = ((IDebugThread2)this).GetThreadProperties(dwFields90, props90);
props[0].bstrLocation = props90[0].bstrLocation;
props[0].bstrName = props90[0].bstrName;
props[0].bstrPriority = props90[0].bstrPriority;
props[0].dwFields = (uint)props90[0].dwFields;
props[0].dwSuspendCount = props90[0].dwSuspendCount;
props[0].dwThreadId = props90[0].dwThreadId;
props[0].dwThreadState = props90[0].dwThreadState;
// Populate the new fields
if (hRes == VSConstants.S_OK && dwFields != (uint)dwFields90) {
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME) != 0) {
// Thread display name is being requested
props[0].bstrDisplayName = Name;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME;
// Give this display name a higher priority than the default (0)
// so that it will actually be displayed
props[0].DisplayNamePriority = 10;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME_PRIORITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY) != 0) {
// Thread category is being requested
if (_debuggedThread.IsWorkerThread) {
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Worker;
} else {
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Main;
}
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID) != 0) {
// Thread category is being requested
props[0].dwThreadId = _vsTid;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY) != 0) {
// Thread cpu affinity is being requested
props[0].AffinityMask = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID) != 0) {
// Thread display name is being requested
props[0].priorityId = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID;
}
}
return hRes;
}
enum enum_THREADCATEGORY {
THREADCATEGORY_Worker = 0,
THREADCATEGORY_UI = (THREADCATEGORY_Worker + 1),
THREADCATEGORY_Main = (THREADCATEGORY_UI + 1),
THREADCATEGORY_RPC = (THREADCATEGORY_Main + 1),
THREADCATEGORY_Unknown = (THREADCATEGORY_RPC + 1)
}
#endregion
#region Uncalled interface methods
// These methods are not currently called by the Visual Studio debugger, so they don't need to be implemented
int IDebugThread2.GetLogicalThread(IDebugStackFrame2 stackFrame, out IDebugLogicalThread2 logicalThread) {
Debug.Fail("This function is not called by the debugger");
logicalThread = null;
return VSConstants.E_NOTIMPL;
}
int IDebugThread2.SetThreadName(string name) {
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Generic hash table implementation
**
** #DictionaryVersusHashtableThreadSafety
** Hashtable has multiple reader/single writer (MR/SW) thread safety built into
** certain methods and properties, whereas Dictionary doesn't. If you're
** converting framework code that formerly used Hashtable to Dictionary, it's
** important to consider whether callers may have taken a dependence on MR/SW
** thread safety. If a reader writer lock is available, then that may be used
** with a Dictionary to get the same thread safety guarantee.
**
** Reader writer locks don't exist in silverlight, so we do the following as a
** result of removing non-generic collections from silverlight:
** 1. If the Hashtable was fully synchronized, then we replace it with a
** Dictionary with full locks around reads/writes (same thread safety
** guarantee).
** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior,
** so we do one of the following on a case-by-case basis:
** a. If the race condition can be addressed by rearranging the code and using a temp
** variable (for example, it's only populated immediately after created)
** then we address the race condition this way and use Dictionary.
** b. If there's concern about degrading performance with the increased
** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at
** least use Hashtable in the desktop build, but Dictionary with full
** locks in silverlight builds. Note that this is heavier locking than
** MR/SW, but this is the only option without rewriting (or adding back)
** the reader writer lock.
** c. If there's no performance concern (e.g. debug-only code) we
** consistently replace Hashtable with Dictionary plus full locks to
** reduce complexity.
** d. Most of serialization is dead code in silverlight. Instead of updating
** those Hashtable occurences in serialization, we carved out references
** to serialization such that this code doesn't need to build in
** silverlight.
===========================================================*/
namespace System.Collections.Generic {
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Security.Permissions;
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback {
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
private int version;
private int freeList;
private int freeCount;
private IEqualityComparer<TKey> comparer;
private KeyCollection keys;
private ValueCollection values;
private Object _syncRoot;
// constants for serialization
private const String VersionName = "Version";
private const String HashSizeName = "HashSize"; // Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs";
private const String ComparerName = "Comparer";
public Dictionary(): this(0, null) {}
public Dictionary(int capacity): this(capacity, null) {}
public Dictionary(IEqualityComparer<TKey> comparer): this(0, comparer) {}
public Dictionary(int capacity, IEqualityComparer<TKey> comparer) {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
#if FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default)
{
this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default;
}
#endif // FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
}
public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {}
public Dictionary(IDictionary<TKey,TValue> dictionary, IEqualityComparer<TKey> comparer):
this(dictionary != null? dictionary.Count: 0, comparer) {
if( dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey,TValue>)) {
Dictionary<TKey,TValue> d = (Dictionary<TKey,TValue>)dictionary;
int count = d.count;
Entry[] entries = d.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey,TValue> pair in dictionary) {
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context) {
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
//we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer {
get {
return comparer;
}
}
public int Count {
get { return count - freeCount; }
}
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys {
get {
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys {
get {
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
if (values == null) values = new ValueCollection(this);
return values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values {
get {
if (values == null) values = new ValueCollection(this);
return values;
}
}
public TValue this[TKey key] {
get {
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set {
Insert(key, value, false);
}
}
public void Add(TKey key, TValue value) {
Insert(key, value, true);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) {
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) {
int i = FindEntry(keyValuePair.Key);
if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) {
int i = FindEntry(keyValuePair.Key);
if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear() {
if (count > 0) {
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
count = 0;
freeCount = 0;
version++;
}
}
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
public bool ContainsValue(TValue value) {
if (value == null) {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
else {
EqualityComparer<TValue> c = EqualityComparer<TValue>.Default;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true;
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length ) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
array[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, version);
#if FEATURE_RANDOMIZED_STRING_HASHING
info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>));
#else
info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>));
#endif
info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array.
if( buckets != null) {
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
private void Initialize(int capacity) {
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[size];
freeList = -1;
}
private void Insert(TKey key, TValue value, bool add) {
if( key == null ) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets == null) Initialize(0);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int targetBucket = hashCode % buckets.Length;
#if FEATURE_RANDOMIZED_STRING_HASHING
int collisionCount = 0;
#endif
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (add) {
#if FEATURE_CORECLR
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
#else
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
#endif
}
entries[i].value = value;
version++;
return;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
collisionCount++;
#endif
}
int index;
if (freeCount > 0) {
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else {
if (count == entries.Length)
{
Resize();
targetBucket = hashCode % buckets.Length;
}
index = count;
count++;
}
entries[index].hashCode = hashCode;
entries[index].next = buckets[targetBucket];
entries[index].key = key;
entries[index].value = value;
buckets[targetBucket] = index;
version++;
#if FEATURE_RANDOMIZED_STRING_HASHING
#if FEATURE_CORECLR
// In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// in this case will be EqualityComparer<string>.Default.
// Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will
// be using randomized string hashing
if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
{
comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
#else
if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
{
comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
Resize(entries.Length, true);
}
#endif // FEATURE_CORECLR
#endif
}
public virtual void OnDeserialization(Object sender) {
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
if (siInfo==null) {
// It might be necessary to call OnDeserialization from a container if the container object also implements
// OnDeserialization. However, remoting will call OnDeserialization again.
// We can return immediately if this function is called twice.
// Note we set remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if( hashsize != 0) {
buckets = new int[hashsize];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[hashsize];
freeList = -1;
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array==null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i=0; i<array.Length; i++) {
if ( array[i].Key == null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Insert(array[i].Key, array[i].Value, true);
}
}
else {
buckets = null;
}
version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize() {
Resize(HashHelpers.ExpandPrime(count), false);
}
private void Resize(int newSize, bool forceNewHashCodes) {
Contract.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
if(forceNewHashCodes) {
for (int i = 0; i < count; i++) {
if(newEntries[i].hashCode != -1) {
newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++) {
if (newEntries[i].hashCode >= 0) {
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
}
}
buckets = newBuckets;
entries = newEntries;
}
public bool Remove(TKey key) {
if(key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (last < 0) {
buckets[bucket] = entries[i].next;
}
else {
entries[last].next = entries[i].next;
}
entries[i].hashCode = -1;
entries[i].next = freeList;
entries[i].key = default(TKey);
entries[i].value = default(TValue);
freeList = i;
freeCount++;
version++;
return true;
}
}
}
return false;
}
public bool TryGetValue(TKey key, out TValue value) {
int i = FindEntry(key);
if (i >= 0) {
value = entries[i].value;
return true;
}
value = default(TValue);
return false;
}
// This is a convenience method for the internal callers that were converted from using Hashtable.
// Many were combining key doesn't exist and key exists but null value (for non-value types) checks.
// This allows them to continue getting that behavior with minimal code delta. This is basically
// TryGetValue without the out param
internal TValue GetValueOrDefault(TKey key) {
int i = FindEntry(key);
if (i >= 0) {
return entries[i].value;
}
return default(TValue);
}
bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly {
get { return false; }
}
void ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey,TValue>[] pairs = array as KeyValuePair<TKey,TValue>[];
if (pairs != null) {
CopyTo(pairs, index);
}
else if( array is DictionaryEntry[]) {
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try {
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
objects[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
}
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool IDictionary.IsFixedSize {
get { return false; }
}
bool IDictionary.IsReadOnly {
get { return false; }
}
ICollection IDictionary.Keys {
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values {
get { return (ICollection)Values; }
}
object IDictionary.this[object key] {
get {
if( IsCompatibleKey(key)) {
int i = FindEntry((TKey)key);
if (i >= 0) {
return entries[i].value;
}
}
return null;
}
set {
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try {
TKey tempKey = (TKey)key;
try {
this[tempKey] = (TValue)value;
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value) {
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try {
TKey tempKey = (TKey)key;
try {
Add(tempKey, (TValue)value);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key) {
if(IsCompatibleKey(key)) {
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key) {
if(IsCompatibleKey(key)) {
Remove((TKey)key);
}
}
[Serializable]
public struct Enumerator: IEnumerator<KeyValuePair<TKey,TValue>>,
IDictionaryEnumerator
{
private Dictionary<TKey,TValue> dictionary;
private int version;
private int index;
private KeyValuePair<TKey,TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
this.getEnumeratorRetType = getEnumeratorRetType;
current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value);
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey,TValue> Current {
get { return current; }
}
public void Dispose() {
}
object IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (getEnumeratorRetType == DictEntry) {
return new System.Collections.DictionaryEntry(current.Key, current.Value);
} else {
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
void IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(current.Key, current.Value);
}
}
object IDictionaryEnumerator.Key {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Key;
}
}
object IDictionaryEnumerator.Value {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Value;
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyCollection: ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey,TValue> dictionary;
public KeyCollection(Dictionary<TKey,TValue> dictionary) {
if (dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator() {
return new Enumerator(dictionary);
}
public void CopyTo(TKey[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count {
get { return dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly {
get { return true; }
}
void ICollection<TKey>.Add(TKey item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear(){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item){
return dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() {
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index) {
if (array==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null) {
CopyTo(keys, index);
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
Object ICollection.SyncRoot {
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TKey currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentKey = default(TKey);
}
public void Dispose() {
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
currentKey = dictionary.entries[index].key;
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
currentKey = default(TKey);
return false;
}
public TKey Current {
get {
return currentKey;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentKey;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentKey = default(TKey);
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueCollection: ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey,TValue> dictionary;
public ValueCollection(Dictionary<TKey,TValue> dictionary) {
if (dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator() {
return new Enumerator(dictionary);
}
public void CopyTo(TValue[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count {
get { return dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly {
get { return true; }
}
void ICollection<TValue>.Add(TValue item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Remove(TValue item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear(){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item){
return dictionary.ContainsValue(item);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() {
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
TValue[] values = array as TValue[];
if (values != null) {
CopyTo(values, index);
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
Object ICollection.SyncRoot {
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TValue currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentValue = default(TValue);
}
public void Dispose() {
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
currentValue = dictionary.entries[index].value;
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
currentValue = default(TValue);
return false;
}
public TValue Current {
get {
return currentValue;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentValue;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentValue = default(TValue);
}
}
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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.
*****************************************************************************/
// Contributed by: Mitch Thompson
using UnityEngine;
using System.Collections.Generic;
namespace Spine.Unity {
[RequireComponent(typeof(Animator))]
public class SkeletonAnimator : SkeletonRenderer, ISkeletonAnimation {
[SerializeField] protected MecanimTranslator translator;
public MecanimTranslator Translator { get { return translator; } }
#region Bone Callbacks (ISkeletonAnimation)
protected event UpdateBonesDelegate _UpdateLocal;
protected event UpdateBonesDelegate _UpdateWorld;
protected event UpdateBonesDelegate _UpdateComplete;
/// <summary>
/// Occurs after the animations are applied and before world space values are resolved.
/// Use this callback when you want to set bone local values.</summary>
public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
/// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Using this callback will cause the world space values to be solved an extra time.
/// Use this callback if want to use bone world space values, and also set bone local values.</summary>
public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
/// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
/// This callback can also be used when setting world position and the bone matrix.</summary>
public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
#endregion
public override void Initialize (bool overwrite) {
if (valid && !overwrite) return;
base.Initialize(overwrite);
if (!valid) return;
if (translator == null) translator = new MecanimTranslator();
translator.Initialize(GetComponent<Animator>(), this.skeletonDataAsset);
}
public void Update () {
if (!valid) return;
translator.Apply(skeleton);
// UpdateWorldTransform and Bone Callbacks
{
if (_UpdateLocal != null)
_UpdateLocal(this);
skeleton.UpdateWorldTransform();
if (_UpdateWorld != null) {
_UpdateWorld(this);
skeleton.UpdateWorldTransform();
}
if (_UpdateComplete != null)
_UpdateComplete(this);
}
}
[System.Serializable]
public class MecanimTranslator {
#region Inspector
public bool autoReset = true;
public MixMode[] layerMixModes = new MixMode[0];
#endregion
public enum MixMode { AlwaysMix, MixNext, SpineStyle }
readonly Dictionary<int, Spine.Animation> animationTable = new Dictionary<int, Spine.Animation>();
readonly Dictionary<AnimationClip, int> clipNameHashCodeTable = new Dictionary<AnimationClip, int>();
readonly List<Animation> previousAnimations = new List<Animation>();
Animator animator;
public Animator Animator { get { return this.animator; } }
public void Initialize (Animator animator, SkeletonDataAsset skeletonDataAsset) {
this.animator = animator;
animationTable.Clear();
clipNameHashCodeTable.Clear();
var data = skeletonDataAsset.GetSkeletonData(true);
foreach (var a in data.Animations)
animationTable.Add(a.Name.GetHashCode(), a);
}
public void Apply (Skeleton skeleton) {
if (layerMixModes.Length < animator.layerCount)
System.Array.Resize<MixMode>(ref layerMixModes, animator.layerCount);
//skeleton.Update(Time.deltaTime); // Doesn't actually do anything, currently. (Spine 3.6).
// Clear Previous
if (autoReset) {
var previousAnimations = this.previousAnimations;
for (int i = 0, n = previousAnimations.Count; i < n; i++)
previousAnimations[i].SetKeyedItemsToSetupPose(skeleton);
previousAnimations.Clear();
for (int layer = 0, n = animator.layerCount; layer < n; layer++) {
float layerWeight = (layer == 0) ? 1 : animator.GetLayerWeight(layer); // Animator.GetLayerWeight always returns 0 on the first layer. Should be interpreted as 1.
if (layerWeight <= 0) continue;
AnimatorStateInfo nextStateInfo = animator.GetNextAnimatorStateInfo(layer);
bool hasNext = nextStateInfo.fullPathHash != 0;
AnimatorClipInfo[] clipInfo = animator.GetCurrentAnimatorClipInfo(layer);
AnimatorClipInfo[] nextClipInfo = animator.GetNextAnimatorClipInfo(layer);
for (int c = 0; c < clipInfo.Length; c++) {
var info = clipInfo[c];
float weight = info.weight * layerWeight; if (weight == 0) continue;
previousAnimations.Add(animationTable[NameHashCode(info.clip)]);
}
if (hasNext) {
for (int c = 0; c < nextClipInfo.Length; c++) {
var info = nextClipInfo[c];
float weight = info.weight * layerWeight; if (weight == 0) continue;
previousAnimations.Add(animationTable[NameHashCode(info.clip)]);
}
}
}
}
// Apply
for (int layer = 0, n = animator.layerCount; layer < n; layer++) {
float layerWeight = (layer == 0) ? 1 : animator.GetLayerWeight(layer); // Animator.GetLayerWeight always returns 0 on the first layer. Should be interpreted as 1.
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(layer);
AnimatorStateInfo nextStateInfo = animator.GetNextAnimatorStateInfo(layer);
bool hasNext = nextStateInfo.fullPathHash != 0;
AnimatorClipInfo[] clipInfo = animator.GetCurrentAnimatorClipInfo(layer);
AnimatorClipInfo[] nextClipInfo = animator.GetNextAnimatorClipInfo(layer);
//UNITY 4
//bool hasNext = nextStateInfo.nameHash != 0;
//var clipInfo = animator.GetCurrentAnimationClipState(i);
//var nextClipInfo = animator.GetNextAnimationClipState(i);
MixMode mode = layerMixModes[layer];
if (mode == MixMode.AlwaysMix) {
// Always use Mix instead of Applying the first non-zero weighted clip.
for (int c = 0; c < clipInfo.Length; c++) {
var info = clipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue;
animationTable[NameHashCode(info.clip)].Apply(skeleton, 0, AnimationTime(stateInfo.normalizedTime, info.clip.length, stateInfo.loop, stateInfo.speed < 0), stateInfo.loop, null, weight, MixPose.Current, MixDirection.In);
}
if (hasNext) {
for (int c = 0; c < nextClipInfo.Length; c++) {
var info = nextClipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue;
animationTable[NameHashCode(info.clip)].Apply(skeleton, 0, AnimationTime(nextStateInfo.normalizedTime , info.clip.length,nextStateInfo.speed < 0), nextStateInfo.loop, null, weight, MixPose.Current, MixDirection.In);
}
}
} else { // case MixNext || SpineStyle
// Apply first non-zero weighted clip
int c = 0;
for (; c < clipInfo.Length; c++) {
var info = clipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue;
animationTable[NameHashCode(info.clip)].Apply(skeleton, 0, AnimationTime(stateInfo.normalizedTime, info.clip.length, stateInfo.loop, stateInfo.speed < 0), stateInfo.loop, null, 1f, MixPose.Current, MixDirection.In);
break;
}
// Mix the rest
for (; c < clipInfo.Length; c++) {
var info = clipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue;
animationTable[NameHashCode(info.clip)].Apply(skeleton, 0, AnimationTime(stateInfo.normalizedTime, info.clip.length, stateInfo.loop, stateInfo.speed < 0), stateInfo.loop, null, weight, MixPose.Current, MixDirection.In);
}
c = 0;
if (hasNext) {
// Apply next clip directly instead of mixing (ie: no crossfade, ignores mecanim transition weights)
if (mode == MixMode.SpineStyle) {
for (; c < nextClipInfo.Length; c++) {
var info = nextClipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue;
animationTable[NameHashCode(info.clip)].Apply(skeleton, 0, AnimationTime(nextStateInfo.normalizedTime , info.clip.length,nextStateInfo.speed < 0), nextStateInfo.loop, null, 1f, MixPose.Current, MixDirection.In);
break;
}
}
// Mix the rest
for (; c < nextClipInfo.Length; c++) {
var info = nextClipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue;
animationTable[NameHashCode(info.clip)].Apply(skeleton, 0, AnimationTime(nextStateInfo.normalizedTime , info.clip.length,nextStateInfo.speed < 0), nextStateInfo.loop, null, weight, MixPose.Current, MixDirection.In);
}
}
}
}
}
static float AnimationTime (float normalizedTime, float clipLength, bool loop, bool reversed) {
if (reversed)
normalizedTime = (1-normalizedTime + (int)normalizedTime) + (int)normalizedTime;
float time = normalizedTime * clipLength;
if (loop) return time;
const float EndSnapEpsilon = 1f/30f; // Workaround for end-duration keys not being applied.
return (clipLength - time < EndSnapEpsilon) ? clipLength : time; // return a time snapped to clipLength;
}
static float AnimationTime (float normalizedTime, float clipLength, bool reversed) {
if (reversed)
normalizedTime = (1-normalizedTime + (int)normalizedTime) + (int)normalizedTime;
return normalizedTime * clipLength;
}
int NameHashCode (AnimationClip clip) {
int clipNameHashCode;
if (!clipNameHashCodeTable.TryGetValue(clip, out clipNameHashCode)) {
clipNameHashCode = clip.name.GetHashCode();
clipNameHashCodeTable.Add(clip, clipNameHashCode);
}
return clipNameHashCode;
}
}
}
}
| |
using System;
using System.Xml;
using System.Collections;
namespace SharpVectors.Dom.Css
{
/// <summary>
/// Used internally for collection of styles for a specific element
/// </summary>
public class CssCollectedStyleDeclaration : CssStyleDeclaration
{
#region Contructors
public CssCollectedStyleDeclaration(XmlElement elm)
{
_element = elm;
}
#endregion
#region Private fields
private XmlElement _element;
private Hashtable collectedStyles = new Hashtable();
#endregion
#region Public methods
public void CollectProperty(string name, int specificity, CssValue cssValue, CssStyleSheetType origin, string priority)
{
CssCollectedProperty newProp = new CssCollectedProperty(name, specificity, cssValue, origin, priority);
if(!collectedStyles.ContainsKey(name))
{
collectedStyles[name] = newProp;
}
else
{
CssCollectedProperty existingProp = (CssCollectedProperty)collectedStyles[name];
if(newProp.IsBetterThen(existingProp))
{
collectedStyles[name] = newProp;
}
}
}
/// <summary>
/// Returns the origin type of the collected property
/// </summary>
/// <param name="propertyName">The name of the property</param>
/// <returns>The origin type</returns>
public CssStyleSheetType GetPropertyOrigin(string propertyName)
{
if(collectedStyles.ContainsKey(propertyName))
{
CssCollectedProperty scp = (CssCollectedProperty)collectedStyles[propertyName];
return scp.Origin;
}
else
{
return CssStyleSheetType.Unknown;
}
}
/// <summary>
/// Used to retrieve the priority of a CSS property (e.g. the "important" qualifier) if the property has been explicitly set in this declaration block.
/// </summary>
/// <param name="propertyName">The name of the CSS property. See the CSS property index.</param>
/// <returns>A string representing the priority (e.g. "important") if one exists. The empty string if none exists.</returns>
public override string GetPropertyPriority(string propertyName)
{
return (collectedStyles.ContainsKey(propertyName)) ? ((CssCollectedProperty)collectedStyles[propertyName]).Priority : String.Empty;
}
private ICssValue getParentStyle(string propertyName)
{
CssXmlDocument doc = _element.OwnerDocument as CssXmlDocument;
XmlElement parentNode = _element.ParentNode as XmlElement;
if(doc != null && parentNode != null)
{
ICssStyleDeclaration parentCsd = doc.GetComputedStyle(parentNode, String.Empty);
if(parentCsd == null)
{
return null;
}
else
{
return parentCsd.GetPropertyCssValue(propertyName);
}
}
else
{
return null;
}
}
public override ICssValue GetPropertyCssValue(string propertyName)
{
if(collectedStyles.ContainsKey(propertyName))
{
CssCollectedProperty scp = (CssCollectedProperty)collectedStyles[propertyName];
if(scp.CssValue.CssValueType == CssValueType.Inherit)
{
// get style from parent chain
return getParentStyle(propertyName);
}
else
{
return scp.CssValue.GetAbsoluteValue(propertyName, _element);
}
}
else
{
// should this property inherit?
CssXmlDocument doc = (CssXmlDocument)_element.OwnerDocument;
if(doc.CssPropertyProfile.IsInherited(propertyName))
{
ICssValue parValue = getParentStyle(propertyName);
if(parValue != null)
{
return parValue;
}
}
string initValue = doc.CssPropertyProfile.GetInitialValue(propertyName);
if(initValue == null)
{
return null;
}
else
{
return CssValue.GetCssValue(initValue, false).GetAbsoluteValue(propertyName, _element);
}
}
}
/// <summary>
/// Used to retrieve the value of a CSS property if it has been explicitly set within this declaration block.
/// </summary>
/// <param name="propertyName">The name of the CSS property. See the CSS property index.</param>
/// <returns>Returns the value of the property if it has been explicitly set for this declaration block. Returns the empty string if the property has not been set.</returns>
public override string GetPropertyValue(string propertyName)
{
CssValue value = (CssValue)GetPropertyCssValue(propertyName);
if(value != null)
{
return value.CssText;
}
else
{
return String.Empty;
}
}
/// <summary>
/// The number of properties that have been explicitly set in this declaration block. The range of valid indices is 0 to length-1 inclusive.
/// </summary>
public override ulong Length
{
get
{
return (ulong)collectedStyles.Count;
}
}
/// <summary>
/// The parsable textual representation of the declaration block (excluding the surrounding curly braces). Setting this attribute will result in the parsing of the new value and resetting of all the properties in the declaration block including the removal or addition of properties.
/// </summary>
/// <exception cref="DomException">SYNTAX_ERR: Raised if the specified CSS string value has a syntax error and is unparsable.</exception>
/// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is readonly or a property is readonly.</exception>
public override string CssText
{
get
{
ulong len = Length;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for(ulong i = 0; i<len; i++)
{
string propName = this[i];
sb.Append(propName);
sb.Append(":");
sb.Append(GetPropertyValue(propName));
string prio = GetPropertyPriority(propName);
if(prio.Length > 0)
{
sb.Append(" !" + prio);
}
sb.Append(";");
}
return sb.ToString();
}
set
{
throw new DomException(DomExceptionType.NoModificationAllowedErr);
}
}
/// <summary>
/// Used to retrieve the properties that have been explicitly set in this declaration block. The order of the properties retrieved using this method does not have to be the order in which they were set. This method can be used to iterate over all properties in this declaration block.
/// The name of the property at this ordinal position. The empty string if no property exists at this position.
/// </summary>
public override string this[ulong index]
{
get
{
if(index>=Length) return String.Empty;
else
{
int ind = (int)index;
IDictionaryEnumerator enu = collectedStyles.GetEnumerator();
enu.MoveNext();
for(int i = 0; i<(int)ind; i++) enu.MoveNext();
return (string)enu.Key;
}
}
}
#endregion
#region Unit tests
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
namespace PowerArgs
{
/// <summary>
/// A class that knows how to revive .NET objects from strings provided on the command line
/// </summary>
public static class ArgRevivers
{
private static Dictionary<Type, Func<string, string, object>> revivers;
private static Dictionary<Type, Func<string, string, object>> Revivers
{
get
{
if (revivers == null)
{
revivers = new Dictionary<Type, Func<string, string, object>>();
LoadDefaultRevivers(revivers);
}
return revivers;
}
}
private static List<Type> cachedConvertibleTypes = new List<Type>();
private static List<Assembly> alreadySearched = new List<Assembly>();
private static bool IsNullable(Type t) => t.IsGenericType && t.GetGenericTypeDefinition().MakeGenericType(typeof(int)) == typeof(int?);
private static Type GetNullableType(Type t) => IsNullable(t) ? t.GetGenericArguments()[0] : throw new ArgumentException("Given argument is not nullable");
/// <summary>
/// Returns true if the given type can be revived, false otherwise
/// </summary>
/// <param name="t">The type to test</param>
/// <returns>true if the given type can be revived, false otherwise</returns>
public static bool CanRevive(Type t)
{
if (Revivers.ContainsKey(t) ||
t.IsEnum ||
cachedConvertibleTypes.Contains(t) ||
(t.GetInterfaces().Contains(typeof(IList)) && t.IsGenericType && CanRevive(t.GetGenericArguments()[0])) ||
(t.IsArray && CanRevive(t.GetElementType())))
return true;
if (IsNullable(t) && CanRevive(GetNullableType(t)))
{
return true;
}
else if(IsNullable(t))
{
// search for nullable revivers in the generic type's assembly
SearchAssemblyForRevivers(GetNullableType(t).Assembly);
}
else
{
SearchAssemblyForRevivers(t.Assembly);
}
if (Revivers.ContainsKey(t) ||
t.IsEnum ||
cachedConvertibleTypes.Contains(t) ||
(t.GetInterfaces().Contains(typeof(IList)) && t.IsGenericType && CanRevive(t.GetGenericArguments()[0])) ||
(t.IsArray && CanRevive(t.GetElementType())))
return true;
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null && t.Assembly.FullName != entryAssembly.FullName)
{
SearchAssemblyForRevivers(entryAssembly);
}
if (Revivers.ContainsKey(t) ||
t.IsEnum ||
cachedConvertibleTypes.Contains(t) ||
(t.GetInterfaces().Contains(typeof(IList)) && t.IsGenericType && CanRevive(t.GetGenericArguments()[0])) ||
(t.IsArray && CanRevive(t.GetElementType())))
return true;
if (System.ComponentModel.TypeDescriptor.GetConverter(t).CanConvertFrom(typeof(string)))
{
lock (cachedConvertibleTypes)
{
cachedConvertibleTypes.Add(t);
}
return true;
}
return false;
}
internal static object ReviveEnum(Type t, string value, bool ignoreCase)
{
if (value.Contains(","))
{
int ret = 0;
var values = value.Split(',').Select(v => v.Trim());
foreach (var enumValue in values)
{
try
{
ret = ret | ParseEnumValue(t, enumValue, ignoreCase);
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
throw new ValidationArgException(enumValue + " is not a valid value for type " + t.Name + ", options are " + string.Join(", ", Enum.GetNames(t)));
}
}
return Enum.ToObject(t, ret);
}
else
{
try
{
return Enum.ToObject(t, ParseEnumValue(t, value, ignoreCase));
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
if (value == string.Empty) value = "<empty>";
throw new ValidationArgException(value + " is not a valid value for type " + t.Name + ", options are " + string.Join(", ", Enum.GetNames(t)));
}
}
}
private static int ParseEnumValue(Type t, string valueString, bool ignoreCase)
{
int rawInt;
if (int.TryParse(valueString, out rawInt))
{
return (int)Enum.ToObject(t, rawInt);
}
object enumShortcutMatch;
if (t.TryMatchEnumShortcut(valueString, ignoreCase, out enumShortcutMatch))
{
return (int)enumShortcutMatch;
}
return (int)Enum.Parse(t, valueString, ignoreCase);
}
/// <summary>
/// Revives the given string into the desired .NET type
/// </summary>
/// <param name="t">The type to revive to</param>
/// <param name="name">the name of the argument</param>
/// <param name="value">The string value to revive</param>
/// <returns>A revived object of the desired type</returns>
public static object Revive(Type t, string name, string value)
{
if (t.IsArray || t.GetInterfaces().Contains(typeof(IList)))
{
var list = t.GetInterfaces().Contains(typeof(IList)) && t.IsArray == false ? (IList)ObjectFactory.CreateInstance(t) : new List<object>();
var elementType = t.IsArray ? t.GetElementType() : t.GetGenericArguments()[0];
List<string> additionalParams;
if(ArgHook.HookContext.Current != null &&
ArgHook.HookContext.Current.CurrentArgument != null &&
ArgHook.HookContext.Current.ParserData.TryGetAndRemoveAdditionalExplicitParameters(ArgHook.HookContext.Current.CurrentArgument, out additionalParams))
{
// this block supports the newer syntax where elements can be separated by a space on the command line
list.Add(Revive(elementType, name + "_element", value));
foreach(var additionalValue in additionalParams)
{
list.Add(Revive(elementType, name + "_element", additionalValue));
}
ArgHook.HookContext.Current.ParserData.AdditionalExplicitParameters.Remove(name);
}
else if (string.IsNullOrWhiteSpace(value) == false)
{
// this block supports the older syntax where elements must be in a single string delimited by commas
foreach (var element in value.Split(','))
{
list.Add(Revive(elementType, name + "_element", element));
}
}
if (t.IsArray)
{
var array = Array.CreateInstance(t.GetElementType(), list.Count);
for (int i = 0; i < array.Length; i++)
{
array.SetValue(list[i], i);
}
return array;
}
else
{
return list;
}
}
else if (Revivers.ContainsKey(t))
{
return Revivers[t].Invoke(name, value);
}
else if(IsNullable(t) && Revivers.ContainsKey(GetNullableType(t)))
{
return Revivers[GetNullableType(t)].Invoke(name, value);
}
else if (System.ComponentModel.TypeDescriptor.GetConverter(t).CanConvertFrom(typeof(string)))
{
return System.ComponentModel.TypeDescriptor.GetConverter(t).ConvertFromString(value);
}
else
{
// Intentionally not an InvalidArgDefinitionException. Other internal code should call
// CanRevive and this block should never be executed.
throw new ArgumentException("Cannot revive type " + t.FullName + ". Callers should be calling CanRevive before calling Revive()");
}
}
internal static void SearchAssemblyForRevivers(Assembly a, bool force = false)
{
if(alreadySearched.Contains(a) && force == false)
{
return;
}
foreach (var type in a.GetTypes().Where(t => t.HasAttr<ArgReviverTypeAttribute>()))
{
var revivers = from m in type.GetMethods(BindingFlags.Static | BindingFlags.Public)
where m.HasAttr<ArgReviverAttribute>() &&
m.GetParameters().Length == 2 &&
m.GetParameters()[0].ParameterType == typeof(string) &&
m.GetParameters()[1].ParameterType == typeof(string) &&
m.ReturnType != typeof(void)
select m;
foreach (var reviver in revivers)
{
SetReviver(reviver);
}
}
if(alreadySearched.Contains(a) == false)
{
alreadySearched.Add(a);
}
}
private static void SetReviver(MethodInfo r)
{
SetReviver(r.ReturnType, (key, val) =>
{
return r.Invoke(null, new object[] { key, val });
});
}
/// <summary>
/// Sets the reviver function for a given type, overriding any existing reviver that may exist.
/// </summary>
/// <param name="t">The type of object the reviver function can revive</param>
/// <param name="reviverFunc">the function that revives a command line string, converting it into a consumable object</param>
public static void SetReviver(Type t, Func<string,string, object> reviverFunc)
{
if (ArgRevivers.Revivers.ContainsKey(t))
{
ArgRevivers.Revivers.Remove(t);
}
ArgRevivers.Revivers.Add(t, reviverFunc);
}
/// <summary>
/// Sets the reviver function for a given type, overriding any existing reviver that may exist.
/// </summary>
/// <typeparam name="T">The type of object the reviver function can revive</typeparam>
/// <param name="reviverFunc">the function that revives a command line string, converting it into a consumable object</param>
public static void SetReviver<T>(Func<string, string, T> reviverFunc)
{
SetReviver(typeof(T), (k, v) => { return reviverFunc(k, v); });
}
/// <summary>
/// Gets the reviver for a given type
/// </summary>
/// <param name="t">the type to revive</param>
/// <returns>the reviver function</returns>
public static Func<string,string,object> GetReviver(Type t)
{
if (ArgRevivers.Revivers.ContainsKey(t))
{
return ArgRevivers.Revivers[t];
}
else
{
return null;
}
}
private static void LoadDefaultRevivers(Dictionary<Type, Func<string, string, object>> revivers)
{
revivers.Add(typeof(bool), (prop, val) =>
{
return val != null && val.ToLower().ToString() != "false" && val != "0"; // null means the switch value was not specified. If it was specified then it's automatically true
});
revivers.Add(typeof(Guid), (prop, val) =>
{
Guid ret;
if (Guid.TryParse(val, out ret) == false) throw new FormatException("value must be a Guid: " + val);
return ret;
});
revivers.Add(typeof(byte), (prop, val) =>
{
byte ret;
if (byte.TryParse(val, out ret) == false) throw new FormatException("value must be a byte: " + val);
return ret;
});
revivers.Add(typeof(int), (prop, val) =>
{
int ret;
if (int.TryParse(val, out ret) == false && TryParseConstant(val, out ret) == false) throw new FormatException("value must be an integer: " + val);
return ret;
});
revivers.Add(typeof(long), (prop, val) =>
{
long ret;
if (long.TryParse(val, out ret) == false && TryParseConstant(val, out ret) == false) throw new FormatException("value must be an integer: " + val);
return ret;
});
revivers.Add(typeof(float), (prop, val) =>
{
float ret;
if (float.TryParse(val, out ret) == false && TryParseConstant(val, out ret) == false) throw new FormatException("value must be a number: " + val);
return ret;
});
revivers.Add(typeof(double), (prop, val) =>
{
double ret;
if (double.TryParse(val, out ret) == false && TryParseConstant(val, out ret) == false) throw new FormatException("value must be a number: " + val);
return ret;
});
revivers.Add(typeof(string), (prop, val) =>
{
return val;
});
revivers.Add(typeof(DateTime), (prop, val) =>
{
DateTime ret;
if (DateTime.TryParse(val, out ret) == false) throw new FormatException("value must be a valid date time: " + val);
return ret;
});
revivers.Add(typeof(SecureStringArgument), (prop, val) =>
{
if (val != null) throw new ArgException("The value for " + prop + " cannot be specified on the command line");
return new SecureStringArgument(prop);
});
revivers.Add(typeof(Uri), (prop, val) =>
{
try
{
return new Uri(val);
}
catch (UriFormatException)
{
throw new UriFormatException("value must be a valid URI: " + val);
}
});
revivers.Add(typeof(IPAddress), (prop, val) =>
{
System.Net.IPAddress ret;
if (System.Net.IPAddress.TryParse(val, out ret) == false) throw new FormatException("value must be a valid IP address: " + val);
return ret;
});
revivers.Add(typeof(ConsoleString), (prop, val) =>
{
return ConsoleString.Parse(val);
});
}
private static bool TryParseConstant<T>(string constantIdentifier, out T ret) where T : struct
{
var match = GetConstants(typeof(T)).Where(c => c.Name == constantIdentifier);
if(match.Count() == 0)
{
ret = default(T);
return false;
}
else
{
ret = (T)match.First().GetValue(null);
return true;
}
}
private static FieldInfo[] GetConstants(System.Type type)
{
ArrayList constants = new ArrayList();
FieldInfo[] fieldInfos = type.GetFields(
// Gets all public and static fields
BindingFlags.Public | BindingFlags.Static |
// This tells it to get the fields from all base types as well
BindingFlags.FlattenHierarchy);
// Go through the list and only pick out the constants
foreach (FieldInfo fi in fieldInfos)
// IsLiteral determines if its value is written at
// compile time and not changeable
// IsInitOnly determines if the field can be set
// in the body of the constructor
// for C# a field which is readonly keyword would have both true
// but a const field would have only IsLiteral equal to true
if (fi.IsLiteral && !fi.IsInitOnly)
constants.Add(fi);
// Return an array of FieldInfos
return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}
}
}
| |
// 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.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Debug = System.Diagnostics.Debug;
using Internal.NativeFormat;
namespace Internal.TypeSystem.Ecma
{
/// <summary>
/// Override of MetadataType that uses actual Ecma335 metadata.
/// </summary>
public sealed partial class EcmaType : MetadataType, EcmaModule.IEntityHandleObject
{
private EcmaModule _module;
private TypeDefinitionHandle _handle;
private TypeDefinition _typeDefinition;
// Cached values
private string _typeName;
private string _typeNamespace;
private TypeDesc[] _genericParameters;
private MetadataType _baseType;
private int _hashcode;
internal EcmaType(EcmaModule module, TypeDefinitionHandle handle)
{
_module = module;
_handle = handle;
_typeDefinition = module.MetadataReader.GetTypeDefinition(handle);
_baseType = this; // Not yet initialized flag
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
public override int GetHashCode()
{
if (_hashcode != 0)
return _hashcode;
return InitializeHashCode();
}
private int InitializeHashCode()
{
TypeDesc containingType = ContainingType;
if (containingType == null)
{
string ns = Namespace;
var hashCodeBuilder = new TypeHashingAlgorithms.HashCodeBuilder(ns);
if (ns.Length > 0)
hashCodeBuilder.Append(".");
hashCodeBuilder.Append(Name);
_hashcode = hashCodeBuilder.ToHashCode();
}
else
{
_hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(
containingType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name));
}
return _hashcode;
}
EntityHandle EcmaModule.IEntityHandleObject.Handle
{
get
{
return _handle;
}
}
public override TypeSystemContext Context
{
get
{
return _module.Context;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = _typeDefinition.GetGenericParameters();
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new EcmaGenericParameter(_module, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override ModuleDesc Module
{
get
{
return _module;
}
}
public EcmaModule EcmaModule
{
get
{
return _module;
}
}
public MetadataReader MetadataReader
{
get
{
return _module.MetadataReader;
}
}
public TypeDefinitionHandle Handle
{
get
{
return _handle;
}
}
private MetadataType InitializeBaseType()
{
var baseTypeHandle = _typeDefinition.BaseType;
if (baseTypeHandle.IsNil)
{
_baseType = null;
return null;
}
var type = _module.GetType(baseTypeHandle) as MetadataType;
if (type == null)
{
// PREFER: "new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadBadFormat, this)" but the metadata is too broken
ThrowHelper.ThrowTypeLoadException(Namespace, Name, Module);
}
_baseType = type;
return type;
}
public override DefType BaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
public override MetadataType MetadataBaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.CategoryMask) != 0)
{
TypeDesc baseType = this.BaseType;
if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType))
{
flags |= TypeFlags.ValueType;
}
else
if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum))
{
flags |= TypeFlags.Enum;
}
else
{
if ((_typeDefinition.Attributes & TypeAttributes.Interface) != 0)
flags |= TypeFlags.Interface;
else
flags |= TypeFlags.Class;
}
// All other cases are handled during TypeSystemContext intitialization
}
if ((mask & TypeFlags.HasGenericVarianceComputed) != 0)
{
flags |= TypeFlags.HasGenericVarianceComputed;
foreach (GenericParameterDesc genericParam in Instantiation)
{
if (genericParam.Variance != GenericVariance.None)
{
flags |= TypeFlags.HasGenericVariance;
break;
}
}
}
if ((mask & TypeFlags.HasFinalizerComputed) != 0)
{
flags |= TypeFlags.HasFinalizerComputed;
if (GetFinalizer() != null)
flags |= TypeFlags.HasFinalizer;
}
return flags;
}
private string InitializeName()
{
var metadataReader = this.MetadataReader;
_typeName = metadataReader.GetString(_typeDefinition.Name);
return _typeName;
}
public override string Name
{
get
{
if (_typeName == null)
return InitializeName();
return _typeName;
}
}
private string InitializeNamespace()
{
var metadataReader = this.MetadataReader;
_typeNamespace = metadataReader.GetString(_typeDefinition.Namespace);
return _typeNamespace;
}
public override string Namespace
{
get
{
if (_typeNamespace == null)
return InitializeNamespace();
return _typeNamespace;
}
}
public override IEnumerable<MethodDesc> GetMethods()
{
foreach (var handle in _typeDefinition.GetMethods())
{
yield return (MethodDesc)_module.GetObject(handle);
}
}
public override MethodDesc GetMethod(string name, MethodSignature signature)
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetMethods())
{
if (stringComparer.Equals(metadataReader.GetMethodDefinition(handle).Name, name))
{
MethodDesc method = (MethodDesc)_module.GetObject(handle);
if (signature == null || signature.Equals(method.Signature))
return method;
}
}
return null;
}
public override MethodDesc GetStaticConstructor()
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetMethods())
{
var methodDefinition = metadataReader.GetMethodDefinition(handle);
if (methodDefinition.Attributes.IsRuntimeSpecialName() &&
stringComparer.Equals(methodDefinition.Name, ".cctor"))
{
MethodDesc method = (MethodDesc)_module.GetObject(handle);
return method;
}
}
return null;
}
public override MethodDesc GetDefaultConstructor()
{
if (IsAbstract)
return null;
MetadataReader metadataReader = this.MetadataReader;
MetadataStringComparer stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetMethods())
{
var methodDefinition = metadataReader.GetMethodDefinition(handle);
MethodAttributes attributes = methodDefinition.Attributes;
if (attributes.IsRuntimeSpecialName() && attributes.IsPublic()
&& stringComparer.Equals(methodDefinition.Name, ".ctor"))
{
MethodDesc method = (MethodDesc)_module.GetObject(handle);
if (method.Signature.Length != 0)
continue;
return method;
}
}
return null;
}
public override MethodDesc GetFinalizer()
{
// System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer
// by checking for a virtual method override that lands anywhere other than Object in the inheritance
// chain.
if (!HasBaseType)
return null;
TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object);
MethodDesc decl = objectType.GetMethod("Finalize", null);
if (decl != null)
{
MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl);
if (impl == null)
{
// TODO: invalid input: the type doesn't derive from our System.Object
throw new TypeLoadException(this.GetFullName());
}
if (impl.OwningType != objectType)
{
return impl;
}
return null;
}
// TODO: Better exception type. Should be: "CoreLib doesn't have a required thing in it".
throw new NotImplementedException();
}
public override IEnumerable<FieldDesc> GetFields()
{
foreach (var handle in _typeDefinition.GetFields())
{
var field = (EcmaField)_module.GetObject(handle);
yield return field;
}
}
public override FieldDesc GetField(string name)
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetFields())
{
if (stringComparer.Equals(metadataReader.GetFieldDefinition(handle).Name, name))
{
var field = (EcmaField)_module.GetObject(handle);
return field;
}
}
return null;
}
public override IEnumerable<MetadataType> GetNestedTypes()
{
foreach (var handle in _typeDefinition.GetNestedTypes())
{
yield return (MetadataType)_module.GetObject(handle);
}
}
public override MetadataType GetNestedType(string name)
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetNestedTypes())
{
if (stringComparer.Equals(metadataReader.GetTypeDefinition(handle).Name, name))
return (MetadataType)_module.GetObject(handle);
}
return null;
}
public TypeAttributes Attributes
{
get
{
return _typeDefinition.Attributes;
}
}
public override DefType ContainingType
{
get
{
if (!_typeDefinition.Attributes.IsNested())
return null;
var handle = _typeDefinition.GetDeclaringType();
return (DefType)_module.GetType(handle);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return !MetadataReader.GetCustomAttributeHandle(_typeDefinition.GetCustomAttributes(),
attributeNamespace, attributeName).IsNil;
}
public override string ToString()
{
return "[" + _module.ToString() + "]" + this.GetFullName();
}
public override ClassLayoutMetadata GetClassLayout()
{
TypeLayout layout = _typeDefinition.GetLayout();
ClassLayoutMetadata result;
result.PackingSize = layout.PackingSize;
result.Size = layout.Size;
// Skip reading field offsets if this is not explicit layout
if (IsExplicitLayout)
{
var fieldDefinitionHandles = _typeDefinition.GetFields();
var numInstanceFields = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
continue;
numInstanceFields++;
}
result.Offsets = new FieldAndOffset[numInstanceFields];
int index = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
continue;
// Note: GetOffset() returns -1 when offset was not set in the metadata
int specifiedOffset = fieldDefinition.GetOffset();
result.Offsets[index] =
new FieldAndOffset((FieldDesc)_module.GetObject(handle), specifiedOffset == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(specifiedOffset));
index++;
}
}
else
result.Offsets = null;
return result;
}
public override MarshalAsDescriptor[] GetFieldMarshalAsDescriptors()
{
var fieldDefinitionHandles = _typeDefinition.GetFields();
MarshalAsDescriptor[] marshalAsDescriptors = new MarshalAsDescriptor[fieldDefinitionHandles.Count];
int index = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
continue;
MarshalAsDescriptor marshalAsDescriptor = GetMarshalAsDescriptor(fieldDefinition);
marshalAsDescriptors[index++] = marshalAsDescriptor;
}
return marshalAsDescriptors;
}
private MarshalAsDescriptor GetMarshalAsDescriptor(FieldDefinition fieldDefinition)
{
if ((fieldDefinition.Attributes & FieldAttributes.HasFieldMarshal) == FieldAttributes.HasFieldMarshal)
{
MetadataReader metadataReader = MetadataReader;
BlobReader marshalAsReader = metadataReader.GetBlobReader(fieldDefinition.GetMarshallingDescriptor());
EcmaSignatureParser parser = new EcmaSignatureParser(EcmaModule, marshalAsReader);
MarshalAsDescriptor marshalAs = parser.ParseMarshalAsDescriptor();
Debug.Assert(marshalAs != null);
return marshalAs;
}
return null;
}
public override bool IsExplicitLayout
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.ExplicitLayout) != 0;
}
}
public override bool IsSequentialLayout
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.SequentialLayout) != 0;
}
}
public override bool IsBeforeFieldInit
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.BeforeFieldInit) != 0;
}
}
public override bool IsModuleType
{
get
{
return _handle.Equals(MetadataTokens.TypeDefinitionHandle(0x00000001 /* COR_GLOBAL_PARENT_TOKEN */));
}
}
public override bool IsSealed
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.Sealed) != 0;
}
}
public override bool IsAbstract
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.Abstract) != 0;
}
}
public override PInvokeStringFormat PInvokeStringFormat
{
get
{
return (PInvokeStringFormat)(_typeDefinition.Attributes & TypeAttributes.StringFormatMask);
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal.NetworkSenders
{
using System;
using System.IO;
using System.Net.Sockets;
using NLog.Common;
/// <summary>
/// Sends messages over a TCP network connection.
/// </summary>
internal class TcpNetworkSender : QueuedNetworkSender
{
#if !SILVERLIGHT
private static bool? EnableKeepAliveSuccessful;
#endif
private readonly EventHandler<SocketAsyncEventArgs> _socketOperationCompleted;
private ISocket _socket;
/// <summary>
/// Initializes a new instance of the <see cref="TcpNetworkSender"/> class.
/// </summary>
/// <param name="url">URL. Must start with tcp://.</param>
/// <param name="addressFamily">The address family.</param>
public TcpNetworkSender(string url, AddressFamily addressFamily)
: base(url)
{
AddressFamily = addressFamily;
_socketOperationCompleted = SocketOperationCompleted;
}
internal AddressFamily AddressFamily { get; set; }
#if !SILVERLIGHT
internal System.Security.Authentication.SslProtocols SslProtocols { get; set; }
internal TimeSpan KeepAliveTime { get; set; }
#endif
/// <summary>
/// Creates the socket with given parameters.
/// </summary>
/// <param name="host">The host address.</param>
/// <param name="addressFamily">The address family.</param>
/// <param name="socketType">Type of the socket.</param>
/// <param name="protocolType">Type of the protocol.</param>
/// <returns>Instance of <see cref="ISocket" /> which represents the socket.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method")]
protected internal virtual ISocket CreateSocket(string host, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
var socketProxy = new SocketProxy(addressFamily, socketType, protocolType);
#if !SILVERLIGHT
if (KeepAliveTime.TotalSeconds >= 1.0 && EnableKeepAliveSuccessful != false)
{
EnableKeepAliveSuccessful = TryEnableKeepAlive(socketProxy.UnderlyingSocket, (int)KeepAliveTime.TotalSeconds);
}
#endif
#if !NETSTANDARD1_0 && !SILVERLIGHT
if (SslProtocols != System.Security.Authentication.SslProtocols.None)
{
return new SslSocketProxy(host, SslProtocols, socketProxy);
}
#endif
return socketProxy;
}
#if !SILVERLIGHT
private static bool TryEnableKeepAlive(Socket underlyingSocket, int keepAliveTimeSeconds)
{
if (TrySetSocketOption(underlyingSocket, SocketOptionName.KeepAlive, true))
{
// SOCKET OPTION NAME CONSTANT
// Ws2ipdef.h (Windows SDK)
// #define TCP_KEEPALIVE 3
// #define TCP_KEEPINTVL 17
SocketOptionName TcpKeepAliveTime = (SocketOptionName)0x3;
SocketOptionName TcpKeepAliveInterval = (SocketOptionName)0x11;
if (PlatformDetector.CurrentOS == RuntimeOS.Linux)
{
// https://github.com/torvalds/linux/blob/v4.16/include/net/tcp.h
// #define TCP_KEEPIDLE 4 /* Start keepalives after this period */
// #define TCP_KEEPINTVL 5 /* Interval between keepalives */
TcpKeepAliveTime = (SocketOptionName)0x4;
TcpKeepAliveInterval = (SocketOptionName)0x5;
}
else if (PlatformDetector.CurrentOS == RuntimeOS.MacOSX)
{
// https://opensource.apple.com/source/xnu/xnu-4570.41.2/bsd/netinet/tcp.h.auto.html
// #define TCP_KEEPALIVE 0x10 /* idle time used when SO_KEEPALIVE is enabled */
// #define TCP_KEEPINTVL 0x101 /* interval between keepalives */
TcpKeepAliveTime = (SocketOptionName)0x10;
TcpKeepAliveInterval = (SocketOptionName)0x101;
}
if (TrySetTcpOption(underlyingSocket, TcpKeepAliveTime, keepAliveTimeSeconds))
{
// Configure retransmission interval when missing acknowledge of keep-alive-probe
TrySetTcpOption(underlyingSocket, TcpKeepAliveInterval, 1); // Default 1 sec on Windows (75 sec on Linux)
return true;
}
}
return false;
}
private static bool TrySetSocketOption(Socket underlyingSocket, SocketOptionName socketOption, bool value)
{
try
{
underlyingSocket.SetSocketOption(SocketOptionLevel.Socket, socketOption, value);
return true;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "NetworkTarget: Failed to configure Socket-option {0} = {1}", socketOption, value);
return false;
}
}
private static bool TrySetTcpOption(Socket underlyingSocket, SocketOptionName socketOption, int value)
{
try
{
underlyingSocket.SetSocketOption(SocketOptionLevel.Tcp, socketOption, value);
return true;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "NetworkTarget: Failed to configure TCP-option {0} = {1}", socketOption, value);
return false;
}
}
#endif
/// <summary>
/// Performs sender-specific initialization.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed in the event handler.")]
protected override void DoInitialize()
{
var uri = new Uri(Address);
var args = new MySocketAsyncEventArgs();
args.RemoteEndPoint = ParseEndpointAddress(new Uri(Address), AddressFamily);
args.Completed += _socketOperationCompleted;
args.UserToken = null;
_socket = CreateSocket(uri.Host, args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
base.BeginInitialize();
bool asyncOperation = false;
try
{
asyncOperation = _socket.ConnectAsync(args);
}
catch (SocketException ex)
{
args.SocketError = ex.SocketErrorCode;
}
catch (Exception ex)
{
if (ex.InnerException is SocketException socketException)
args.SocketError = socketException.SocketErrorCode;
else
args.SocketError = SocketError.OperationAborted;
}
if (!asyncOperation)
{
SocketOperationCompleted(_socket, args);
}
}
/// <summary>
/// Closes the socket.
/// </summary>
/// <param name="continuation">The continuation.</param>
protected override void DoClose(AsyncContinuation continuation)
{
base.DoClose(ex => CloseSocket(continuation, ex));
}
private void CloseSocket(AsyncContinuation continuation, Exception pendingException)
{
try
{
var sock = _socket;
_socket = null;
if (sock != null)
{
sock.Close();
}
continuation(pendingException);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
continuation(exception);
}
}
private void SocketOperationCompleted(object sender, SocketAsyncEventArgs args)
{
var asyncContinuation = args.UserToken as AsyncContinuation;
Exception pendingException = null;
if (args.SocketError != SocketError.Success)
{
pendingException = new IOException("Error: " + args.SocketError);
}
args.Completed -= _socketOperationCompleted; // Maybe consider reusing for next request?
args.Dispose();
base.EndRequest(asyncContinuation, pendingException);
}
protected override void BeginRequest(NetworkRequestArgs eventArgs)
{
var args = new MySocketAsyncEventArgs();
args.SetBuffer(eventArgs.RequestBuffer, eventArgs.RequestBufferOffset, eventArgs.RequestBufferLength);
args.UserToken = eventArgs.AsyncContinuation;
args.Completed += _socketOperationCompleted;
bool asyncOperation = false;
try
{
asyncOperation = _socket.SendAsync(args);
}
catch (SocketException ex)
{
InternalLogger.Error(ex, "NetworkTarget: Error sending tcp request");
args.SocketError = ex.SocketErrorCode;
}
catch (Exception ex)
{
InternalLogger.Error(ex, "NetworkTarget: Error sending tcp request");
if (ex.InnerException is SocketException socketException)
args.SocketError = socketException.SocketErrorCode;
else
args.SocketError = SocketError.OperationAborted;
}
if (!asyncOperation)
{
SocketOperationCompleted(_socket, args);
}
}
public override void CheckSocket()
{
if (_socket == null)
{
DoInitialize();
}
}
/// <summary>
/// Facilitates mocking of <see cref="SocketAsyncEventArgs"/> class.
/// </summary>
internal class MySocketAsyncEventArgs : SocketAsyncEventArgs
{
/// <summary>
/// Raises the Completed event.
/// </summary>
public void RaiseCompleted()
{
OnCompleted(this);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
namespace Caliburn.Light.WinUI
{
/// <summary>
/// Integrate framework lifetime handling into <see cref="Frame"/> navigation events.
/// </summary>
public sealed class FrameAdapter : IFrameAdapter
{
private static readonly DependencyProperty FrameAdapterProperty =
DependencyProperty.RegisterAttached("_FrameAdapter", typeof(AdapterImpl), typeof(FrameAdapter), null);
private static readonly DependencyProperty PageKeyProperty =
DependencyProperty.RegisterAttached("_PageKey", typeof(string), typeof(FrameAdapter), null);
private readonly IViewModelLocator _viewModelLocator;
/// <summary>
/// Creates an instance of <see cref="FrameAdapter" />.
/// </summary>
/// <param name="viewModelLocator">The view-model locator.</param>
public FrameAdapter(IViewModelLocator viewModelLocator)
{
if (viewModelLocator is null)
throw new ArgumentNullException(nameof(viewModelLocator));
_viewModelLocator = viewModelLocator;
}
/// <summary>
/// Attaches this instance to the <paramref name="frame"/>.
/// </summary>
/// <param name="frame">The frame to attach to.</param>
public void AttachTo(Frame frame)
{
if (frame is null)
throw new ArgumentNullException(nameof(frame));
var adapter = (AdapterImpl)frame.GetValue(FrameAdapterProperty);
if (adapter is not null) return;
adapter = new AdapterImpl(this, frame)
{
FrameState = new Dictionary<string, object>()
};
frame.SetValue(FrameAdapterProperty, adapter);
View.SetViewModelLocator(frame, _viewModelLocator);
}
/// <summary>
/// Detaches this instance from the <paramref name="frame"/>.
/// </summary>
/// <param name="frame">The frame to detach from.</param>
public void DetatchFrom(Frame frame)
{
if (frame is null)
throw new ArgumentNullException(nameof(frame));
var adapter = (AdapterImpl)frame.GetValue(FrameAdapterProperty);
if (adapter is null) return;
frame.ClearValue(FrameAdapterProperty);
frame.ClearValue(View.ViewModelLocatorProperty);
adapter.Dispose();
}
private sealed class AdapterImpl : IDisposable
{
private readonly FrameAdapter _parent;
private readonly Frame _frame;
private Page _previousPage;
public AdapterImpl(FrameAdapter parent, Frame frame)
{
_parent = parent;
_frame = frame;
frame.Navigating += OnNavigating;
frame.Navigated += OnNavigated;
frame.NavigationFailed += OnNavigationFailed;
}
public IDictionary<string, object> FrameState { get; set; }
private void OnNavigating(object sender, NavigatingCancelEventArgs e)
{
if (_frame.Content is not Page page) return;
_parent.OnNavigatingFrom(page, e);
if (!e.Cancel)
_previousPage = page;
}
private void OnNavigated(object sender, NavigationEventArgs e)
{
if (_previousPage is not null)
{
var previousPage = _previousPage;
_previousPage = null;
_parent.OnNavigatedFrom(previousPage, FrameState);
}
if (_frame.Content is not Page page) return;
_parent.OnNavigatedTo(page, e, FrameState);
}
private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
_previousPage = null;
}
public void Dispose()
{
_frame.Navigating -= OnNavigating;
_frame.Navigated -= OnNavigated;
_frame.NavigationFailed -= OnNavigationFailed;
}
}
private void OnNavigatingFrom(Page page, NavigatingCancelEventArgs e)
{
if (e.Cancel) return;
if (page.DataContext is ICloseGuard guard)
{
var task = guard.CanCloseAsync();
if (!task.IsCompleted)
throw new NotSupportedException("Asynchronous task is not supported yet.");
if (!task.Result)
{
e.Cancel = true;
}
}
}
private void OnNavigatedFrom(Page page, IDictionary<string, object> frameState)
{
if (page.DataContext is INavigationAware navigationAware)
{
navigationAware.OnNavigatedFrom();
}
SavePageState(page, frameState);
if (page.DataContext is IActivatable deactivator)
{
var close = page.NavigationCacheMode == NavigationCacheMode.Disabled;
deactivator.DeactivateAsync(close).Observe();
}
}
private void OnNavigatedTo(Page page, NavigationEventArgs e, IDictionary<string, object> frameState)
{
if (page.DataContext is null)
{
page.DataContext = _viewModelLocator.LocateForView(page);
View.SetBind(page, true);
}
RestorePageState(page, e.NavigationMode, frameState);
if (page.DataContext is INavigationAware navigationAware)
{
navigationAware.OnNavigatedTo(e.Parameter);
}
if (page.DataContext is IActivatable activator)
{
activator.ActivateAsync().Observe();
}
}
/// <summary>
/// Save the current state for <paramref name="frame"/>.
/// </summary>
/// <param name="frame">The frame.</param>
/// <returns>The internal frame state dictionary.</returns>
public IDictionary<string, object> SaveState(Frame frame)
{
if (frame is null)
throw new ArgumentNullException(nameof(frame));
var adapter = (AdapterImpl)frame.GetValue(FrameAdapterProperty);
if (adapter is null)
throw new InvalidOperationException("Adapter is not attached to frame.");
var frameState = adapter.FrameState;
if (frame.Content is Page currentPage)
{
SavePageState(currentPage, frameState);
}
frameState["Navigation"] = frame.GetNavigationState();
return frameState;
}
/// <summary>
/// Restores previously saved for <paramref name="frame"/>.
/// </summary>
/// <param name="frame">The frame.</param>
/// <param name="frameState">The state dictionary that will be used.</param>
public void RestoreState(Frame frame, IDictionary<string, object> frameState)
{
if (frame is null)
throw new ArgumentNullException(nameof(frame));
if (frameState is null)
throw new ArgumentNullException(nameof(frameState));
var adapter = (AdapterImpl)frame.GetValue(FrameAdapterProperty);
if (adapter is null)
throw new InvalidOperationException("Adapter is not attached to frame.");
adapter.FrameState = frameState;
if (frameState.ContainsKey("Navigation"))
{
frame.SetNavigationState((string)frameState["Navigation"]);
}
}
private void SavePageState(Page page, IDictionary<string, object> frameState)
{
if (page.DataContext is not IPreserveState preserveState) return;
var pageKey = (string)page.GetValue(PageKeyProperty);
var pageState = new Dictionary<string, object>();
preserveState.SaveState(pageState);
frameState[pageKey] = pageState;
}
private void RestorePageState(Page page, NavigationMode navigationMode, IDictionary<string, object> frameState)
{
var frame = page.Frame;
var pageKey = "Page-" + frame.BackStackDepth;
page.SetValue(PageKeyProperty, pageKey);
if (navigationMode == NavigationMode.New)
{
// Clear existing state for forward navigation when adding a new page to the navigation stack
var nextPageKey = pageKey;
int nextPageIndex = frame.BackStackDepth;
while (frameState.Remove(nextPageKey))
{
nextPageIndex++;
nextPageKey = "Page-" + nextPageIndex;
}
}
else
{
// Pass the preserved page state to the page,
// using the same strategy for loading suspended state and recreating pages discarded from cache
if (page.DataContext is IPreserveState preserveState)
{
var pageState = (Dictionary<string, object>)frameState[pageKey];
preserveState.RestoreState(pageState);
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Lists;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Configuration;
using osu.Game.Input.Bindings;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Timing;
using osu.Game.Rulesets.UI.Scrolling.Algorithms;
namespace osu.Game.Rulesets.UI.Scrolling
{
/// <summary>
/// A type of <see cref="DrawableRuleset{TObject}"/> that supports a <see cref="ScrollingPlayfield"/>.
/// <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/> will scroll within the playfield.
/// </summary>
public abstract class DrawableScrollingRuleset<TObject> : DrawableRuleset<TObject>, IKeyBindingHandler<GlobalAction>
where TObject : HitObject
{
/// <summary>
/// The default span of time visible by the length of the scrolling axes.
/// This is clamped between <see cref="time_span_min"/> and <see cref="time_span_max"/>.
/// </summary>
private const double time_span_default = 1500;
/// <summary>
/// The minimum span of time that may be visible by the length of the scrolling axes.
/// </summary>
private const double time_span_min = 50;
/// <summary>
/// The maximum span of time that may be visible by the length of the scrolling axes.
/// </summary>
private const double time_span_max = 20000;
/// <summary>
/// The step increase/decrease of the span of time visible by the length of the scrolling axes.
/// </summary>
private const double time_span_step = 200;
protected readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>();
/// <summary>
/// The span of time that is visible by the length of the scrolling axes.
/// For example, only hit objects with start time less than or equal to 1000 will be visible with <see cref="TimeRange"/> = 1000.
/// </summary>
protected readonly BindableDouble TimeRange = new BindableDouble(time_span_default)
{
Default = time_span_default,
MinValue = time_span_min,
MaxValue = time_span_max
};
protected virtual ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Sequential;
/// <summary>
/// Whether the player can change <see cref="TimeRange"/>.
/// </summary>
protected virtual bool UserScrollSpeedAdjustment => true;
/// <summary>
/// Whether <see cref="TimingControlPoint"/> beat lengths should scale relative to the most common beat length in the <see cref="Beatmap"/>.
/// </summary>
protected virtual bool RelativeScaleBeatLengths => false;
/// <summary>
/// The <see cref="MultiplierControlPoint"/>s that adjust the scrolling rate of <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/>.
/// </summary>
protected readonly SortedList<MultiplierControlPoint> ControlPoints = new SortedList<MultiplierControlPoint>(Comparer<MultiplierControlPoint>.Default);
protected IScrollingInfo ScrollingInfo => scrollingInfo;
[Cached(Type = typeof(IScrollingInfo))]
private readonly LocalScrollingInfo scrollingInfo;
protected DrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
scrollingInfo = new LocalScrollingInfo();
scrollingInfo.Direction.BindTo(Direction);
scrollingInfo.TimeRange.BindTo(TimeRange);
}
[BackgroundDependencyLoader]
private void load()
{
switch (VisualisationMethod)
{
case ScrollVisualisationMethod.Sequential:
scrollingInfo.Algorithm = new SequentialScrollAlgorithm(ControlPoints);
break;
case ScrollVisualisationMethod.Overlapping:
scrollingInfo.Algorithm = new OverlappingScrollAlgorithm(ControlPoints);
break;
case ScrollVisualisationMethod.Constant:
scrollingInfo.Algorithm = new ConstantScrollAlgorithm();
break;
}
double lastObjectTime = Objects.LastOrDefault()?.GetEndTime() ?? double.MaxValue;
double baseBeatLength = TimingControlPoint.DEFAULT_BEAT_LENGTH;
if (RelativeScaleBeatLengths)
{
baseBeatLength = Beatmap.GetMostCommonBeatLength();
// The slider multiplier is post-multiplied to determine the final velocity, but for relative scale beat lengths
// the multiplier should not affect the effective timing point (the longest in the beatmap), so it is factored out here
baseBeatLength /= Beatmap.Difficulty.SliderMultiplier;
}
// Merge sequences of timing and difficulty control points to create the aggregate "multiplier" control point
var lastTimingPoint = new TimingControlPoint();
var lastEffectPoint = new EffectControlPoint();
var allPoints = new SortedList<ControlPoint>(Comparer<ControlPoint>.Default);
allPoints.AddRange(Beatmap.ControlPointInfo.TimingPoints);
allPoints.AddRange(Beatmap.ControlPointInfo.EffectPoints);
// Generate the timing points, making non-timing changes use the previous timing change and vice-versa
var timingChanges = allPoints.Select(c =>
{
switch (c)
{
case TimingControlPoint timingPoint:
lastTimingPoint = timingPoint;
break;
case EffectControlPoint difficultyPoint:
lastEffectPoint = difficultyPoint;
break;
}
return new MultiplierControlPoint(c.Time)
{
Velocity = Beatmap.Difficulty.SliderMultiplier,
BaseBeatLength = baseBeatLength,
TimingPoint = lastTimingPoint,
EffectPoint = lastEffectPoint
};
});
// Trim unwanted sequences of timing changes
timingChanges = timingChanges
// Collapse sections after the last hit object
.Where(s => s.StartTime <= lastObjectTime)
// Collapse sections with the same start time
.GroupBy(s => s.StartTime).Select(g => g.Last()).OrderBy(s => s.StartTime);
ControlPoints.AddRange(timingChanges);
if (ControlPoints.Count == 0)
ControlPoints.Add(new MultiplierControlPoint { Velocity = Beatmap.Difficulty.SliderMultiplier });
}
protected override void LoadComplete()
{
base.LoadComplete();
if (!(Playfield is ScrollingPlayfield))
throw new ArgumentException($"{nameof(Playfield)} must be a {nameof(ScrollingPlayfield)} when using {nameof(DrawableScrollingRuleset<TObject>)}.");
}
/// <summary>
/// Adjusts the scroll speed of <see cref="HitObject"/>s.
/// </summary>
/// <param name="amount">The amount to adjust by. Greater than 0 if the scroll speed should be increased, less than 0 if it should be decreased.</param>
protected virtual void AdjustScrollSpeed(int amount) => this.TransformBindableTo(TimeRange, TimeRange.Value - amount * time_span_step, 200, Easing.OutQuint);
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (!UserScrollSpeedAdjustment)
return false;
switch (e.Action)
{
case GlobalAction.IncreaseScrollSpeed:
AdjustScrollSpeed(1);
return true;
case GlobalAction.DecreaseScrollSpeed:
AdjustScrollSpeed(-1);
return true;
}
return false;
}
private ScheduledDelegate scheduledScrollSpeedAdjustment;
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
scheduledScrollSpeedAdjustment?.Cancel();
scheduledScrollSpeedAdjustment = null;
}
private class LocalScrollingInfo : IScrollingInfo
{
public IBindable<ScrollingDirection> Direction { get; } = new Bindable<ScrollingDirection>();
public IBindable<double> TimeRange { get; } = new BindableDouble();
public IScrollAlgorithm Algorithm { get; set; }
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Services
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Services;
/// <summary>
/// Static proxy methods.
/// </summary>
internal static class ServiceProxySerializer
{
/// <summary>
/// Writes proxy method invocation data to the specified writer.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="methodName">Name of the method.</param>
/// <param name="method">Method (optional, can be null).</param>
/// <param name="arguments">Arguments.</param>
/// <param name="platformType">The platform.</param>
public static void WriteProxyMethod(BinaryWriter writer, string methodName, MethodBase method,
object[] arguments, PlatformType platformType)
{
Debug.Assert(writer != null);
writer.WriteString(methodName);
if (arguments != null)
{
writer.WriteBoolean(true);
writer.WriteInt(arguments.Length);
if (platformType == PlatformType.DotNet)
{
// Write as is for .NET.
foreach (var arg in arguments)
{
writer.WriteObjectDetached(arg);
}
}
else
{
// Other platforms do not support Serializable, need to convert arrays and collections
var mParams = method != null ? method.GetParameters() : null;
Debug.Assert(mParams == null || mParams.Length == arguments.Length);
for (var i = 0; i < arguments.Length; i++)
{
WriteArgForPlatforms(writer, mParams != null ? mParams[i].ParameterType : null, arguments[i]);
}
}
}
else
writer.WriteBoolean(false);
}
/// <summary>
/// Reads proxy method invocation data from the specified reader.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="mthdName">Method name.</param>
/// <param name="mthdArgs">Method arguments.</param>
public static void ReadProxyMethod(IBinaryStream stream, Marshaller marsh,
out string mthdName, out object[] mthdArgs)
{
var reader = marsh.StartUnmarshal(stream);
var srvKeepBinary = reader.ReadBoolean();
mthdName = reader.ReadString();
if (reader.ReadBoolean())
{
mthdArgs = new object[reader.ReadInt()];
if (srvKeepBinary)
reader = marsh.StartUnmarshal(stream, true);
for (var i = 0; i < mthdArgs.Length; i++)
mthdArgs[i] = reader.ReadObject<object>();
}
else
mthdArgs = null;
}
/// <summary>
/// Writes method invocation result.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="methodResult">Method result.</param>
/// <param name="invocationError">Method invocation error.</param>
public static void WriteInvocationResult(IBinaryStream stream, Marshaller marsh, object methodResult,
Exception invocationError)
{
Debug.Assert(stream != null);
Debug.Assert(marsh != null);
var writer = marsh.StartMarshal(stream);
BinaryUtils.WriteInvocationResult(writer, invocationError == null, invocationError ?? methodResult);
marsh.FinishMarshal(writer);
}
/// <summary>
/// Reads method invocation result.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Binary flag.</param>
/// <returns>
/// Method invocation result, or exception in case of error.
/// </returns>
public static object ReadInvocationResult(IBinaryStream stream, Marshaller marsh, bool keepBinary)
{
Debug.Assert(stream != null);
Debug.Assert(marsh != null);
var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize;
var reader = marsh.StartUnmarshal(stream, mode);
object err;
var res = BinaryUtils.ReadInvocationResult(reader, out err);
if (err == null)
return res;
var binErr = err as IBinaryObject;
throw binErr != null
? new ServiceInvocationException("Proxy method invocation failed with a binary error. " +
"Examine BinaryCause for details.", binErr)
: new ServiceInvocationException("Proxy method invocation failed with an exception. " +
"Examine InnerException for details.", (Exception) err);
}
/// <summary>
/// Reads service deployment result.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Binary flag.</param>
/// <returns>
/// Method invocation result, or exception in case of error.
/// </returns>
public static void ReadDeploymentResult(IBinaryStream stream, Marshaller marsh, bool keepBinary)
{
Debug.Assert(stream != null);
Debug.Assert(marsh != null);
var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize;
var reader = marsh.StartUnmarshal(stream, mode);
object err;
BinaryUtils.ReadInvocationResult(reader, out err);
if (err == null)
{
return;
}
// read failed configurations
ICollection<ServiceConfiguration> failedCfgs;
try
{
// switch to BinaryMode.Deserialize mode to avoid IService casting exception
reader = marsh.StartUnmarshal(stream);
failedCfgs = reader.ReadNullableCollectionRaw(f => new ServiceConfiguration(f));
}
catch (Exception e)
{
throw new ServiceDeploymentException("Service deployment failed with an exception. " +
"Examine InnerException for details.", e);
}
var binErr = err as IBinaryObject;
throw binErr != null
? new ServiceDeploymentException("Service deployment failed with a binary error. " +
"Examine BinaryCause for details.", binErr, failedCfgs)
: new ServiceDeploymentException("Service deployment failed with an exception. " +
"Examine InnerException for details.", (Exception) err, failedCfgs);
}
/// <summary>
/// Writes the argument in platform-compatible format.
/// </summary>
private static void WriteArgForPlatforms(BinaryWriter writer, Type paramType, object arg)
{
var hnd = GetPlatformArgWriter(paramType, arg);
if (hnd != null)
{
hnd(writer, arg);
}
else
{
writer.WriteObjectDetached(arg);
}
}
/// <summary>
/// Gets arg writer for platform-compatible service calls.
/// </summary>
private static Action<BinaryWriter, object> GetPlatformArgWriter(Type paramType, object arg)
{
if (arg == null)
{
return null;
}
var type = paramType ?? arg.GetType();
// Unwrap nullable
type = Nullable.GetUnderlyingType(type) ?? type;
if (type.IsPrimitive)
return null;
if (type.IsArray)
{
Type elemType = type.GetElementType();
if (elemType == typeof(Guid?))
return (writer, o) => writer.WriteGuidArray((Guid?[]) o);
else if (elemType == typeof(DateTime?))
return (writer, o) => writer.WriteTimestampArray((DateTime?[]) o);
}
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler != null)
return null;
if (type.IsArray)
return (writer, o) => writer.WriteArrayInternal((Array) o);
if (arg is ICollection)
return (writer, o) => writer.WriteCollection((ICollection) o);
if (arg is DateTime)
return (writer, o) => writer.WriteTimestamp((DateTime) o);
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System.Text;
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_SignatureHelper))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SignatureHelper : _SignatureHelper
{
#region Consts Fields
private const int NO_SIZE_IN_SIG = -1;
#endregion
#region Static Members
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
}
internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst)
{
SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst);
sigHelp.AddData(inst.Length);
foreach(Type t in inst)
sigHelp.AddArgument(t);
return sigHelp;
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention, int cGenericParam,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
{
returnType = typeof(void);
}
intCall = MdSigCallingConvention.Default;
if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
intCall = MdSigCallingConvention.Vararg;
if (cGenericParam > 0)
{
intCall |= MdSigCallingConvention.Generic;
}
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType,
requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
returnType = typeof(void);
if (unmanagedCallConv == CallingConvention.Cdecl)
{
intCall = MdSigCallingConvention.C;
}
else if (unmanagedCallConv == CallingConvention.StdCall || unmanagedCallConv == CallingConvention.Winapi)
{
intCall = MdSigCallingConvention.StdCall;
}
else if (unmanagedCallConv == CallingConvention.ThisCall)
{
intCall = MdSigCallingConvention.ThisCall;
}
else if (unmanagedCallConv == CallingConvention.FastCall)
{
intCall = MdSigCallingConvention.FastCall;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), "unmanagedCallConv");
}
sigHelp = new SignatureHelper(mod, intCall, returnType, null, null);
return sigHelp;
}
public static SignatureHelper GetLocalVarSigHelper()
{
return GetLocalVarSigHelper(null);
}
public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(null, callingConvention, returnType);
}
public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType)
{
return GetMethodSigHelper(null, unmanagedCallingConvention, returnType);
}
public static SignatureHelper GetLocalVarSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.LocalSig);
}
public static SignatureHelper GetFieldSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.Field);
}
public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null);
}
public static SignatureHelper GetPropertySigHelper(Module mod,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
if (returnType == null)
{
returnType = typeof(void);
}
MdSigCallingConvention intCall = MdSigCallingConvention.Property;
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(mod, intCall,
returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetTypeSigToken(Module mod, Type type)
{
if (mod == null)
throw new ArgumentNullException("module");
if (type == null)
throw new ArgumentNullException("type");
return new SignatureHelper(mod, type);
}
#endregion
#region Private Data Members
private byte[] m_signature;
private int m_currSig; // index into m_signature buffer for next available byte
private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed)
private ModuleBuilder m_module;
private bool m_sigDone;
private int m_argCount; // tracking number of arguments in the signature
#endregion
#region Constructor
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention)
{
// Use this constructor to instantiate a local var sig or Field where return type is not applied.
Init(mod, callingConvention);
}
[System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// Use this constructor to instantiate a any signatures that will require a return type.
Init(mod, callingConvention, cGenericParameters);
if (callingConvention == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig"));
AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
[System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
}
[System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, Type type)
{
Init(mod);
AddOneArgTypeHelper(type);
}
private void Init(Module mod)
{
m_signature = new byte[32];
m_currSig = 0;
m_module = mod as ModuleBuilder;
m_argCount = 0;
m_sigDone = false;
m_sizeLoc = NO_SIZE_IN_SIG;
if (m_module == null && mod != null)
throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder"));
}
private void Init(Module mod, MdSigCallingConvention callingConvention)
{
Init(mod, callingConvention, 0);
}
private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam)
{
Init(mod);
AddData((byte)callingConvention);
if (callingConvention == MdSigCallingConvention.Field ||
callingConvention == MdSigCallingConvention.GenericInst)
{
m_sizeLoc = NO_SIZE_IN_SIG;
}
else
{
if (cGenericParam > 0)
AddData(cGenericParam);
m_sizeLoc = m_currSig++;
}
}
#endregion
#region Private Members
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type argument, bool pinned)
{
if (pinned)
AddElementType(CorElementType.Pinned);
AddOneArgTypeHelper(argument);
}
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// This function will not increase the argument count. It only fills in bytes
// in the signature based on clsArgument. This helper is called for return type.
Contract.Requires(clsArgument != null);
Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters);
if (optionalCustomModifiers != null)
{
for (int i = 0; i < optionalCustomModifiers.Length; i++)
{
Type t = optionalCustomModifiers[i];
if (t == null)
throw new ArgumentNullException("optionalCustomModifiers");
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "optionalCustomModifiers");
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "optionalCustomModifiers");
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
Contract.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
if (requiredCustomModifiers != null)
{
for (int i = 0; i < requiredCustomModifiers.Length; i++)
{
Type t = requiredCustomModifiers[i];
if (t == null)
throw new ArgumentNullException("requiredCustomModifiers");
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "requiredCustomModifiers");
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "requiredCustomModifiers");
AddElementType(CorElementType.CModReqd);
int token = m_module.GetTypeToken(t).Token;
Contract.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddOneArgTypeHelper(clsArgument);
}
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); }
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst)
{
if (clsArgument.IsGenericParameter)
{
if (clsArgument.DeclaringMethod != null)
AddElementType(CorElementType.MVar);
else
AddElementType(CorElementType.Var);
AddData(clsArgument.GenericParameterPosition);
}
else if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst))
{
AddElementType(CorElementType.GenericInst);
AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), true);
Type[] args = clsArgument.GetGenericArguments();
AddData(args.Length);
foreach (Type t in args)
AddOneArgTypeHelper(t);
}
else if (clsArgument is TypeBuilder)
{
TypeBuilder clsBuilder = (TypeBuilder)clsArgument;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument is EnumBuilder)
{
TypeBuilder clsBuilder = ((EnumBuilder)clsArgument).m_typeBuilder;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument.IsByRef)
{
AddElementType(CorElementType.ByRef);
clsArgument = clsArgument.GetElementType();
AddOneArgTypeHelper(clsArgument);
}
else if (clsArgument.IsPointer)
{
AddElementType(CorElementType.Ptr);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else if (clsArgument.IsArray)
{
if (clsArgument.IsSzArray)
{
AddElementType(CorElementType.SzArray);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else
{
AddElementType(CorElementType.Array);
AddOneArgTypeHelper(clsArgument.GetElementType());
// put the rank information
int rank = clsArgument.GetArrayRank();
AddData(rank); // rank
AddData(0); // upper bounds
AddData(rank); // lower bound
for (int i = 0; i < rank; i++)
AddData(0);
}
}
else
{
CorElementType type = CorElementType.Max;
if (clsArgument is RuntimeType)
{
type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument);
//GetCorElementType returns CorElementType.Class for both object and string
if (type == CorElementType.Class)
{
if (clsArgument == typeof(object))
type = CorElementType.Object;
else if (clsArgument == typeof(string))
type = CorElementType.String;
}
}
if (IsSimpleType(type))
{
AddElementType(type);
}
else if (m_module == null)
{
InternalAddRuntimeType(clsArgument);
}
else if (clsArgument.IsValueType)
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ValueType);
}
else
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.Class);
}
}
}
private void AddData(int data)
{
// A managed representation of CorSigCompressData;
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
if (data <= 0x7F)
{
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x3FFF)
{
m_signature[m_currSig++] = (byte)((data >>8) | 0x80);
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x1FFFFFFF)
{
m_signature[m_currSig++] = (byte)((data >>24) | 0xC0);
m_signature[m_currSig++] = (byte)((data >>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data >>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data) & 0xFF);
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
}
private void AddData(uint data)
{
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
m_signature[m_currSig++] = (byte)((data) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
}
private void AddData(ulong data)
{
if (m_currSig + 8 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
m_signature[m_currSig++] = (byte)((data) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>32) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>40) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>48) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>56) & 0xFF);
}
private void AddElementType(CorElementType cvt)
{
// Adds an element to the signature. A managed represenation of CorSigCompressElement
if (m_currSig + 1 > m_signature.Length)
m_signature = ExpandArray(m_signature);
m_signature[m_currSig++] = (byte)cvt;
}
private void AddToken(int token)
{
// A managed represenation of CompressToken
// Pulls the token appart to get a rid, adds some appropriate bits
// to the token and then adds this to the signature.
int rid = (token & 0x00FFFFFF); //This is RidFromToken;
MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken;
if (rid > 0x3FFFFFF)
{
// token is too big to be compressed
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
rid = (rid << 2);
// TypeDef is encoded with low bits 00
// TypeRef is encoded with low bits 01
// TypeSpec is encoded with low bits 10
if (type == MetadataTokenType.TypeRef)
{
//if type is mdtTypeRef
rid|=0x1;
}
else if (type == MetadataTokenType.TypeSpec)
{
//if type is mdtTypeSpec
rid|=0x2;
}
AddData(rid);
}
private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType)
{
// Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType
AddElementType(CorType);
AddToken(clsToken.Token);
}
[System.Security.SecurityCritical] // auto-generated
private unsafe void InternalAddRuntimeType(Type type)
{
// Add a runtime type into the signature.
AddElementType(CorElementType.Internal);
IntPtr handle = type.GetTypeHandleInternal().Value;
// Internal types must have their pointer written into the signature directly (we don't
// want to convert to little-endian format on big-endian machines because the value is
// going to be extracted and used directly as a pointer (and only within this process)).
if (m_currSig + sizeof(void*) > m_signature.Length)
m_signature = ExpandArray(m_signature);
byte *phandle = (byte*)&handle;
for (int i = 0; i < sizeof(void*); i++)
m_signature[m_currSig++] = phandle[i];
}
private byte[] ExpandArray(byte[] inArray)
{
// Expand the signature buffer size
return ExpandArray(inArray, inArray.Length * 2);
}
private byte[] ExpandArray(byte[] inArray, int requiredLength)
{
// Expand the signature buffer size
if (requiredLength < inArray.Length)
requiredLength = inArray.Length*2;
byte[] outArray = new byte[requiredLength];
Buffer.BlockCopy(inArray, 0, outArray, 0, inArray.Length);
return outArray;
}
private void IncrementArgCounts()
{
if (m_sizeLoc == NO_SIZE_IN_SIG)
{
//We don't have a size if this is a field.
return;
}
m_argCount++;
}
private void SetNumberOfSignatureElements(bool forceCopy)
{
// For most signatures, this will set the number of elements in a byte which we have reserved for it.
// However, if we have a field signature, we don't set the length and return.
// If we have a signature with more than 128 arguments, we can't just set the number of elements,
// we actually have to allocate more space (e.g. shift everything in the array one or more spaces to the
// right. We do this by making a copy of the array and leaving the correct number of blanks. This new
// array is now set to be m_signature and we use the AddData method to set the number of elements properly.
// The forceCopy argument can be used to force SetNumberOfSignatureElements to make a copy of
// the array. This is useful for GetSignature which promises to trim the array to be the correct size anyway.
byte[] temp;
int newSigSize;
int currSigHolder = m_currSig;
if (m_sizeLoc == NO_SIZE_IN_SIG)
return;
//If we have fewer than 128 arguments and we haven't been told to copy the
//array, we can just set the appropriate bit and return.
if (m_argCount < 0x80 && !forceCopy)
{
m_signature[m_sizeLoc] = (byte)m_argCount;
return;
}
//We need to have more bytes for the size. Figure out how many bytes here.
//Since we need to copy anyway, we're just going to take the cost of doing a
//new allocation.
if (m_argCount < 0x80)
{
newSigSize = 1;
}
else if (m_argCount < 0x4000)
{
newSigSize = 2;
}
else
{
newSigSize = 4;
}
//Allocate the new array.
temp = new byte[m_currSig + newSigSize - 1];
//Copy the calling convention. The calling convention is always just one byte
//so we just copy that byte. Then copy the rest of the array, shifting everything
//to make room for the new number of elements.
temp[0] = m_signature[0];
Buffer.BlockCopy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1));
m_signature = temp;
//Use the AddData method to add the number of elements appropriately compressed.
m_currSig = m_sizeLoc;
AddData(m_argCount);
m_currSig = currSigHolder + (newSigSize - 1);
}
#endregion
#region Internal Members
internal int ArgumentCount
{
get
{
return m_argCount;
}
}
internal static bool IsSimpleType(CorElementType type)
{
if (type <= CorElementType.String)
return true;
if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object)
return true;
return false;
}
internal byte[] InternalGetSignature(out int length)
{
// An internal method to return the signature. Does not trim the
// array, but passes out the length of the array in an out parameter.
// This is the actual array -- not a copy -- so the callee must agree
// to not copy it.
//
// param length : an out param indicating the length of the array.
// return : A reference to the internal ubyte array.
if (!m_sigDone)
{
m_sigDone = true;
// If we have more than 128 variables, we can't just set the length, we need
// to compress it. Unfortunately, this means that we need to copy the entire
// array. Bummer, eh?
SetNumberOfSignatureElements(false);
}
length = m_currSig;
return m_signature;
}
internal byte[] InternalGetSignatureArray()
{
int argCount = m_argCount;
int currSigLength = m_currSig;
int newSigSize = currSigLength;
//Allocate the new array.
if (argCount < 0x7F)
newSigSize += 1;
else if (argCount < 0x3FFF)
newSigSize += 2;
else
newSigSize += 4;
byte[] temp = new byte[newSigSize];
// copy the sig
int sigCopyIndex = 0;
// calling convention
temp[sigCopyIndex++] = m_signature[0];
// arg size
if (argCount <= 0x7F)
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
else if (argCount <= 0x3FFF)
{
temp[sigCopyIndex++] = (byte)((argCount >>8) | 0x80);
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
}
else if (argCount <= 0x1FFFFFFF)
{
temp[sigCopyIndex++] = (byte)((argCount >>24) | 0xC0);
temp[sigCopyIndex++] = (byte)((argCount >>16) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount >>8) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount) & 0xFF);
}
else
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
// copy the sig part of the sig
Buffer.BlockCopy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2);
// mark the end of sig
temp[newSigSize - 1] = (byte)CorElementType.End;
return temp;
}
#endregion
#region Public Methods
public void AddArgument(Type clsArgument)
{
AddArgument(clsArgument, null, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, bool pinned)
{
if (argument == null)
throw new ArgumentNullException("argument");
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
}
public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "requiredCustomModifiers", "arguments"));
if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "optionalCustomModifiers", "arguments"));
if (arguments != null)
{
for (int i =0; i < arguments.Length; i++)
{
AddArgument(arguments[i],
requiredCustomModifiers == null ? null : requiredCustomModifiers[i],
optionalCustomModifiers == null ? null : optionalCustomModifiers[i]);
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized"));
if (argument == null)
throw new ArgumentNullException("argument");
IncrementArgCounts();
// Add an argument to the signature. Takes a Type and determines whether it
// is one of the primitive types of which we have special knowledge or a more
// general class. In the former case, we only add the appropriate short cut encoding,
// otherwise we will calculate proper description for the type.
AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers);
}
public void AddSentinel()
{
AddElementType(CorElementType.Sentinel);
}
public override bool Equals(Object obj)
{
if (!(obj is SignatureHelper))
{
return false;
}
SignatureHelper temp = (SignatureHelper)obj;
if ( !temp.m_module.Equals(m_module) || temp.m_currSig!=m_currSig || temp.m_sizeLoc!=m_sizeLoc || temp.m_sigDone !=m_sigDone )
{
return false;
}
for (int i=0; i<m_currSig; i++)
{
if (m_signature[i]!=temp.m_signature[i])
return false;
}
return true;
}
public override int GetHashCode()
{
// Start the hash code with the hash code of the module and the values of the member variables.
int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc;
// Add one if the sig is done.
if (m_sigDone)
HashCode += 1;
// Then add the hash code of all the arguments.
for (int i=0; i < m_currSig; i++)
HashCode += m_signature[i].GetHashCode();
return HashCode;
}
public byte[] GetSignature()
{
return GetSignature(false);
}
internal byte[] GetSignature(bool appendEndOfSig)
{
// Chops the internal signature to the appropriate length. Adds the
// end token to the signature and marks the signature as finished so that
// no further tokens can be added. Return the full signature in a trimmed array.
if (!m_sigDone)
{
if (appendEndOfSig)
AddElementType(CorElementType.End);
SetNumberOfSignatureElements(true);
m_sigDone = true;
}
// This case will only happen if the user got the signature through
// InternalGetSignature first and then called GetSignature.
if (m_signature.Length > m_currSig)
{
byte[] temp = new byte[m_currSig];
Array.Copy(m_signature, 0, temp, 0, m_currSig);
m_signature = temp;
}
return m_signature;
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Length: " + m_currSig + Environment.NewLine);
if (m_sizeLoc != -1)
{
sb.Append("Arguments: " + m_signature[m_sizeLoc] + Environment.NewLine);
}
else
{
sb.Append("Field Signature" + Environment.NewLine);
}
sb.Append("Signature: " + Environment.NewLine);
for (int i=0; i<=m_currSig; i++)
{
sb.Append(m_signature[i] + " ");
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
#if !FEATURE_CORECLR
void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
}
| |
// <copyright file="Precision.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
#if PORTABLE
using System.Runtime.InteropServices;
#endif
namespace MathNet.Numerics
{
/// <summary>
/// Support Interface for Precision Operation (like AlmostEquals).
/// </summary>
/// <typeparam name="T">Type of the implementing class.</typeparam>
public interface IPrecisionSupport<in T>
{
/// <summary>
/// Returns a Norm of a value of this type, which is appropriate for measuring how
/// close this value is to zero.
/// </summary>
/// <returns>A norm of this value.</returns>
double Norm();
/// <summary>
/// Returns a Norm of the difference of two values of this type, which is
/// appropriate for measuring how close together these two values are.
/// </summary>
/// <param name="otherValue">The value to compare with.</param>
/// <returns>A norm of the difference between this and the other value.</returns>
double NormOfDifference(T otherValue);
}
/// <summary>
/// Utilities for working with floating point numbers.
/// </summary>
/// <remarks>
/// <para>
/// Useful links:
/// <list type="bullet">
/// <item>
/// http://docs.sun.com/source/806-3568/ncg_goldberg.html#689 - What every computer scientist should know about floating-point arithmetic
/// </item>
/// <item>
/// http://en.wikipedia.org/wiki/Machine_epsilon - Gives the definition of machine epsilon
/// </item>
/// </list>
/// </para>
/// </remarks>
public static partial class Precision
{
/// <summary>
/// The number of binary digits used to represent the binary number for a double precision floating
/// point value. i.e. there are this many digits used to represent the
/// actual number, where in a number as: 0.134556 * 10^5 the digits are 0.134556 and the exponent is 5.
/// </summary>
const int DoubleWidth = 53;
/// <summary>
/// The number of binary digits used to represent the binary number for a single precision floating
/// point value. i.e. there are this many digits used to represent the
/// actual number, where in a number as: 0.134556 * 10^5 the digits are 0.134556 and the exponent is 5.
/// </summary>
const int SingleWidth = 24;
/// <summary>
/// The maximum relative precision of of double-precision floating numbers (64 bit)
/// </summary>
public static readonly double DoublePrecision = Math.Pow(2, -DoubleWidth);
/// <summary>
/// The maximum relative precision of of single-precision floating numbers (32 bit)
/// </summary>
public static readonly double SinglePrecision = Math.Pow(2, -SingleWidth);
/// <summary>
/// The number of significant decimal places of double-precision floating numbers (64 bit).
/// </summary>
public static readonly int DoubleDecimalPlaces = (int) Math.Floor(Math.Abs(Math.Log10(DoublePrecision)));
/// <summary>
/// The number of significant decimal places of single-precision floating numbers (32 bit).
/// </summary>
public static readonly int SingleDecimalPlaces = (int) Math.Floor(Math.Abs(Math.Log10(SinglePrecision)));
/// <summary>
/// Value representing 10 * 2^(-53) = 1.11022302462516E-15
/// </summary>
static readonly double DefaultDoubleAccuracy = DoublePrecision*10;
/// <summary>
/// Value representing 10 * 2^(-24) = 5.96046447753906E-07
/// </summary>
static readonly float DefaultSingleAccuracy = (float) (SinglePrecision*10);
/// <summary>
/// Returns the magnitude of the number.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The magnitude of the number.</returns>
public static int Magnitude(this double value)
{
// Can't do this with zero because the 10-log of zero doesn't exist.
if (value.Equals(0.0))
{
return 0;
}
// Note that we need the absolute value of the input because Log10 doesn't
// work for negative numbers (obviously).
double magnitude = Math.Log10(Math.Abs(value));
#if PORTABLE
var truncated = (int)Truncate(magnitude);
#else
var truncated = (int) Math.Truncate(magnitude);
#endif
// To get the right number we need to know if the value is negative or positive
// truncating a positive number will always give use the correct magnitude
// truncating a negative number will give us a magnitude that is off by 1 (unless integer)
return magnitude < 0d && truncated != magnitude
? truncated - 1
: truncated;
}
/// <summary>
/// Returns the magnitude of the number.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The magnitude of the number.</returns>
public static int Magnitude(this float value)
{
// Can't do this with zero because the 10-log of zero doesn't exist.
if (value.Equals(0.0f))
{
return 0;
}
// Note that we need the absolute value of the input because Log10 doesn't
// work for negative numbers (obviously).
var magnitude = Convert.ToSingle(Math.Log10(Math.Abs(value)));
#if PORTABLE
var truncated = (int)Truncate(magnitude);
#else
var truncated = (int) Math.Truncate(magnitude);
#endif
// To get the right number we need to know if the value is negative or positive
// truncating a positive number will always give use the correct magnitude
// truncating a negative number will give us a magnitude that is off by 1 (unless integer)
return magnitude < 0f && truncated != magnitude
? truncated - 1
: truncated;
}
/// <summary>
/// Returns the number divided by it's magnitude, effectively returning a number between -10 and 10.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The value of the number.</returns>
public static double ScaleUnitMagnitude(this double value)
{
if (value.Equals(0.0))
{
return value;
}
int magnitude = Magnitude(value);
return value*Math.Pow(10, -magnitude);
}
/// <summary>
/// Gets the equivalent <c>long</c> value for the given <c>double</c> value.
/// </summary>
/// <param name="value">The <c>double</c> value which should be turned into a <c>long</c> value.</param>
/// <returns>
/// The resulting <c>long</c> value.
/// </returns>
static long AsInt64(double value)
{
#if PORTABLE
return DoubleToInt64Bits(value);
#else
return BitConverter.DoubleToInt64Bits(value);
#endif
}
/// <summary>
/// Returns a 'directional' long value. This is a long value which acts the same as a double,
/// e.g. a negative double value will return a negative double value starting at 0 and going
/// more negative as the double value gets more negative.
/// </summary>
/// <param name="value">The input double value.</param>
/// <returns>A long value which is roughly the equivalent of the double value.</returns>
static long AsDirectionalInt64(double value)
{
// Convert in the normal way.
long result = AsInt64(value);
// Now find out where we're at in the range
// If the value is larger/equal to zero then we can just return the value
// if the value is negative we subtract long.MinValue from it.
return (result >= 0) ? result : (long.MinValue - result);
}
/// <summary>
/// Returns a 'directional' int value. This is a int value which acts the same as a float,
/// e.g. a negative float value will return a negative int value starting at 0 and going
/// more negative as the float value gets more negative.
/// </summary>
/// <param name="value">The input float value.</param>
/// <returns>An int value which is roughly the equivalent of the double value.</returns>
static int AsDirectionalInt32(float value)
{
// Convert in the normal way.
int result = FloatToInt32Bits(value);
// Now find out where we're at in the range
// If the value is larger/equal to zero then we can just return the value
// if the value is negative we subtract int.MinValue from it.
return (result >= 0) ? result : (int.MinValue - result);
}
/// <summary>
/// Increments a floating point number to the next bigger number representable by the data type.
/// </summary>
/// <param name="value">The value which needs to be incremented.</param>
/// <param name="count">How many times the number should be incremented.</param>
/// <remarks>
/// The incrementation step length depends on the provided value.
/// Increment(double.MaxValue) will return positive infinity.
/// </remarks>
/// <returns>The next larger floating point value.</returns>
public static double Increment(this double value, int count = 1)
{
if (double.IsInfinity(value) || double.IsNaN(value) || count == 0)
{
return value;
}
if (count < 0)
{
return Decrement(value, -count);
}
// Translate the bit pattern of the double to an integer.
// Note that this leads to:
// double > 0 --> long > 0, growing as the double value grows
// double < 0 --> long < 0, increasing in absolute magnitude as the double
// gets closer to zero!
// i.e. 0 - double.epsilon will give the largest long value!
long intValue = AsInt64(value);
if (intValue < 0)
{
intValue -= count;
}
else
{
intValue += count;
}
// Note that long.MinValue has the same bit pattern as -0.0.
if (intValue == long.MinValue)
{
return 0;
}
// Note that not all long values can be translated into double values. There's a whole bunch of them
// which return weird values like infinity and NaN
#if PORTABLE
return Int64BitsToDouble(intValue);
#else
return BitConverter.Int64BitsToDouble(intValue);
#endif
}
/// <summary>
/// Decrements a floating point number to the next smaller number representable by the data type.
/// </summary>
/// <param name="value">The value which should be decremented.</param>
/// <param name="count">How many times the number should be decremented.</param>
/// <remarks>
/// The decrementation step length depends on the provided value.
/// Decrement(double.MinValue) will return negative infinity.
/// </remarks>
/// <returns>The next smaller floating point value.</returns>
public static double Decrement(this double value, int count = 1)
{
if (double.IsInfinity(value) || double.IsNaN(value) || count == 0)
{
return value;
}
if (count < 0)
{
return Decrement(value, -count);
}
// Translate the bit pattern of the double to an integer.
// Note that this leads to:
// double > 0 --> long > 0, growing as the double value grows
// double < 0 --> long < 0, increasing in absolute magnitude as the double
// gets closer to zero!
// i.e. 0 - double.epsilon will give the largest long value!
long intValue = AsInt64(value);
// If the value is zero then we'd really like the value to be -0. So we'll make it -0
// and then everything else should work out.
if (intValue == 0)
{
// Note that long.MinValue has the same bit pattern as -0.0.
intValue = long.MinValue;
}
if (intValue < 0)
{
intValue += count;
}
else
{
intValue -= count;
}
// Note that not all long values can be translated into double values. There's a whole bunch of them
// which return weird values like infinity and NaN
#if PORTABLE
return Int64BitsToDouble(intValue);
#else
return BitConverter.Int64BitsToDouble(intValue);
#endif
}
/// <summary>
/// Forces small numbers near zero to zero, according to the specified absolute accuracy.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <param name="maxNumbersBetween">The maximum count of numbers between the zero and the number <paramref name="a"/>.</param>
/// <returns>
/// Zero if |<paramref name="a"/>| is fewer than <paramref name="maxNumbersBetween"/> numbers from zero, <paramref name="a"/> otherwise.
/// </returns>
public static double CoerceZero(this double a, int maxNumbersBetween)
{
return CoerceZero(a, (long) maxNumbersBetween);
}
/// <summary>
/// Forces small numbers near zero to zero, according to the specified absolute accuracy.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <param name="maxNumbersBetween">The maximum count of numbers between the zero and the number <paramref name="a"/>.</param>
/// <returns>
/// Zero if |<paramref name="a"/>| is fewer than <paramref name="maxNumbersBetween"/> numbers from zero, <paramref name="a"/> otherwise.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="maxNumbersBetween"/> is smaller than zero.
/// </exception>
public static double CoerceZero(this double a, long maxNumbersBetween)
{
if (maxNumbersBetween < 0)
{
throw new ArgumentOutOfRangeException("maxNumbersBetween");
}
if (double.IsInfinity(a) || double.IsNaN(a))
{
return a;
}
// We allow maxNumbersBetween between 0 and the number so
// we need to check if there a
if (NumbersBetween(0.0, a) <= (ulong) maxNumbersBetween)
{
return 0.0;
}
return a;
}
/// <summary>
/// Forces small numbers near zero to zero, according to the specified absolute accuracy.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <param name="maximumAbsoluteError">The absolute threshold for <paramref name="a"/> to consider it as zero.</param>
/// <returns>Zero if |<paramref name="a"/>| is smaller than <paramref name="maximumAbsoluteError"/>, <paramref name="a"/> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="maximumAbsoluteError"/> is smaller than zero.
/// </exception>
public static double CoerceZero(this double a, double maximumAbsoluteError)
{
if (maximumAbsoluteError < 0)
{
throw new ArgumentOutOfRangeException("maximumAbsoluteError");
}
if (double.IsInfinity(a) || double.IsNaN(a))
{
return a;
}
if (Math.Abs(a) < maximumAbsoluteError)
{
return 0.0;
}
return a;
}
/// <summary>
/// Forces small numbers near zero to zero.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <returns>Zero if |<paramref name="a"/>| is smaller than 2^(-53) = 1.11e-16, <paramref name="a"/> otherwise.</returns>
public static double CoerceZero(this double a)
{
return CoerceZero(a, DoublePrecision);
}
/// <summary>
/// Determines the range of floating point numbers that will match the specified value with the given tolerance.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="maxNumbersBetween"/> is smaller than zero.
/// </exception>
/// <returns>Tuple of the bottom and top range ends.</returns>
public static Tuple<double, double> RangeOfMatchingFloatingPointNumbers(this double value, long maxNumbersBetween)
{
// Make sure ulpDifference is non-negative
if (maxNumbersBetween < 1)
{
throw new ArgumentOutOfRangeException("maxNumbersBetween");
}
// If the value is infinity (positive or negative) just
// return the same infinity for the range.
if (double.IsInfinity(value))
{
return new Tuple<double, double>(value, value);
}
// If the value is a NaN then the range is a NaN too.
if (double.IsNaN(value))
{
return new Tuple<double, double>(double.NaN, double.NaN);
}
// Translate the bit pattern of the double to an integer.
// Note that this leads to:
// double > 0 --> long > 0, growing as the double value grows
// double < 0 --> long < 0, increasing in absolute magnitude as the double
// gets closer to zero!
// i.e. 0 - double.epsilon will give the largest long value!
long intValue = AsInt64(value);
#if PORTABLE
// We need to protect against over- and under-flow of the intValue when
// we start to add the ulpsDifference.
if (intValue < 0)
{
// Note that long.MinValue has the same bit pattern as
// -0.0. Therefore we're working in opposite direction (i.e. add if we want to
// go more negative and subtract if we want to go less negative)
var topRangeEnd = Math.Abs(long.MinValue - intValue) < maxNumbersBetween
// Got underflow, which can be fixed by splitting the calculation into two bits
// first get the remainder of the intValue after subtracting it from the long.MinValue
// and add that to the ulpsDifference. That way we'll turn positive without underflow
? Int64BitsToDouble(maxNumbersBetween + (long.MinValue - intValue))
// No problems here, move along.
: Int64BitsToDouble(intValue - maxNumbersBetween);
var bottomRangeEnd = Math.Abs(intValue) < maxNumbersBetween
// Underflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return -Double.MaxValue
? -double.MaxValue
// intValue is negative. Adding the positive ulpsDifference means that it gets less negative.
// However due to the conversion way this means that the actual double value gets more negative :-S
: Int64BitsToDouble(intValue + maxNumbersBetween);
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
else
{
// IntValue is positive
var topRangeEnd = long.MaxValue - intValue < maxNumbersBetween
// Overflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return Double.MaxValue
? double.MaxValue
// No troubles here
: Int64BitsToDouble(intValue + maxNumbersBetween);
// Check the bottom range end for underflows
var bottomRangeEnd = intValue > maxNumbersBetween
// No problems here. IntValue is larger than ulpsDifference so we'll end up with a
// positive number.
? Int64BitsToDouble(intValue - maxNumbersBetween)
// Int value is bigger than zero but smaller than the ulpsDifference. So we'll need to deal with
// the reversal at the negative end
: Int64BitsToDouble(long.MinValue + (maxNumbersBetween - intValue));
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
#else
// We need to protect against over- and under-flow of the intValue when
// we start to add the ulpsDifference.
if (intValue < 0)
{
// Note that long.MinValue has the same bit pattern as
// -0.0. Therefore we're working in opposite direction (i.e. add if we want to
// go more negative and subtract if we want to go less negative)
var topRangeEnd = Math.Abs(long.MinValue - intValue) < maxNumbersBetween
// Got underflow, which can be fixed by splitting the calculation into two bits
// first get the remainder of the intValue after subtracting it from the long.MinValue
// and add that to the ulpsDifference. That way we'll turn positive without underflow
? BitConverter.Int64BitsToDouble(maxNumbersBetween + (long.MinValue - intValue))
// No problems here, move along.
: BitConverter.Int64BitsToDouble(intValue - maxNumbersBetween);
var bottomRangeEnd = Math.Abs(intValue) < maxNumbersBetween
// Underflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return -Double.MaxValue
? -double.MaxValue
// intValue is negative. Adding the positive ulpsDifference means that it gets less negative.
// However due to the conversion way this means that the actual double value gets more negative :-S
: BitConverter.Int64BitsToDouble(intValue + maxNumbersBetween);
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
else
{
// IntValue is positive
var topRangeEnd = long.MaxValue - intValue < maxNumbersBetween
// Overflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return Double.MaxValue
? double.MaxValue
// No troubles here
: BitConverter.Int64BitsToDouble(intValue + maxNumbersBetween);
// Check the bottom range end for underflows
var bottomRangeEnd = intValue > maxNumbersBetween
// No problems here. IntValue is larger than ulpsDifference so we'll end up with a
// positive number.
? BitConverter.Int64BitsToDouble(intValue - maxNumbersBetween)
// Int value is bigger than zero but smaller than the ulpsDifference. So we'll need to deal with
// the reversal at the negative end
: BitConverter.Int64BitsToDouble(long.MinValue + (maxNumbersBetween - intValue));
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
#endif
}
/// <summary>
/// Returns the floating point number that will match the value with the tolerance on the maximum size (i.e. the result is
/// always bigger than the value)
/// </summary>
/// <param name="value">The value.</param>
/// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param>
/// <returns>The maximum floating point number which is <paramref name="maxNumbersBetween"/> larger than the given <paramref name="value"/>.</returns>
public static double MaximumMatchingFloatingPointNumber(this double value, long maxNumbersBetween)
{
return RangeOfMatchingFloatingPointNumbers(value, maxNumbersBetween).Item2;
}
/// <summary>
/// Returns the floating point number that will match the value with the tolerance on the minimum size (i.e. the result is
/// always smaller than the value)
/// </summary>
/// <param name="value">The value.</param>
/// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param>
/// <returns>The minimum floating point number which is <paramref name="maxNumbersBetween"/> smaller than the given <paramref name="value"/>.</returns>
public static double MinimumMatchingFloatingPointNumber(this double value, long maxNumbersBetween)
{
return RangeOfMatchingFloatingPointNumbers(value, maxNumbersBetween).Item1;
}
/// <summary>
/// Determines the range of <c>ulps</c> that will match the specified value with the given tolerance.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="relativeDifference">The relative difference.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="relativeDifference"/> is smaller than zero.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="value"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="value"/> is <c>double.NaN</c>.
/// </exception>
/// <returns>
/// Tuple with the number of ULPS between the <c>value</c> and the <c>value - relativeDifference</c> as first,
/// and the number of ULPS between the <c>value</c> and the <c>value + relativeDifference</c> as second value.
/// </returns>
public static Tuple<long, long> RangeOfMatchingNumbers(this double value, double relativeDifference)
{
// Make sure the relative is non-negative
if (relativeDifference < 0)
{
throw new ArgumentOutOfRangeException("relativeDifference");
}
// If the value is infinity (positive or negative) then
// we can't determine the range.
if (double.IsInfinity(value))
{
throw new ArgumentOutOfRangeException("value");
}
// If the value is a NaN then we can't determine the range.
if (double.IsNaN(value))
{
throw new ArgumentOutOfRangeException("value");
}
// If the value is zero (0.0) then we can't calculate the relative difference
// so return the ulps counts for the difference.
if (value.Equals(0))
{
var v = AsInt64(relativeDifference);
return new Tuple<long, long>(v, v);
}
// Calculate the ulps for the maximum and minimum values
// Note that these can overflow
long max = AsDirectionalInt64(value + (relativeDifference*Math.Abs(value)));
long min = AsDirectionalInt64(value - (relativeDifference*Math.Abs(value)));
// Calculate the ulps from the value
long intValue = AsDirectionalInt64(value);
// Determine the ranges
return new Tuple<long, long>(Math.Abs(intValue - min), Math.Abs(max - intValue));
}
/// <summary>
/// Evaluates the count of numbers between two double numbers
/// </summary>
/// <param name="a">The first parameter.</param>
/// <param name="b">The second parameter.</param>
/// <remarks>The second number is included in the number, thus two equal numbers evaluate to zero and two neighbor numbers evaluate to one. Therefore, what is returned is actually the count of numbers between plus 1.</remarks>
/// <returns>The number of floating point values between <paramref name="a"/> and <paramref name="b"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="a"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="a"/> is <c>double.NaN</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="b"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="b"/> is <c>double.NaN</c>.
/// </exception>
[CLSCompliant(false)]
public static ulong NumbersBetween(this double a, double b)
{
if (double.IsNaN(a) || double.IsInfinity(a))
{
throw new ArgumentOutOfRangeException("a");
}
if (double.IsNaN(b) || double.IsInfinity(b))
{
throw new ArgumentOutOfRangeException("b");
}
// Calculate the ulps for the maximum and minimum values
// Note that these can overflow
long intA = AsDirectionalInt64(a);
long intB = AsDirectionalInt64(b);
// Now find the number of values between the two doubles. This should not overflow
// given that there are more long values than there are double values
return (a >= b) ? (ulong) (intA - intB) : (ulong) (intB - intA);
}
/// <summary>
/// Evaluates the minimum distance to the next distinguishable number near the argument value.
/// </summary>
/// <param name="value">The value used to determine the minimum distance.</param>
/// <returns>
/// Relative Epsilon (positive double or NaN).
/// </returns>
/// <remarks>Evaluates the <b>negative</b> epsilon. The more common positive epsilon is equal to two times this negative epsilon.</remarks>
/// <seealso cref="PositiveEpsilonOf(double)"/>
public static double EpsilonOf(this double value)
{
if (double.IsInfinity(value) || double.IsNaN(value))
{
return double.NaN;
}
#if PORTABLE
long signed64 = DoubleToInt64Bits(value);
if (signed64 == 0)
{
signed64++;
return Int64BitsToDouble(signed64) - value;
}
if (signed64-- < 0)
{
return Int64BitsToDouble(signed64) - value;
}
return value - Int64BitsToDouble(signed64);
#else
long signed64 = BitConverter.DoubleToInt64Bits(value);
if (signed64 == 0)
{
signed64++;
return BitConverter.Int64BitsToDouble(signed64) - value;
}
if (signed64-- < 0)
{
return BitConverter.Int64BitsToDouble(signed64) - value;
}
return value - BitConverter.Int64BitsToDouble(signed64);
#endif
}
/// <summary>
/// Evaluates the minimum distance to the next distinguishable number near the argument value.
/// </summary>
/// <param name="value">The value used to determine the minimum distance.</param>
/// <returns>Relative Epsilon (positive double or NaN)</returns>
/// <remarks>Evaluates the <b>positive</b> epsilon. See also <see cref="EpsilonOf"/></remarks>
/// <seealso cref="EpsilonOf(double)"/>
public static double PositiveEpsilonOf(this double value)
{
return 2*EpsilonOf(value);
}
/// <summary>
/// Converts a float valut to a bit array stored in an int.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The bit array.</returns>
static int FloatToInt32Bits(float value)
{
return BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
}
#if PORTABLE
static long DoubleToInt64Bits(double value)
{
var union = new DoubleLongUnion {Double = value};
return union.Int64;
}
static double Int64BitsToDouble(long value)
{
var union = new DoubleLongUnion {Int64 = value};
return union.Double;
}
static double Truncate(double value)
{
return value >= 0.0 ? Math.Floor(value) : Math.Ceiling(value);
}
[StructLayout(LayoutKind.Explicit)]
struct DoubleLongUnion
{
[FieldOffset(0)]
public double Double;
[FieldOffset(0)]
public long Int64;
}
#endif
}
}
| |
// 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.
/***************************************************************************\
*
* File: XmlWrappingReader.cs
*
* Purpose:
*
\***************************************************************************/
using System;
using System.Xml;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.IO.Packaging
{
internal class XmlWrappingReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Fields
//
protected XmlReader _reader;
protected IXmlLineInfo _readerAsIXmlLineInfo;
protected IXmlNamespaceResolver _readerAsResolver;
//
// Constructor
//
internal XmlWrappingReader(XmlReader baseReader)
{
Debug.Assert(baseReader != null);
Reader = baseReader;
}
//
// XmlReader implementation
//
public override XmlReaderSettings Settings { get { return _reader.Settings; } }
public override XmlNodeType NodeType { get { return _reader.NodeType; } }
public override string Name { get { return _reader.Name; } }
public override string LocalName { get { return _reader.LocalName; } }
public override string NamespaceURI { get { return _reader.NamespaceURI; } }
public override string Prefix { get { return _reader.Prefix; } }
public override bool HasValue { get { return _reader.HasValue; } }
public override string Value { get { return _reader.Value; } }
public override int Depth { get { return _reader.Depth; } }
public override string BaseURI { get { return _reader.BaseURI; } }
public override bool IsEmptyElement { get { return _reader.IsEmptyElement; } }
public override bool IsDefault { get { return _reader.IsDefault; } }
public override XmlSpace XmlSpace { get { return _reader.XmlSpace; } }
public override string XmlLang { get { return _reader.XmlLang; } }
public override System.Type ValueType { get { return _reader.ValueType; } }
public override int AttributeCount { get { return _reader.AttributeCount; } }
public override string this[int i] { get { return _reader[i]; } }
public override string this[string name] { get { return _reader[name]; } }
public override string this[string name, string namespaceURI] { get { return _reader[name, namespaceURI]; } }
public override bool CanResolveEntity { get { return _reader.CanResolveEntity; } }
public override bool EOF { get { return _reader.EOF; } }
public override ReadState ReadState { get { return _reader.ReadState; } }
public override bool HasAttributes { get { return _reader.HasAttributes; } }
public override XmlNameTable NameTable { get { return _reader.NameTable; } }
public override string GetAttribute(string name)
{
return _reader.GetAttribute(name);
}
public override string GetAttribute(string name, string namespaceURI)
{
return _reader.GetAttribute(name, namespaceURI);
}
public override string GetAttribute(int i)
{
return _reader.GetAttribute(i);
}
public override bool MoveToAttribute(string name)
{
return _reader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string name, string ns)
{
return _reader.MoveToAttribute(name, ns);
}
public override void MoveToAttribute(int i)
{
_reader.MoveToAttribute(i);
}
public override bool MoveToFirstAttribute()
{
return _reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _reader.MoveToNextAttribute();
}
public override bool MoveToElement()
{
return _reader.MoveToElement();
}
public override bool Read()
{
return _reader.Read();
}
public override void Skip()
{
_reader.Skip();
}
public override string LookupNamespace(string prefix)
{
return _reader.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return (_readerAsResolver == null) ? null : _readerAsResolver.LookupPrefix(namespaceName);
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return (_readerAsResolver == null) ? null : _readerAsResolver.GetNamespacesInScope(scope);
}
public override void ResolveEntity()
{
_reader.ResolveEntity();
}
public override bool ReadAttributeValue()
{
return _reader.ReadAttributeValue();
}
//
// IDisposable interface
//
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
((IDisposable)_reader).Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
//
// IXmlLineInfo members
//
public virtual bool HasLineInfo()
{
return (_readerAsIXmlLineInfo == null) ? false : _readerAsIXmlLineInfo.HasLineInfo();
}
public virtual int LineNumber
{
get
{
return (_readerAsIXmlLineInfo == null) ? 0 : _readerAsIXmlLineInfo.LineNumber;
}
}
public virtual int LinePosition
{
get
{
return (_readerAsIXmlLineInfo == null) ? 0 : _readerAsIXmlLineInfo.LinePosition;
}
}
//
// Protected methods
//
protected XmlReader Reader
{
get
{
return _reader;
}
set
{
_reader = value;
_readerAsIXmlLineInfo = value as IXmlLineInfo;
_readerAsResolver = value as IXmlNamespaceResolver;
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Akka.Actor;
using GridDomain.Common;
using GridDomain.CQRS;
using GridDomain.EventSourcing;
using GridDomain.EventSourcing.CommonDomain;
using GridDomain.Node;
using GridDomain.Node.Actors;
using GridDomain.Node.Actors.CommandPipe.Messages;
using GridDomain.Node.Actors.PersistentHub;
using GridDomain.Node.Actors.ProcessManagers;
using GridDomain.Node.AkkaMessaging;
using GridDomain.Node.AkkaMessaging.Waiting;
using GridDomain.ProcessManagers;
using GridDomain.ProcessManagers.State;
using GridDomain.Tools;
using GridDomain.Tools.Repositories.AggregateRepositories;
using GridDomain.Tools.Repositories.EventRepositories;
namespace GridDomain.Tests.Common
{
public static class GridNodeExtensions
{
public static async Task<WarmUpResult> WarmUpProcessManager<TProcess>(this GridDomainNode node, string id,TimeSpan? timeout = null)
{
var processHub = await node.LookupProcessHubActor<TProcess>(timeout);
return await processHub.Ask<WarmUpResult>(new WarmUpChild(id));
}
public static Task SendToProcessManagers(this GridDomainNode node, DomainEvent msg, TimeSpan? timeout = null)
{
return node.Pipe.ProcessesPipeActor.Ask<ProcessesTransitComplete>(new MessageMetadataEnvelop(msg), timeout);
}
public static async Task<TExpect> SendToProcessManager<TExpect>(this GridDomainNode node, DomainEvent msg, TimeSpan? timeout = null) where TExpect : class
{
var res = await node.NewDebugWaiter(timeout)
.Expect<TExpect>()
.Create()
.SendToProcessManagers(msg);
return res.Message<TExpect>();
}
public static async Task<TState> GetTransitedState<TState>(this GridDomainNode node, DomainEvent msg, TimeSpan? timeout = null) where TState : IProcessState
{
var res = await node.SendToProcessManager<ProcessReceivedMessage<TState>>(msg,timeout);
return res.State;
}
public static async Task<TState> GetCreatedState<TState>(this GridDomainNode node, DomainEvent msg, TimeSpan? timeout = null) where TState : IProcessState
{
var res = await node.SendToProcessManager<ProcessManagerCreated<TState>>(msg, timeout);
return res.State;
}
public static IMessageWaiter<AnyMessagePublisher> NewDebugWaiter(this GridDomainNode node, TimeSpan? timeout = null)
{
var conditionBuilder = new MetadataConditionBuilder<AnyMessagePublisher>();
var waiter = new LocalMessagesWaiter<AnyMessagePublisher>(node.System, node.Transport, timeout ?? node.DefaultTimeout, conditionBuilder);
conditionBuilder.CreateResultFunc = t => new AnyMessagePublisher(node.Pipe, waiter);
return waiter;
}
public static async Task<TAggregate> LoadAggregate<TAggregate>(this GridDomainNode node, string id)
where TAggregate : Aggregate
{
using (var eventsRepo = new ActorSystemEventRepository(node.System))
using (var repo = new AggregateRepository(eventsRepo))
{
return await repo.LoadAggregate<TAggregate>(id);
}
}
public static async Task<object[]> LoadFromJournal(this GridDomainNode node, string id)
{
using (var repo = new ActorSystemJournalRepository(node.System))
{
return await repo.Load(id);
}
}
public static async Task SaveToJournal(this GridDomainNode node, string id, params object[] messages)
{
using (var repo = new ActorSystemJournalRepository(node.System, false))
{
await repo.Save(id, messages);
}
}
public static async Task SaveToJournal<TAggregate>(this GridDomainNode node, TAggregate aggregate) where TAggregate : Aggregate
{
var domainEvents = ((IAggregate) aggregate).GetUncommittedEvents()
.ToArray();
await node.SaveToJournal<TAggregate>(aggregate.Id, domainEvents);
aggregate.ClearUncommitedEvents();
}
public static async Task SaveToJournal<TAggregate>(this GridDomainNode node, string id, params DomainEvent[] messages)
where TAggregate : Aggregate
{
var name = EntityActorName.New<TAggregate>(id).Name;
await node.SaveToJournal(name, messages);
}
public static async Task<IActorRef> LookupAggregateActor<T>(this GridDomainNode node,
string id,
TimeSpan? timeout = null) where T : IAggregate
{
var name = EntityActorName.New<T>(id).Name;
return await node.ResolveActor($"{typeof(T).Name}_Hub/{name}", timeout);
}
public static async Task<IActorRef> LookupAggregateHubActor<T>(this GridDomainNode node, TimeSpan? timeout = null)
where T : IAggregate
{
return await node.ResolveActor($"{typeof(T).Name}_Hub", timeout);
}
public static async Task KillAggregate<TAggregate>(this GridDomainNode node, string id, TimeSpan? timeout = null)
where TAggregate : Aggregate
{
IActorRef aggregateHubActor;
IActorRef aggregateActor;
try
{
aggregateHubActor = await node.LookupAggregateHubActor<TAggregate>(timeout);
aggregateActor = await node.LookupAggregateActor<TAggregate>(id, timeout);
}
catch (ActorNotFoundException)
{
return;
}
await ShutDownHubActor(node, id, aggregateActor, aggregateHubActor, timeout);
}
private static async Task ShutDownHubActor(GridDomainNode node, string id, IActorRef aggregateActor, IActorRef aggregateHubActor, TimeSpan? timeout=null)
{
using (var inbox = Inbox.Create(node.System))
{
inbox.Watch(aggregateActor);
aggregateHubActor.Tell(new ShutdownChild(id));
var msg = await inbox.ReceiveAsync(timeout ?? node.DefaultTimeout);
if (!(msg is Terminated))
throw new UnexpectedMessageExpection($"Expected {typeof(Terminated)} but got {msg}");
}
}
public static async Task KillProcessManager<TProcess, TState>(this GridDomainNode node, string id, TimeSpan? timeout = null)
where TState : IProcessState
{
var hub = await node.LookupProcessHubActor<TProcess>(timeout);
IActorRef processActor;
try
{
processActor = await node.LookupProcessActor<TProcess, TState>(id, timeout);
}
catch
{
return;
}
await ShutDownHubActor(node, id, processActor, hub, timeout);
var processStateHubActor = await node.ResolveActor($"{typeof(TState).Name}_Hub", timeout);
var processStateActor = await node.ResolveActor($"{typeof(TState).Name}_Hub/" + EntityActorName.New<ProcessStateAggregate<TState>>(id), timeout);
await ShutDownHubActor(node, id, processStateActor, processStateHubActor, timeout);
}
public static async Task<IActorRef> LookupProcessActor<TProcess, TData>(this GridDomainNode node,
string id,
TimeSpan? timeout = null) where TData : IProcessState
{
var name = EntityActorName.New<TProcess>(id).Name;
var type = typeof(TProcess).BeautyName();
return await node.ResolveActor($"{type}_Hub/{name}", timeout);
}
public static async Task<IActorRef> LookupProcessHubActor<TProcess>(this GridDomainNode node, TimeSpan? timeout = null)
{
return await node.ResolveActor($"{typeof(TProcess).BeautyName()}_Hub", timeout);
}
public static async Task<IActorRef> ResolveActor(this GridDomainNode node, string actorPath, TimeSpan? timeout = null)
{
return await node.System.ActorSelection("user/" + actorPath).ResolveOne(timeout ?? node.DefaultTimeout);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Drawing.Text;
using Xunit;
namespace System.Drawing.Tests
{
public class FontFamilyTests
{
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(GenericFontFamilies.Serif - 1, "Courier New")] // Value is outside the enum range.
[InlineData(GenericFontFamilies.Monospace + 1, "Courier New")] // Value is outside the enum range.
[InlineData(GenericFontFamilies.Monospace, "Courier New")]
[InlineData(GenericFontFamilies.SansSerif, "Microsoft Sans Serif")]
[InlineData(GenericFontFamilies.Serif, "Times New Roman")]
public void Ctor_GenericFamily(GenericFontFamilies genericFamily, string expectedName)
{
using (var fontFamily = new FontFamily(genericFamily))
{
Assert.Equal(expectedName, fontFamily.Name);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData("Courier New", "Courier New")]
[InlineData("Microsoft Sans Serif", "Microsoft Sans Serif")]
[InlineData("Times New Roman", "Times New Roman")]
[InlineData("times new roman", "Times New Roman")]
public void Ctor_Name(string name, string expectedName)
{
using (var fontFamily = new FontFamily(name))
{
Assert.Equal(expectedName, fontFamily.Name);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_Name_FontCollection()
{
using (var fontCollection = new PrivateFontCollection())
{
fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.otf"));
using (var fontFamily = new FontFamily("Code New Roman", fontCollection))
{
Assert.Equal("Code New Roman", fontFamily.Name);
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(null)]
[InlineData("NoSuchFont")]
[InlineData("Serif")]
public void Ctor_NoSuchFontName_ThrowsArgumentException(string name)
{
AssertExtensions.Throws<ArgumentException>(null, () => new FontFamily(name));
AssertExtensions.Throws<ArgumentException>(null, () => new FontFamily(name, null));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_NoSuchFontNameInCollection_ThrowsArgumentException()
{
using (var fontCollection = new PrivateFontCollection())
{
Assert.Throws<ArgumentException>(null, () => new FontFamily("Times New Roman", fontCollection));
}
}
public static IEnumerable<object[]> Equals_TestData()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
yield return new object[] { fontFamily, fontFamily, true };
yield return new object[] { FontFamily.GenericMonospace, FontFamily.GenericMonospace, true };
yield return new object[] { FontFamily.GenericMonospace, FontFamily.GenericSansSerif, false };
yield return new object[] { FontFamily.GenericSansSerif, new object(), false };
yield return new object[] { FontFamily.GenericSansSerif, null, false };
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Equals_TestData))]
public void Equals_Object_ReturnsExpected(FontFamily fontFamily, object other, bool expected)
{
try
{
Assert.Equal(expected, fontFamily.Equals(other));
}
finally
{
fontFamily.Dispose();
(other as IDisposable)?.Dispose();
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Families_Get_ReturnsExpected()
{
#pragma warning disable 0618 // FontFamily.GetFamilies is deprecated.
using (var image = new Bitmap(10, 10))
using (var graphics = Graphics.FromImage(image))
{
FontFamily[] families = FontFamily.Families;
FontFamily[] familiesWithGraphics = FontFamily.GetFamilies(graphics);
// FontFamily.Equals uses the native handle to determine equality. However, GDI+ does not always
// cache handles, so we cannot just Assert.Equal(families, familiesWithGraphics);
Assert.Equal(families.Length, familiesWithGraphics.Length);
for (int i = 0; i < families.Length; i++)
{
Assert.Equal(families[i].Name, familiesWithGraphics[i].Name);
}
foreach (FontFamily fontFamily in families)
{
using (FontFamily copy = new FontFamily(fontFamily.Name))
{
Assert.Equal(fontFamily.Name, copy.Name);
}
}
}
#pragma warning restore 0618
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GenericMonospace_Get_ReturnsExpected()
{
using (FontFamily fontFamily1 = FontFamily.GenericMonospace)
{
using (FontFamily fontFamily2 = FontFamily.GenericMonospace)
{
Assert.NotSame(fontFamily1, fontFamily2);
Assert.Equal("Courier New", fontFamily2.Name);
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GenericSansSerif_Get_ReturnsExpected()
{
using (FontFamily fontFamily1 = FontFamily.GenericSansSerif)
{
using (FontFamily fontFamily2 = FontFamily.GenericSansSerif)
{
Assert.NotSame(fontFamily1, fontFamily2);
Assert.Equal("Microsoft Sans Serif", fontFamily2.Name);
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GenericSerif_Get_ReturnsExpected()
{
using (FontFamily fontFamily1 = FontFamily.GenericSerif)
{
using (FontFamily fontFamily2 = FontFamily.GenericSerif)
{
Assert.NotSame(fontFamily1, fontFamily2);
Assert.Equal("Times New Roman", fontFamily2.Name);
}
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetFamilies_NullGraphics_ThrowsArgumentNullException()
{
#pragma warning disable 0618 // FontFamily.GetFamilies is deprecated.
AssertExtensions.Throws<ArgumentNullException>("graphics", () => FontFamily.GetFamilies(null));
#pragma warning restore 0618
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetHashCode_Invoke_ReturnsNameHashCode()
{
using (FontFamily fontFamily = FontFamily.GenericSansSerif)
{
Assert.Equal(fontFamily.GetName(0).GetHashCode(), fontFamily.GetHashCode());
}
}
public static IEnumerable<object[]> FontStyle_TestData()
{
yield return new object[] { FontStyle.Bold };
yield return new object[] { FontStyle.Italic };
yield return new object[] { FontStyle.Regular };
yield return new object[] { FontStyle.Strikeout };
yield return new object[] { FontStyle.Strikeout };
yield return new object[] { FontStyle.Regular - 1 };
yield return new object[] { FontStyle.Strikeout + 1 };
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(FontStyle_TestData))]
public void FontFamilyProperties_CustomFont_ReturnsExpected(FontStyle style)
{
using (var fontCollection = new PrivateFontCollection())
{
fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.otf"));
using (var fontFamily = new FontFamily("Code New Roman", fontCollection))
{
Assert.True(fontFamily.IsStyleAvailable(style));
Assert.Equal(1884, fontFamily.GetCellAscent(style));
Assert.Equal(514, fontFamily.GetCellDescent(style));
Assert.Equal(2048, fontFamily.GetEmHeight(style));
Assert.Equal(2398, fontFamily.GetLineSpacing(style));
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void IsStyleAvailable_Disposed_ThrowsArgumentException()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => fontFamily.IsStyleAvailable(FontStyle.Italic));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetEmHeight_Disposed_ThrowsArgumentException()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => fontFamily.GetEmHeight(FontStyle.Italic));
}
private const int FrenchLCID = 1036;
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(-1, "Code New Roman")]
[InlineData(0, "Code New Roman")]
[InlineData(int.MaxValue, "Code New Roman")]
// This font has been modified to change the name to "Bonjour" if the language is French.
[InlineData(FrenchLCID, "Bonjour")]
public void GetName_LanguageCode_ReturnsExpected(int languageCode, string expectedName)
{
using (var fontCollection = new PrivateFontCollection())
{
fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.ttf"));
using (var fontFamily = new FontFamily("Code New Roman", fontCollection))
{
Assert.Equal(expectedName, fontFamily.GetName(languageCode));
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetName_Disposed_ThrowsArgumentException()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => fontFamily.GetName(0));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetCellAscent_Disposed_ThrowsArgumentException()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => fontFamily.GetCellAscent(FontStyle.Italic));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetCellDescent_Disposed_ThrowsArgumentException()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => fontFamily.GetCellDescent(FontStyle.Italic));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetLineSpacing_Disposed_ThrowsArgumentException()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => fontFamily.GetLineSpacing(FontStyle.Italic));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Dispose_MultipleTimes_Nop()
{
FontFamily fontFamily = FontFamily.GenericMonospace;
fontFamily.Dispose();
fontFamily.Dispose();
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using FluentAssertions;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using LocalizableStrings = Microsoft.DotNet.Tools.Publish.LocalizableStrings;
namespace Microsoft.DotNet.Cli.Publish.Tests
{
public class GivenDotnetPublishPublishesProjects : TestBase
{
[Fact]
public void ItPublishesARunnablePortableApp()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new PublishCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("--framework netcoreapp3.0")
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
var outputDll = Path.Combine(testProjectDirectory, "bin", configuration, "netcoreapp3.0", "publish", $"{testAppName}.dll");
new DotnetCommand()
.ExecuteWithCapturedOutput(outputDll)
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItImplicitlyRestoresAProjectWhenPublishing()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new PublishCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("--framework netcoreapp3.0")
.Should().Pass();
}
[Fact]
public void ItCanPublishAMultiTFMProjectWithImplicitRestore()
{
var testInstance = TestAssets.Get(
TestAssetKinds.DesktopTestProjects,
"NETFrameworkReferenceNETStandard20")
.CreateInstance()
.WithSourceFiles();
string projectDirectory = Path.Combine(testInstance.Root.FullName, "MultiTFMTestApp");
new PublishCommand()
.WithWorkingDirectory(projectDirectory)
.Execute("--framework netcoreapp3.0")
.Should().Pass();
}
[Fact]
public void ItDoesNotImplicitlyRestoreAProjectWhenPublishingWithTheNoRestoreOption()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new PublishCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--framework netcoreapp3.0 --no-restore")
.Should().Fail()
.And.HaveStdOutContaining("project.assets.json");
}
[Theory]
[InlineData(null)]
[InlineData("--self-contained")]
[InlineData("--self-contained=true")]
public void ItPublishesSelfContainedWithRid(string args)
{
var testAppName = "MSBuildTestApp";
var rid = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var outputDirectory = PublishApp(testAppName, rid, args);
var outputProgram = Path.Combine(outputDirectory.FullName, $"{testAppName}{Constants.ExeSuffix}");
new TestCommand(outputProgram)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Theory]
[InlineData("--self-contained=false")]
public void ItPublishesFrameworkDependentWithRid(string args)
{
var testAppName = "MSBuildTestApp";
var rid = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var outputDirectory = PublishApp(testAppName, rid, args);
outputDirectory.Should().OnlyHaveFiles(new[] {
$"{testAppName}{Constants.ExeSuffix}",
$"{testAppName}.dll",
$"{testAppName}.pdb",
$"{testAppName}.deps.json",
$"{testAppName}.runtimeconfig.json",
});
var outputProgram = Path.Combine(outputDirectory.FullName, $"{testAppName}{Constants.ExeSuffix}");
var command = new TestCommand(outputProgram);
command.Environment[Environment.Is64BitProcess ? "DOTNET_ROOT" : "DOTNET_ROOT(x86)"] =
new RepoDirectoriesProvider().DotnetRoot;
command.ExecuteWithCapturedOutput()
.Should()
.Pass()
.And
.HaveStdOutContaining("Hello World");
}
[Theory]
[InlineData("--self-contained=false")]
[InlineData(null)]
public void ItPublishesFrameworkDependentWithoutRid(string args)
{
var testAppName = "MSBuildTestApp";
var outputDirectory = PublishApp(testAppName, rid: null, args: args);
outputDirectory.Should().OnlyHaveFiles(new[] {
$"{testAppName}{Constants.ExeSuffix}",
$"{testAppName}.dll",
$"{testAppName}.pdb",
$"{testAppName}.deps.json",
$"{testAppName}.runtimeconfig.json",
});
new DotnetCommand()
.ExecuteWithCapturedOutput(Path.Combine(outputDirectory.FullName, $"{testAppName}.dll"))
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
private DirectoryInfo PublishApp(string testAppName, string rid, string args = null)
{
var testInstance = TestAssets.Get(testAppName)
.CreateInstance($"PublishApp_{rid ?? "none"}_{args ?? "none"}")
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root;
new PublishCommand()
.WithRuntime(rid)
.WithWorkingDirectory(testProjectDirectory)
.Execute(args ?? "")
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
return testProjectDirectory
.GetDirectory("bin", configuration, "netcoreapp3.0", rid ?? "", "publish");
}
[Fact]
public void ItPublishesAppWhenRestoringToSpecificPackageDirectory()
{
string dir = "pkgs";
string args = $"--packages {dir}";
var testInstance = TestAssets.Get("TestAppSimple")
.CreateInstance()
.WithSourceFiles();
var rootDir = testInstance.Root;
new RestoreCommand()
.WithWorkingDirectory(rootDir)
.Execute(args)
.Should()
.Pass();
new PublishCommand()
.WithWorkingDirectory(rootDir)
.ExecuteWithCapturedOutput("--no-restore")
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
var outputProgram = rootDir
.GetDirectory("bin", configuration, "netcoreapp3.0", "publish", $"{rootDir.Name}.dll")
.FullName;
new TestCommand(outputProgram)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItFailsToPublishWithNoBuildIfNotPreviouslyBuilt()
{
var testInstance = TestAssets.Get("TestAppSimple")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles(); // note implicit restore here
var rootPath = testInstance.Root;
new PublishCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput("--no-build")
.Should()
.Fail()
.And.HaveStdOutContaining("MSB3030"); // "Could not copy ___ because it was not found."
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ItPublishesSuccessfullyWithNoBuildIfPreviouslyBuilt(bool selfContained)
{
var testInstance = TestAssets.Get("TestAppSimple")
.CreateInstance(nameof(ItPublishesSuccessfullyWithNoBuildIfPreviouslyBuilt) + selfContained)
.WithSourceFiles();
var rootPath = testInstance.Root;
var rid = selfContained ? DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier() : "";
var ridArg = selfContained ? $"-r {rid}" : "";
new BuildCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput(ridArg)
.Should()
.Pass();
new PublishCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput($"{ridArg} --no-build")
.Should()
.Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
var outputProgram = rootPath
.GetDirectory("bin", configuration, "netcoreapp3.0", rid, "publish", $"{rootPath.Name}.dll")
.FullName;
new TestCommand(outputProgram)
.ExecuteWithCapturedOutput()
.Should()
.Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItFailsToPublishWithNoBuildIfPreviouslyBuiltWithoutRid()
{
var testInstance = TestAssets.Get("TestAppSimple")
.CreateInstance()
.WithSourceFiles();
var rootPath = testInstance.Root;
new BuildCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput()
.Should()
.Pass();
new PublishCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput("-r win-x64 --no-build")
.Should()
.Fail();
}
}
}
| |
/* ====================================================================
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.Generic;
using System.Collections.ObjectModel;
using NPOI.SS.Formula.Function;
namespace NPOI.SS.Formula.Atp
{
using System;
using System.Collections;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Udf;
public class NotImplemented : FreeRefFunction
{
private String _functionName;
public NotImplemented(String functionName)
{
_functionName = functionName;
}
public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
{
throw new NotImplementedException(_functionName);
}
};
public class AnalysisToolPak : UDFFinder
{
public static UDFFinder instance = new AnalysisToolPak();
private static Hashtable _functionsByName = CreateFunctionsMap();
private AnalysisToolPak()
{
// no instances of this class
}
public override FreeRefFunction FindFunction(String name)
{
// functions that are available in Excel 2007+ have a prefix _xlfn.
// if you save such a .xlsx workbook as .xls
if (name.StartsWith("_xlfn.")) name = name.Substring(6);
return (FreeRefFunction)_functionsByName[name.ToUpper()];
}
private static Hashtable CreateFunctionsMap()
{
Hashtable m = new Hashtable(100);
r(m, "ACCRINT", null);
r(m, "ACCRINTM", null);
r(m, "AMORDEGRC", null);
r(m, "AMORLINC", null);
r(m, "AVERAGEIF", null);
r(m, "AVERAGEIFS", null);
r(m, "BAHTTEXT", null);
r(m, "BESSELI", null);
r(m, "BESSELJ", null);
r(m, "BESSELK", null);
r(m, "BESSELY", null);
r(m, "BIN2DEC", null);
r(m, "BIN2HEX", null);
r(m, "BIN2OCT", null);
r(m, "COMPLEX", null);
r(m, "CONVERT", null);
r(m, "COUNTIFS", null);
r(m, "COUPDAYBS", null);
r(m, "COUPDAYS", null);
r(m, "COUPDAYSNC", null);
r(m, "COUPNCD", null);
r(m, "COUPNUM", null);
r(m, "COUPPCD", null);
r(m, "CUBEKPIMEMBER", null);
r(m, "CUBEMEMBER", null);
r(m, "CUBEMEMBERPROPERTY", null);
r(m, "CUBERANKEDMEMBER", null);
r(m, "CUBESET", null);
r(m, "CUBESETCOUNT", null);
r(m, "CUBEVALUE", null);
r(m, "CUMIPMT", null);
r(m, "CUMPRINC", null);
r(m, "DEC2BIN", null);
r(m, "DEC2HEX", null);
r(m, "DEC2OCT", null);
r(m, "DELTA", null);
r(m, "DISC", null);
r(m, "DOLLARDE", null);
r(m, "DOLLARFR", null);
r(m, "DURATION", null);
r(m, "EDATE", EDate.Instance);
r(m, "EFFECT", null);
r(m, "EOMONTH", null);
r(m, "ERF", null);
r(m, "ERFC", null);
r(m, "FACTDOUBLE", null);
r(m, "FVSCHEDULE", null);
r(m, "GCD", null);
r(m, "GESTEP", null);
r(m, "HEX2BIN", null);
r(m, "HEX2DEC", null);
r(m, "HEX2OCT", null);
r(m, "IFERROR", IfError.Instance);
r(m, "IMABS", null);
r(m, "IMAGINARY", null);
r(m, "IMARGUMENT", null);
r(m, "IMCONJUGATE", null);
r(m, "IMCOS", null);
r(m, "IMDIV", null);
r(m, "IMEXP", null);
r(m, "IMLN", null);
r(m, "IMLOG10", null);
r(m, "IMLOG2", null);
r(m, "IMPOWER", null);
r(m, "IMPRODUCT", null);
r(m, "IMREAL", null);
r(m, "IMSIN", null);
r(m, "IMSQRT", null);
r(m, "IMSUB", null);
r(m, "IMSUM", null);
r(m, "INTRATE", null);
r(m, "ISEVEN", ParityFunction.IS_EVEN);
r(m, "ISODD", ParityFunction.IS_ODD);
r(m, "JIS", null);
r(m, "LCM", null);
r(m, "MDURATION", null);
r(m, "MROUND", MRound.Instance);
r(m, "MULTINOMIAL", null);
r(m, "NETWORKDAYS", NetworkdaysFunction.instance);
r(m, "NOMINAL", null);
r(m, "OCT2BIN", null);
r(m, "OCT2DEC", null);
r(m, "OCT2HEX", null);
r(m, "ODDFPRICE", null);
r(m, "ODDFYIELD", null);
r(m, "ODDLPRICE", null);
r(m, "ODDLYIELD", null);
r(m, "PRICE", null);
r(m, "PRICEDISC", null);
r(m, "PRICEMAT", null);
r(m, "QUOTIENT", null);
r(m, "RANDBETWEEN", RandBetween.Instance);
r(m, "RECEIVED", null);
r(m, "RTD", null);
r(m, "SERIESSUM", null);
r(m, "SQRTPI", null);
r(m, "SUMIFS", Sumifs.instance);
r(m, "TBILLEQ", null);
r(m, "TBILLPRICE", null);
r(m, "TBILLYIELD", null);
r(m, "WEEKNUM", null);
r(m, "WORKDAY", WorkdayFunction.instance);
r(m, "XIRR", null);
r(m, "XNPV", null);
r(m, "YEARFRAC", YearFrac.instance);
r(m, "YIELD", null);
r(m, "YIELDDISC", null);
r(m, "YIELDMAT", null);
return m;
}
private static void r(Hashtable m, String functionName, FreeRefFunction pFunc)
{
FreeRefFunction func = pFunc == null ? new NotImplemented(functionName) : pFunc;
m[functionName] = func;
}
public static bool IsATPFunction(String name)
{
//AnalysisToolPak inst = (AnalysisToolPak)instance;
return AnalysisToolPak._functionsByName.ContainsKey(name);
}
/**
* Returns a collection of ATP function names implemented by POI.
*
* @return an array of supported functions
* @since 3.8 beta6
*/
public static ReadOnlyCollection<String> GetSupportedFunctionNames()
{
AnalysisToolPak inst = (AnalysisToolPak)instance;
List<String> lst = new List<String>();
foreach (String name in AnalysisToolPak._functionsByName.Keys)
{
FreeRefFunction func = (FreeRefFunction)AnalysisToolPak._functionsByName[(name)];
if (func != null && !(func is NotImplemented))
{
lst.Add(name);
}
}
return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst);
}
/**
* Returns a collection of ATP function names NOT implemented by POI.
*
* @return an array of not supported functions
* @since 3.8 beta6
*/
public static ReadOnlyCollection<String> GetNotSupportedFunctionNames()
{
AnalysisToolPak inst = (AnalysisToolPak)instance;
List<String> lst = new List<String>();
foreach (String name in AnalysisToolPak._functionsByName.Keys)
{
FreeRefFunction func = (FreeRefFunction)AnalysisToolPak._functionsByName[(name)];
if (func != null && (func is NotImplemented))
{
lst.Add(name);
}
}
return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst);
}
/**
* Register a ATP function in runtime.
*
* @param name the function name
* @param func the functoin to register
* @throws ArgumentException if the function is unknown or already registered.
* @since 3.8 beta6
*/
public static void RegisterFunction(String name, FreeRefFunction func)
{
AnalysisToolPak inst = (AnalysisToolPak)instance;
if (!IsATPFunction(name))
{
FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByName(name);
if (metaData != null)
{
throw new ArgumentException(name + " is a built-in Excel function. " +
"Use FunctoinEval.RegisterFunction(String name, Function func) instead.");
}
else
{
throw new ArgumentException(name + " is not a function from the Excel Analysis Toolpack.");
}
}
FreeRefFunction f = inst.FindFunction(name);
if (f != null && !(f is NotImplemented))
{
throw new ArgumentException("POI already implememts " + name +
". You cannot override POI's implementations of Excel functions");
}
if (_functionsByName.ContainsKey(name))
_functionsByName[name] = func;
else
_functionsByName.Add(name, func);
}
}
}
| |
// 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;
public class Test
{
public Boolean runTest()
{
TestLibrary.Logging.WriteLine( "parse testing started." );
bool passing = true;
try
{
//input is null
passing &= VerifyParseException(null, typeof(ArgumentNullException), false);
//input is empty
passing &= VerifyParseException(String.Empty, typeof(ArgumentException), false);
//input is whitespace
passing &= VerifyParseException(" ", typeof(ArgumentException), false);
//input has 1 component
passing &= VerifyParseException("1234", typeof(ArgumentException), false);
//input has 5 components
passing &= VerifyParseException("123.123.123.324.543", typeof(ArgumentException), false);
//input has a negative component
passing &= NormalCasesException("-123", typeof(ArgumentOutOfRangeException), false);
//component > Int32
passing &= NormalCasesException((((long)Int32.MaxValue) + 1).ToString("d"), typeof(OverflowException), false);
//component has extra whitespace (internal and external)
passing &= NormalCases(" 123");
passing &= NormalCases("123 ");
passing &= NormalCases(" 123 ");
passing &= NormalCasesException("1 23", typeof(FormatException), false);
//component in hex format
passing &= NormalCasesException("0x123", typeof(FormatException), false);
//component in exp format
passing &= NormalCasesException("12e2", typeof(FormatException), false);
//component has leading sign
passing &= NormalCases("+123");
//component has trailing sign
passing &= NormalCasesException("123+", typeof(FormatException), false);
passing &= NormalCasesException("123-", typeof(FormatException), false);
//component has commas
passing &= NormalCasesException("12,345", typeof(FormatException), false);
//component has hex chars
passing &= NormalCasesException("ac", typeof(FormatException), false);
//component has non-digit
passing &= NormalCasesException("12v3", typeof(FormatException), false);
passing &= NormalCasesException("12^3", typeof(FormatException), false);
passing &= NormalCasesException("12#3", typeof(FormatException), false);
passing &= NormalCasesException("1*23", typeof(FormatException), false);
//component has wrong seperator
passing &= VerifyParseException("123,123,123,324", typeof(ArgumentException), false);
passing &= VerifyParseException("123:123:123:324", typeof(ArgumentException), false);
passing &= VerifyParseException("123;123;123;324", typeof(ArgumentException), false);
passing &= VerifyParseException("123-123-123-324", typeof(ArgumentException), false);
passing &= VerifyParseException("123 123 123 324", typeof(ArgumentException), false);
//added "V" at start
passing &= VerifyParseException("V123.123.123.324", typeof(FormatException), false);
passing &= VerifyParseException("v123.123.123.324", typeof(FormatException), false);
//normal case
passing &= VerifyParse("123.123");
passing &= VerifyParse("123.123.123");
passing &= VerifyParse("123.123.123.123");
//valid 0 case
passing &= NormalCases("0");
passing &= VerifyParse("0.0.0.0");
//Int32.MaxValue cases
passing &= NormalCases(Int32.MaxValue.ToString("d"));
}
catch(Exception exc_general)
{
TestLibrary.Logging.WriteLine("Error: Unexpected Exception: {0}", exc_general);
passing = false;
}
if (passing)
{
TestLibrary.Logging.WriteLine("Passed!");
}
else
{
TestLibrary.Logging.WriteLine( "Failed!" );
}
return passing;
}
private bool NormalCasesException(string input, Type exceptionType, bool tryThrows)
{
bool passing = true;
passing &= VerifyParseException(String.Format("{0}.123", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.{0}", input), exceptionType, false);
passing &= VerifyParseException(String.Format("{0}.123.123", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.{0}.123", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.123.{0}", input), exceptionType, false);
passing &= VerifyParseException(String.Format("{0}.123.123.324", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.{0}.123.324", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.123.{0}.324", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.123.123.{0}", input), exceptionType, false);
return passing;
}
private bool VerifyParseException(string input, Type exceptionType, bool tryThrows)
{
bool result = true;
TestLibrary.Logging.WriteLine("");
TestLibrary.Logging.WriteLine("Testing input: \"{0}\"", input);
try
{
try
{
Version.Parse(input);
TestLibrary.Logging.WriteLine("Version.Parse:: Expected Exception not thrown.");
result = false;
}
catch (Exception e)
{
if (e.GetType() != exceptionType)
{
TestLibrary.Logging.WriteLine("Version.Parse:: Wrong Exception thrown: Expected:{0} Got:{1}", exceptionType, e);
result = false;
}
}
Version test;
if (tryThrows)
{
try
{
Version.TryParse(input, out test);
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected Exception not thrown.");
result = false;
}
catch (Exception e)
{
if (e.GetType() != exceptionType)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Wrong Exception thrown: Expected:{0} Got:{1}", exceptionType, e);
result = false;
}
}
}
else
{
bool rVal;
rVal = Version.TryParse(input, out test);
if (rVal)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected failure parsing, got true return value.");
result = false;
}
if (!IsDefaultVersion(test))
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected null, got {0} value.", test);
result = false;
}
}
}
catch (Exception exc)
{
TestLibrary.Logging.WriteLine("Unexpected exception for input: \"{0}\" exception: {1}", input, exc);
result = false;
}
if (!result)
{
TestLibrary.Logging.WriteLine("Incorrect result for input: \"{0}\"", input);
}
return result;
}
private bool NormalCases(string input)
{
bool passing = true;
passing &= VerifyParse(String.Format("{0}.123", input));
passing &= VerifyParse(String.Format("123.{0}", input));
passing &= VerifyParse(String.Format("{0}.123.123", input));
passing &= VerifyParse(String.Format("123.{0}.123", input));
passing &= VerifyParse(String.Format("123.123.{0}", input));
passing &= VerifyParse(String.Format("{0}.123.123.324", input));
passing &= VerifyParse(String.Format("123.{0}.123.324", input));
passing &= VerifyParse(String.Format("123.123.{0}.324", input));
passing &= VerifyParse(String.Format("123.123.123.{0}", input));
return passing;
}
private bool VerifyParse(string input)
{
bool result = true;
TestLibrary.Logging.WriteLine("");
TestLibrary.Logging.WriteLine("Testing input: \"{0}\"", input);
try
{
String[] parts = input.Split('.');
int major = Int32.Parse(parts[0]);
int minor = Int32.Parse(parts[1]);
int build = 0;
int revision = 0;
if (parts.Length > 2) build = Int32.Parse(parts[2]);
if (parts.Length > 3) revision = Int32.Parse(parts[3]);
Version expected = null;
if (parts.Length == 2) expected = new Version(major, minor);
if (parts.Length == 3) expected = new Version(major, minor, build);
if (parts.Length > 3) expected = new Version(major, minor, build, revision);
Version test;
try
{
test = Version.Parse(input);
if (test.CompareTo(expected) != 0)
{
TestLibrary.Logging.WriteLine("Version.Parse:: Expected Result. Expected {0}, Got {1}", expected, test);
result = false;
}
}
catch (Exception e)
{
TestLibrary.Logging.WriteLine("Version.Parse:: Unexpected Exception thrown: {0}", e);
result = false;
}
try
{
bool rVal;
rVal = Version.TryParse(input, out test);
if (!rVal)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected no failure parsing, got false return value.");
result = false;
}
if (test.CompareTo(expected) != 0)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected {0}, Got {1}", expected, test);
result = false;
}
}
catch (Exception e)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Unexpected Exception thrown: {0}", e);
result = false;
}
}
catch (Exception exc)
{
TestLibrary.Logging.WriteLine("Unexpected exception for input: \"{0}\" exception:{1}", input, exc);
result = false;
}
if (!result)
{
TestLibrary.Logging.WriteLine("Incorrect result for input: \"{0}\"", input);
}
return result;
}
private bool IsDefaultVersion(Version input)
{
bool ret = false;
if (input == null)
{
ret = true;
}
return ret;
//use to return Version of 0.0.0.0 on failure - now returning null.
//return (input.CompareTo(new Version()) == 0);
}
public static int Main(String[] args)
{
Boolean bResult = false;
Test test = new Test();
try
{
bResult = test.runTest();
}
catch (Exception exc)
{
bResult = false;
TestLibrary.Logging.WriteLine("Unexpected Exception thrown: {0}", exc);
}
if (bResult == false) return 1;
return 100;
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// Represents an intrinsic debugger method with byref return type.
/// </summary>
internal sealed class PlaceholderMethodSymbol : MethodSymbol, Cci.ISignature
{
internal delegate ImmutableArray<TypeParameterSymbol> GetTypeParameters(PlaceholderMethodSymbol method);
internal delegate ImmutableArray<ParameterSymbol> GetParameters(PlaceholderMethodSymbol method);
internal delegate TypeSymbol GetReturnType(PlaceholderMethodSymbol method);
private readonly NamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly TypeSymbol _returnType;
private readonly ImmutableArray<ParameterSymbol> _parameters;
internal PlaceholderMethodSymbol(
NamedTypeSymbol container,
string name,
GetTypeParameters getTypeParameters,
GetReturnType getReturnType,
GetParameters getParameters)
{
_container = container;
_name = name;
_typeParameters = getTypeParameters(this);
_returnType = getReturnType(this);
_parameters = getParameters(this);
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override bool ReturnsVoid
{
get { return false; }
}
public override TypeSymbol ReturnType
{
get { return _returnType; }
}
bool Cci.ISignature.ReturnValueIsByRef
{
get { return true; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
return this.IsGenericMethod ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using Microsoft.Win32;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Color = System.Windows.Media.Color;
namespace Gearset.Components.Logger {
public sealed class LoggerManager : Gear {
readonly StreamItem _defaultStream;
readonly SolidColorBrush[] _colors = {
new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)),
new SolidColorBrush(Color.FromArgb(255, 128, 200, 200)),
new SolidColorBrush(Color.FromArgb(255, 200, 200, 128)),
new SolidColorBrush(Color.FromArgb(255, 200, 128, 200)),
new SolidColorBrush(Color.FromArgb(255, 128, 128, 200)),
new SolidColorBrush(Color.FromArgb(255, 128, 200, 128)),
new SolidColorBrush(Color.FromArgb(255, 200, 128, 128)),
new SolidColorBrush(Color.FromArgb(255, 150, 110, 110)),
new SolidColorBrush(Color.FromArgb(255, 110, 150, 110)),
new SolidColorBrush(Color.FromArgb(255, 110, 110, 150)),
new SolidColorBrush(Color.FromArgb(255, 150, 150, 110)),
new SolidColorBrush(Color.FromArgb(255, 150, 110, 150)),
new SolidColorBrush(Color.FromArgb(255, 110, 150, 150))
};
readonly ScrollViewer _scrollViewer;
KeyboardState _prevKbs;
int _currentColor;
internal ObservableCollection<StreamItem> Streams;
internal FixedLengthQueue<LogItem> LogItems;
internal FixedLengthQueue<LogItem> LogItemsOld;
internal ICollectionView FilteredView;
bool _locationJustChanged;
public LoggerManager()
: base(GearsetSettings.Instance.LoggerConfig) {
// Create the back-end collections
Streams = new ObservableCollection<StreamItem>();
LogItems = new FixedLengthQueue<LogItem>(500);
LogItemsOld = new FixedLengthQueue<LogItem>(10000);
//LogItems.DequeueTarget = LogItemsOld;
Streams.Add(_defaultStream = new StreamItem { Name = "Default", Enabled = true, Color = _colors[_currentColor++] });
// Create the window.
Window = new LoggerWindow();
Window.Top = Config.Top;
Window.Left = Config.Left;
Window.Width = Config.Width;
Window.Height = Config.Height;
Window.IsVisibleChanged += logger_IsVisibleChanged;
Window.SoloRequested += logger_SoloRequested;
WindowHelper.EnsureOnScreen(Window);
if (Config.Visible)
Window.Show();
FilteredView = CollectionViewSource.GetDefaultView(LogItems);
FilteredView.Filter = a => ((LogItem)a).Stream.Enabled;
FilteredView.GroupDescriptions.Add(new PropertyGroupDescription("UpdateNumber"));
Window.LogListBox.DataContext = FilteredView;
Window.StreamListBox.DataContext = Streams;
Window.LocationChanged += logger_LocationChanged;
Window.SizeChanged += logger_SizeChanged;
_scrollViewer = GetDescendantByType(Window.LogListBox, typeof(ScrollViewer)) as ScrollViewer;
}
internal LoggerWindow Window { get; private set; }
//private Brush[] BackBrushes = new Brush[2];
public LoggerConfig Config { get { return GearsetSettings.Instance.LoggerConfig; } }
void logger_SoloRequested(object sender, SoloRequestedEventArgs e) {
foreach (var stream in Streams) {
if (stream != e.StreamItem)
stream.Enabled = false;
else
stream.Enabled = true;
}
}
void logger_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) {
Config.Visible = Window.IsVisible;
}
protected override void OnVisibleChanged() {
if (Window != null)
Window.Visibility = Visible ? Visibility.Visible : Visibility.Hidden;
}
void logger_SizeChanged(object sender, SizeChangedEventArgs e) {
_locationJustChanged = true;
}
void logger_LocationChanged(object sender, EventArgs e) {
_locationJustChanged = true;
}
public override void Update(GameTime gameTime) {
var kbs = Keyboard.GetState();
if (_locationJustChanged) {
_locationJustChanged = false;
Config.Top = Window.Top;
Config.Left = Window.Left;
Config.Width = Window.Width;
Config.Height = Window.Height;
}
if (kbs.IsKeyDown(Keys.LeftControl) && kbs.IsKeyDown(Keys.F7) && _prevKbs.IsKeyUp(Keys.F7)) {
if (Window.IsVisible)
Window.Hide();
else {
Window.Show();
}
}
_prevKbs = kbs;
}
public void EnableAllStreams() {
foreach (var stream in Streams)
stream.Enabled = true;
}
public void DisableAllStreams() {
foreach (var stream in Streams)
stream.Enabled = false;
}
/// <summary>
/// Shows a dialog asking for a filename and saves the log file.
/// </summary>
public void SaveLogToFile() {
// Configure save file dialog box
var dlg = new SaveFileDialog();
dlg.FileName = ""; // Default file name
dlg.DefaultExt = ".log"; // Default file extension
dlg.Filter = "Log files (.log)|*.log"; // Filter files by extension
// Show save file dialog box
var result = dlg.ShowDialog();
// Process save file dialog box results
if (result != true) {
return;
}
// Generate the log file.
SaveLogToFile(dlg.FileName);
}
/// <summary>
/// Saves the log to the specified file.
/// </summary>
/// <param name="filename">Name of the file to save the log (usually ending in .log)</param>
public void SaveLogToFile(string filename) {
// Generate the log file.
using (TextWriter t = new StreamWriter(filename)) {
var updateNumber = -1;
var maxStreamNameSize = 0;
foreach (var item in Streams)
if (item.Name.Length > maxStreamNameSize)
maxStreamNameSize = item.Name.Length;
// Store old items (not shown in the Logger window).
foreach (var item in LogItemsOld) {
if (item.UpdateNumber > updateNumber) {
t.WriteLine("Update " + item.UpdateNumber);
updateNumber = item.UpdateNumber;
}
t.WriteLine(item.Stream.Name.PadLeft(maxStreamNameSize) + " | " + item.Content);
}
// Store last n items (shown in the logger window).
foreach (var item in LogItems) {
if (item.UpdateNumber > updateNumber) {
t.WriteLine("Update " + item.UpdateNumber);
updateNumber = item.UpdateNumber;
}
t.WriteLine(item.Stream.Name.PadLeft(maxStreamNameSize) + " | " + item.Content);
}
t.Close();
}
}
StreamItem SearchStream(String name) {
foreach (var streamItem in Streams) {
if (streamItem.Name == name)
return streamItem;
}
return null;
}
/// <summary>
/// Logs a formatted string to the specified stream.
/// </summary>
/// <param name="streamName">Stream to log to</param>
/// <param name="format">The format string</param>
/// <param name="arg0">The first format parameter</param>
public void Log(String streamName, String format, Object arg0) {
Log(streamName, String.Format(format, arg0));
}
/// <summary>
/// Logs a formatted string to the specified stream.
/// </summary>
/// <param name="streamName">Stream to log to</param>
/// <param name="format">The format string</param>
/// <param name="arg0">The first format parameter</param>
/// <param name="arg1">The second format parameter</param>
public void Log(String streamName, String format, Object arg0, Object arg1) {
Log(streamName, String.Format(format, arg0, arg1));
}
/// <summary>
/// Logs a formatted string to the specified stream.
/// </summary>
/// <param name="streamName">Stream to log to</param>
/// <param name="format">The format string</param>
/// <param name="arg0">The first format parameter</param>
/// <param name="arg1">The second format parameter</param>
/// <param name="arg2">The third format parameter</param>
public void Log(String streamName, String format, Object arg0, Object arg1, Object arg2) {
Log(streamName, String.Format(format, arg0, arg1, arg2));
}
/// <summary>
/// Logs a formatted string to the specified stream.
/// </summary>
/// <param name="streamName">Stream to log to</param>
/// <param name="format">The format string</param>
/// <param name="arg0">The format parameters</param>
public void Log(String streamName, String format, params Object[] args) {
Log(streamName, String.Format(format, args));
}
/// <summary>
/// Los a message to the specified stream.
/// </summary>
/// <param name="streamName">Name of the Stream to log the message to</param>
/// <param name="message">Message to log</param>
public void Log(String streamName, String message) {
var stream = SearchStream(streamName);
// Is it a new stream?
if (stream == null) {
stream = new StreamItem {
Enabled = !Config.HiddenStreams.Contains(streamName),
Name = streamName,
Color = _colors[(_currentColor++)]
};
stream.PropertyChanged += stream_PropertyChanged;
Streams.Add(stream);
// Repeat the colors.
if (_currentColor >= _colors.Length)
_currentColor = 0;
}
// Log even if the stream is disabled.
var logItem = new LogItem { Stream = stream, Content = message, UpdateNumber = GearsetResources.Console.UpdateCount };
LogItems.Enqueue(logItem);
if (stream.Enabled)
_scrollViewer.ScrollToEnd();
}
/// <summary>
/// Logs the specified message in the default stream.
/// </summary>
/// <param name="content">The message to log.</param>
public void Log(String message) {
LogItems.Enqueue(new LogItem { Stream = _defaultStream, Content = message, UpdateNumber = GearsetResources.Console.UpdateCount });
}
static Visual GetDescendantByType(Visual element, Type type) {
if (element == null)
return null;
if (element.GetType() == type)
return element;
Visual foundElement = null;
if (element is FrameworkElement) {
(element as FrameworkElement).ApplyTemplate();
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) {
var visual = VisualTreeHelper.GetChild(element, i) as Visual;
foundElement = GetDescendantByType(visual, type);
if (foundElement != null)
break;
}
return foundElement;
}
void stream_PropertyChanged(object sender, PropertyChangedEventArgs e) {
FilteredView.Refresh();
if (e.PropertyName == "Enabled") {
var stream = sender as StreamItem;
if (stream == null)
return;
if (stream.Enabled && Config.HiddenStreams.Contains(stream.Name))
Config.HiddenStreams.Remove(stream.Name);
else if (!stream.Enabled && !(Config.HiddenStreams.Contains(stream.Name)))
Config.HiddenStreams.Add(stream.Name);
}
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_10_6 : EcmaTest
{
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsIRemainsSameAfterChangingActualParametersInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-10-c-ii-1-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsIChangeWithActualParameters()
{
RunTest(@"TestCases/ch10/10.6/10.6-10-c-ii-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsIDoesnTMapToActualParametersInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-10-c-ii-2-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsIMapToActualParameter()
{
RunTest(@"TestCases/ch10/10.6/10.6-10-c-ii-2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsObjectHasIndexProperty0AsItsOwnPropertyItShouldeBeWritableEnumerableConfigurableAndDoesNotInvokeTheSetterDefinedOnObjectPrototype0Step11B()
{
RunTest(@"TestCases/ch10/10.6/10.6-11-b-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void AccessingCalleePropertyOfArgumentsObjectIsAllowed()
{
RunTest(@"TestCases/ch10/10.6/10.6-12-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsCalleeHasCorrectAttributes()
{
RunTest(@"TestCases/ch10/10.6/10.6-12-2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void AccessingCallerPropertyOfArgumentsObjectIsAllowed()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void InNonStrictModeArgumentsObjectShouldHaveItsOwnCalleePropertyDefinedStep13A()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-a-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ADirectCallToArgumentsCalleeCallerShouldWork()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-a-2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void AnIndirectCallToArgumentsCalleeCallerShouldWork()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-a-3.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void AccessingCallerPropertyOfArgumentsObjectThrowsTypeerrorInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-b-1-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsCallerExistsInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-b-2-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsCallerIsNonConfigurableInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-b-3-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void AccessingCalleePropertyOfArgumentsObjectThrowsTypeerrorInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-c-1-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsCalleeIsExistsInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-c-2-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsCalleeIsNonConfigurableInStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-13-c-3-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeCalleeExistsAndCallerExistsUnderStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-14-1-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeEnumerableAttributeValueInCallerIsFalseUnderStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-14-b-1-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeTypeerrorIsThrownWhenAccessingTheSetAttributeInCallerUnderStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-14-b-4-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeEnumerableAttributeValueInCalleeIsFalseUnderStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-14-c-1-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeTypeerrorIsThrownWhenAccessingTheSetAttributeInCalleeUnderStrictMode()
{
RunTest(@"TestCases/ch10/10.6/10.6-14-c-4-s.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeArgumentsCalleeCannotBeAccessedInAStrictFunctionButDoesNotThrowAnEarlyError()
{
RunTest(@"TestCases/ch10/10.6/10.6-1gs.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void StrictModeArgumentsCalleeCannotBeAccessedInAStrictFunction()
{
RunTest(@"TestCases/ch10/10.6/10.6-2gs.js", true);
}
[Fact]
[Trait("Category", "10.6")]
public void PrototypePropertyOfArgumentsIsSetToObjectPrototypeObject()
{
RunTest(@"TestCases/ch10/10.6/10.6-5-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void LengthPropertyOfArgumentsObjectExists()
{
RunTest(@"TestCases/ch10/10.6/10.6-6-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void LengthPropertyOfArgumentsObjectHasCorrectAttributes()
{
RunTest(@"TestCases/ch10/10.6/10.6-6-2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void LengthPropertyOfArgumentsObjectFor0ArgumentFunctionExists()
{
RunTest(@"TestCases/ch10/10.6/10.6-6-3.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void LengthPropertyOfArgumentsObjectFor0ArgumentFunctionCallIs0EvenWithFormalParameters()
{
RunTest(@"TestCases/ch10/10.6/10.6-6-4.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void ArgumentsObjectHasLengthAsItsOwnPropertyAndDoesNotInvokeTheSetterDefinedOnObjectPrototypeLengthStep7()
{
RunTest(@"TestCases/ch10/10.6/10.6-7-1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void WhenControlEntersAnExecutionContextForFunctionCodeAnArgumentsObjectIsCreatedAndInitialised()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void TheValueOfTheInternalPrototypePropertyOfTheCreatedArgumentsObjectIsTheOriginalObjectPrototypeObjectTheOneThatIsTheInitialValueOfObjectPrototype()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameCalleeWithPropertyAttributesDontenumAndNoOthers()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A3_T1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameCalleeWithPropertyAttributesDontenumAndNoOthers2()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A3_T2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameCalleeWithPropertyAttributesDontenumAndNoOthers3()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A3_T3.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameCalleeWithPropertyAttributesDontenumAndNoOthers4()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A3_T4.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void TheInitialValueOfTheCreatedPropertyCalleeIsTheFunctionObjectBeingExecuted()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A4.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameLengthWithPropertyAttributesDontenumAndNoOthers()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A5_T1.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameLengthWithPropertyAttributesDontenumAndNoOthers2()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A5_T2.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameLengthWithPropertyAttributesDontenumAndNoOthers3()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A5_T3.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void APropertyIsCreatedWithNameLengthWithPropertyAttributesDontenumAndNoOthers4()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A5_T4.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void TheInitialValueOfTheCreatedPropertyLengthIsTheNumberOfActualParameterValuesSuppliedByTheCaller()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A6.js", false);
}
[Fact]
[Trait("Category", "10.6")]
public void GetArgumentsOfFunction()
{
RunTest(@"TestCases/ch10/10.6/S10.6_A7.js", false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Drawing2D;
namespace System.Drawing.Html
{
/// <summary>
/// Provides some drawing functionallity
/// </summary>
internal static class CssDrawingHelper
{
/// <summary>
/// Border specifiers
/// </summary>
internal enum Border
{
Top, Right, Bottom, Left
}
/// <summary>
/// Rounds the specified point
/// </summary>
/// <param name="p"></param>
/// <param name="b"></param>
/// <returns></returns>
private static PointF RoundP(PointF p, CssBox b)
{
//HACK: Don't round if in printing mode
//return Point.Round(p);
return p;
}
/// <summary>
/// Rounds the specified rectangle
/// </summary>
/// <param name="p"></param>
/// <param name="b"></param>
/// <returns></returns>
private static RectangleF RoundR(RectangleF r, CssBox b)
{
//HACK: Don't round if in printing mode
return Rectangle.Round(r);
}
/// <summary>
/// Makes a border path
/// </summary>
/// <param name="border">Desired border</param>
/// <param name="b">Box wich the border corresponds</param>
/// <param name="isLineStart">Specifies if the border is for a starting line (no bevel on left)</param>
/// <param name="isLineEnd">Specifies if the border is for an ending line (no bevel on right)</param>
/// <returns>Beveled border path</returns>
public static GraphicsPath GetBorderPath(Border border, CssBox b, RectangleF r, bool isLineStart, bool isLineEnd)
{
PointF[] pts = new PointF[4];
float bwidth = 0;
GraphicsPath corner = null;
switch (border)
{
case Border.Top:
bwidth = b.ActualBorderTopWidth;
pts[0] = RoundP(new PointF(r.Left + b.ActualCornerNW, r.Top), b);
pts[1] = RoundP(new PointF(r.Right - b.ActualCornerNE, r.Top), b);
pts[2] = RoundP(new PointF(r.Right - b.ActualCornerNE, r.Top + bwidth), b);
pts[3] = RoundP(new PointF(r.Left + b.ActualCornerNW, r.Top + bwidth), b);
if (isLineEnd && b.ActualCornerNE == 0f) pts[2].X -= b.ActualBorderRightWidth;
if (isLineStart && b.ActualCornerNW == 0f) pts[3].X += b.ActualBorderLeftWidth;
if (b.ActualCornerNW > 0f) corner = CreateCorner(b, r, 1);
break;
case Border.Right:
bwidth = b.ActualBorderRightWidth;
pts[0] = RoundP(new PointF(r.Right - bwidth, r.Top + b.ActualCornerNE), b);
pts[1] = RoundP(new PointF(r.Right, r.Top + b.ActualCornerNE), b);
pts[2] = RoundP(new PointF(r.Right, r.Bottom - b.ActualCornerSE), b);
pts[3] = RoundP(new PointF(r.Right - bwidth, r.Bottom - b.ActualCornerSE), b);
if (b.ActualCornerNE == 0f) pts[0].Y += b.ActualBorderTopWidth;
if (b.ActualCornerSE == 0f) pts[3].Y -= b.ActualBorderBottomWidth;
if (b.ActualCornerNE > 0f) corner = CreateCorner(b, r, 2);
break;
case Border.Bottom:
bwidth = b.ActualBorderBottomWidth;
pts[0] = RoundP(new PointF(r.Left + b.ActualCornerSW, r.Bottom - bwidth), b);
pts[1] = RoundP(new PointF(r.Right - b.ActualCornerSE, r.Bottom - bwidth), b);
pts[2] = RoundP(new PointF(r.Right - b.ActualCornerSE, r.Bottom), b);
pts[3] = RoundP(new PointF(r.Left + b.ActualCornerSW, r.Bottom), b);
if (isLineStart && b.ActualCornerSW == 0f) pts[0].X += b.ActualBorderLeftWidth;
if (isLineEnd && b.ActualCornerSE == 0f) pts[1].X -= b.ActualBorderRightWidth;
if (b.ActualCornerSE > 0f) corner = CreateCorner(b, r, 3);
break;
case Border.Left:
bwidth = b.ActualBorderLeftWidth;
pts[0] = RoundP(new PointF(r.Left, r.Top + b.ActualCornerNW), b);
pts[1] = RoundP(new PointF(r.Left + bwidth, r.Top + b.ActualCornerNW), b);
pts[2] = RoundP(new PointF(r.Left + bwidth, r.Bottom - b.ActualCornerSW), b);
pts[3] = RoundP(new PointF(r.Left, r.Bottom - b.ActualCornerSW), b);
if (b.ActualCornerNW == 0f) pts[1].Y += b.ActualBorderTopWidth;
if (b.ActualCornerSW == 0f) pts[2].Y -= b.ActualBorderBottomWidth;
if (b.ActualCornerSW > 0f) corner = CreateCorner(b, r, 4);
break;
}
GraphicsPath path = new GraphicsPath(pts, new byte[] { (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line });
if (corner != null)
{
path.AddPath(corner, true);
}
return path;
}
/// <summary>
/// Creates the corner to place with the borders
/// </summary>
/// <param name="outer"></param>
/// <param name="inner"></param>
/// <param name="startAngle"></param>
/// <param name="sweepAngle"></param>
/// <returns></returns>
private static GraphicsPath CreateCorner(CssBox b, RectangleF r, int cornerIndex)
{
GraphicsPath corner = new GraphicsPath();
RectangleF outer = RectangleF.Empty;
RectangleF inner = RectangleF.Empty;
float start1 = 0;
float start2 = 0;
switch (cornerIndex)
{
case 1:
outer = new RectangleF(r.Left, r.Top, b.ActualCornerNW, b.ActualCornerNW);
inner = RectangleF.FromLTRB(outer.Left + b.ActualBorderLeftWidth, outer.Top + b.ActualBorderTopWidth, outer.Right, outer.Bottom);
start1 = 180;
start2 = 270;
break;
case 2:
outer = new RectangleF(r.Right - b.ActualCornerNE, r.Top, b.ActualCornerNE, b.ActualCornerNE);
inner = RectangleF.FromLTRB(outer.Left, outer.Top + b.ActualBorderTopWidth, outer.Right - b.ActualBorderRightWidth, outer.Bottom);
outer.X -= outer.Width;
inner.X -= inner.Width;
start1 = -90;
start2 = 0;
break;
case 3:
outer = RectangleF.FromLTRB(r.Right - b.ActualCornerSE, r.Bottom - b.ActualCornerSE, r.Right, r.Bottom);
inner = new RectangleF(outer.Left, outer.Top, outer.Width - b.ActualBorderRightWidth, outer.Height - b.ActualBorderBottomWidth);
outer.X -= outer.Width;
outer.Y -= outer.Height;
inner.X -= inner.Width;
inner.Y -= inner.Height;
start1 = 0;
start2 = 90;
break;
case 4:
outer = new RectangleF(r.Left, r.Bottom - b.ActualCornerSW, b.ActualCornerSW, b.ActualCornerSW);
inner = RectangleF.FromLTRB( r.Left + b.ActualBorderLeftWidth , outer.Top , outer.Right, outer.Bottom - b.ActualBorderBottomWidth);
start1 = 90;
start2 = 180;
outer.Y -= outer.Height;
inner.Y -= inner.Height;
break;
}
if (outer.Width <= 0f) outer.Width = 1f;
if (outer.Height <= 0f) outer.Height = 1f;
if (inner.Width <= 0f) inner.Width = 1f;
if (inner.Height <= 0f) inner.Height = 1f;
outer.Width *= 2; outer.Height *= 2;
inner.Width *= 2; inner.Height *= 2;
outer = RoundR(outer, b); inner = RoundR(inner, b);
corner.AddArc(outer, start1, 90);
corner.AddArc(inner, start2, -90);
corner.CloseFigure();
return corner;
}
/// <summary>
/// Creates a rounded rectangle using the specified corner radius
/// </summary>
/// <param name="rect">Rectangle to round</param>
/// <param name="nwRadius">Radius of the north east corner</param>
/// <param name="neRadius">Radius of the north west corner</param>
/// <param name="seRadius">Radius of the south east corner</param>
/// <param name="swRadius">Radius of the south west corner</param>
/// <returns>GraphicsPath with the lines of the rounded rectangle ready to be painted</returns>
public static GraphicsPath GetRoundRect(RectangleF rect, float nwRadius, float neRadius, float seRadius, float swRadius)
{
/// NW-----NE
/// | |
/// | |
/// SW-----SE
GraphicsPath path = new GraphicsPath();
nwRadius *= 2;
neRadius *= 2;
seRadius *= 2;
swRadius *= 2;
//NW ---- NE
path.AddLine(rect.X + nwRadius, rect.Y, rect.Right - neRadius, rect.Y);
//NE Arc
if (neRadius > 0f)
{
path.AddArc(
RectangleF.FromLTRB(rect.Right - neRadius, rect.Top, rect.Right, rect.Top + neRadius),
-90, 90);
}
// NE
// |
// SE
path.AddLine(rect.Right, rect.Top + neRadius, rect.Right, rect.Bottom - seRadius);
//SE Arc
if (seRadius > 0f)
{
path.AddArc(
RectangleF.FromLTRB(rect.Right - seRadius, rect.Bottom - seRadius, rect.Right, rect.Bottom),
0, 90);
}
// SW --- SE
path.AddLine(rect.Right - seRadius, rect.Bottom, rect.Left + swRadius, rect.Bottom);
//SW Arc
if (swRadius > 0f)
{
path.AddArc(
RectangleF.FromLTRB(rect.Left, rect.Bottom - swRadius, rect.Left + swRadius, rect.Bottom),
90, 90);
}
// NW
// |
// SW
path.AddLine(rect.Left, rect.Bottom - swRadius, rect.Left, rect.Top + nwRadius);
//NW Arc
if (nwRadius > 0f)
{
path.AddArc(
RectangleF.FromLTRB(rect.Left, rect.Top, rect.Left + nwRadius, rect.Top + nwRadius),
180, 90);
}
path.CloseFigure();
return path;
}
/// <summary>
/// Makes the specified color darker
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static Color Darken(Color c)
{
return Color.FromArgb(c.R / 2, c.G / 2, c.B / 2);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualMachineScaleSetVMsOperations operations.
/// </summary>
public partial interface IVirtualMachineScaleSetVMsOperations
{
/// <summary>
/// Allows you to re-image(update the version of the installed
/// operating system) a virtual machine scale set instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> ReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to re-image(update the version of the installed
/// operating system) a virtual machine scale set instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to deallocate a virtual machine scale set virtual
/// machine. Shuts down the virtual machine and releases the compute
/// resources. You are not billed for the compute resources that this
/// virtual machine uses.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to deallocate a virtual machine scale set virtual
/// machine. Shuts down the virtual machine and releases the compute
/// resources. You are not billed for the compute resources that this
/// virtual machine uses.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to delete a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to delete a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Displays information about a virtual machine scale set virtual
/// machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualMachineScaleSetVM>> GetWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Displays the status of a virtual machine scale set virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualMachineScaleSetVMInstanceView>> GetInstanceViewWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all virtual machines in a VM scale sets.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// The list parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, ODataQuery<VirtualMachineScaleSetVM> odataQuery = default(ODataQuery<VirtualMachineScaleSetVM>), string select = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to power off (stop) a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to power off (stop) a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to restart a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> RestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to restart a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to start a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to start a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all virtual machines in a VM scale sets.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// Notification
/// </summary>
[DataContract]
public partial class Notification : IEquatable<Notification>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Notification" /> class.
/// </summary>
/// <param name="canFilterByDistributionCenters">True if this notification can be filtered to only send for one or more distribution centers..</param>
/// <param name="canIncludeAffiliate">True if this notification can include an affiliate information..</param>
/// <param name="canIncludeOrder">True if this notification can include an order attachment..</param>
/// <param name="canIncludeOrderPlainText">True if this notification can include a plain text rendering of an order directly within an email. Some desire this over an attachment.</param>
/// <param name="distributionCenterFilters">If this notification supports it, this list of distribution center CODES will filter the notification to just those distribution centers..</param>
/// <param name="includeAffiliate">If true, and this notification supports it, affiliate information will be attached to all notifications of this type.</param>
/// <param name="includeOrder">If true, and this notification supports it, the order will be attached to all notifications of this type.</param>
/// <param name="includeOrderPlainText">If true, and this notification supports it, a plain text order will be directly inserted into all notifications of this type.</param>
/// <param name="name">The name of this notification..</param>
/// <param name="notificationGroup">A group for this notification. This name is only used for visual grouping within interfaces..</param>
/// <param name="selected">True if this user wishes to receive this email notification..</param>
public Notification(bool? canFilterByDistributionCenters = default(bool?), bool? canIncludeAffiliate = default(bool?), bool? canIncludeOrder = default(bool?), bool? canIncludeOrderPlainText = default(bool?), List<string> distributionCenterFilters = default(List<string>), bool? includeAffiliate = default(bool?), bool? includeOrder = default(bool?), bool? includeOrderPlainText = default(bool?), string name = default(string), string notificationGroup = default(string), bool? selected = default(bool?))
{
this.CanFilterByDistributionCenters = canFilterByDistributionCenters;
this.CanIncludeAffiliate = canIncludeAffiliate;
this.CanIncludeOrder = canIncludeOrder;
this.CanIncludeOrderPlainText = canIncludeOrderPlainText;
this.DistributionCenterFilters = distributionCenterFilters;
this.IncludeAffiliate = includeAffiliate;
this.IncludeOrder = includeOrder;
this.IncludeOrderPlainText = includeOrderPlainText;
this.Name = name;
this.NotificationGroup = notificationGroup;
this.Selected = selected;
}
/// <summary>
/// True if this notification can be filtered to only send for one or more distribution centers.
/// </summary>
/// <value>True if this notification can be filtered to only send for one or more distribution centers.</value>
[DataMember(Name="can_filter_by_distribution_centers", EmitDefaultValue=false)]
public bool? CanFilterByDistributionCenters { get; set; }
/// <summary>
/// True if this notification can include an affiliate information.
/// </summary>
/// <value>True if this notification can include an affiliate information.</value>
[DataMember(Name="can_include_affiliate", EmitDefaultValue=false)]
public bool? CanIncludeAffiliate { get; set; }
/// <summary>
/// True if this notification can include an order attachment.
/// </summary>
/// <value>True if this notification can include an order attachment.</value>
[DataMember(Name="can_include_order", EmitDefaultValue=false)]
public bool? CanIncludeOrder { get; set; }
/// <summary>
/// True if this notification can include a plain text rendering of an order directly within an email. Some desire this over an attachment
/// </summary>
/// <value>True if this notification can include a plain text rendering of an order directly within an email. Some desire this over an attachment</value>
[DataMember(Name="can_include_order_plain_text", EmitDefaultValue=false)]
public bool? CanIncludeOrderPlainText { get; set; }
/// <summary>
/// If this notification supports it, this list of distribution center CODES will filter the notification to just those distribution centers.
/// </summary>
/// <value>If this notification supports it, this list of distribution center CODES will filter the notification to just those distribution centers.</value>
[DataMember(Name="distribution_center_filters", EmitDefaultValue=false)]
public List<string> DistributionCenterFilters { get; set; }
/// <summary>
/// If true, and this notification supports it, affiliate information will be attached to all notifications of this type
/// </summary>
/// <value>If true, and this notification supports it, affiliate information will be attached to all notifications of this type</value>
[DataMember(Name="include_affiliate", EmitDefaultValue=false)]
public bool? IncludeAffiliate { get; set; }
/// <summary>
/// If true, and this notification supports it, the order will be attached to all notifications of this type
/// </summary>
/// <value>If true, and this notification supports it, the order will be attached to all notifications of this type</value>
[DataMember(Name="include_order", EmitDefaultValue=false)]
public bool? IncludeOrder { get; set; }
/// <summary>
/// If true, and this notification supports it, a plain text order will be directly inserted into all notifications of this type
/// </summary>
/// <value>If true, and this notification supports it, a plain text order will be directly inserted into all notifications of this type</value>
[DataMember(Name="include_order_plain_text", EmitDefaultValue=false)]
public bool? IncludeOrderPlainText { get; set; }
/// <summary>
/// The name of this notification.
/// </summary>
/// <value>The name of this notification.</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// A group for this notification. This name is only used for visual grouping within interfaces.
/// </summary>
/// <value>A group for this notification. This name is only used for visual grouping within interfaces.</value>
[DataMember(Name="notification_group", EmitDefaultValue=false)]
public string NotificationGroup { get; set; }
/// <summary>
/// True if this user wishes to receive this email notification.
/// </summary>
/// <value>True if this user wishes to receive this email notification.</value>
[DataMember(Name="selected", EmitDefaultValue=false)]
public bool? Selected { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Notification {\n");
sb.Append(" CanFilterByDistributionCenters: ").Append(CanFilterByDistributionCenters).Append("\n");
sb.Append(" CanIncludeAffiliate: ").Append(CanIncludeAffiliate).Append("\n");
sb.Append(" CanIncludeOrder: ").Append(CanIncludeOrder).Append("\n");
sb.Append(" CanIncludeOrderPlainText: ").Append(CanIncludeOrderPlainText).Append("\n");
sb.Append(" DistributionCenterFilters: ").Append(DistributionCenterFilters).Append("\n");
sb.Append(" IncludeAffiliate: ").Append(IncludeAffiliate).Append("\n");
sb.Append(" IncludeOrder: ").Append(IncludeOrder).Append("\n");
sb.Append(" IncludeOrderPlainText: ").Append(IncludeOrderPlainText).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" NotificationGroup: ").Append(NotificationGroup).Append("\n");
sb.Append(" Selected: ").Append(Selected).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Notification);
}
/// <summary>
/// Returns true if Notification instances are equal
/// </summary>
/// <param name="input">Instance of Notification to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Notification input)
{
if (input == null)
return false;
return
(
this.CanFilterByDistributionCenters == input.CanFilterByDistributionCenters ||
(this.CanFilterByDistributionCenters != null &&
this.CanFilterByDistributionCenters.Equals(input.CanFilterByDistributionCenters))
) &&
(
this.CanIncludeAffiliate == input.CanIncludeAffiliate ||
(this.CanIncludeAffiliate != null &&
this.CanIncludeAffiliate.Equals(input.CanIncludeAffiliate))
) &&
(
this.CanIncludeOrder == input.CanIncludeOrder ||
(this.CanIncludeOrder != null &&
this.CanIncludeOrder.Equals(input.CanIncludeOrder))
) &&
(
this.CanIncludeOrderPlainText == input.CanIncludeOrderPlainText ||
(this.CanIncludeOrderPlainText != null &&
this.CanIncludeOrderPlainText.Equals(input.CanIncludeOrderPlainText))
) &&
(
this.DistributionCenterFilters == input.DistributionCenterFilters ||
this.DistributionCenterFilters != null &&
this.DistributionCenterFilters.SequenceEqual(input.DistributionCenterFilters)
) &&
(
this.IncludeAffiliate == input.IncludeAffiliate ||
(this.IncludeAffiliate != null &&
this.IncludeAffiliate.Equals(input.IncludeAffiliate))
) &&
(
this.IncludeOrder == input.IncludeOrder ||
(this.IncludeOrder != null &&
this.IncludeOrder.Equals(input.IncludeOrder))
) &&
(
this.IncludeOrderPlainText == input.IncludeOrderPlainText ||
(this.IncludeOrderPlainText != null &&
this.IncludeOrderPlainText.Equals(input.IncludeOrderPlainText))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.NotificationGroup == input.NotificationGroup ||
(this.NotificationGroup != null &&
this.NotificationGroup.Equals(input.NotificationGroup))
) &&
(
this.Selected == input.Selected ||
(this.Selected != null &&
this.Selected.Equals(input.Selected))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CanFilterByDistributionCenters != null)
hashCode = hashCode * 59 + this.CanFilterByDistributionCenters.GetHashCode();
if (this.CanIncludeAffiliate != null)
hashCode = hashCode * 59 + this.CanIncludeAffiliate.GetHashCode();
if (this.CanIncludeOrder != null)
hashCode = hashCode * 59 + this.CanIncludeOrder.GetHashCode();
if (this.CanIncludeOrderPlainText != null)
hashCode = hashCode * 59 + this.CanIncludeOrderPlainText.GetHashCode();
if (this.DistributionCenterFilters != null)
hashCode = hashCode * 59 + this.DistributionCenterFilters.GetHashCode();
if (this.IncludeAffiliate != null)
hashCode = hashCode * 59 + this.IncludeAffiliate.GetHashCode();
if (this.IncludeOrder != null)
hashCode = hashCode * 59 + this.IncludeOrder.GetHashCode();
if (this.IncludeOrderPlainText != null)
hashCode = hashCode * 59 + this.IncludeOrderPlainText.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.NotificationGroup != null)
hashCode = hashCode * 59 + this.NotificationGroup.GetHashCode();
if (this.Selected != null)
hashCode = hashCode * 59 + this.Selected.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// 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.Linq;
using System.Numerics;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
public partial class ImportExport
{
private static bool EphemeralKeysAreExportable => !PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer();
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void ExportAutoKey()
{
RSAParameters privateParams;
RSAParameters publicParams;
int keySize;
using (RSA rsa = RSAFactory.Create())
{
keySize = rsa.KeySize;
// We've not done anything with this instance yet, but it should automatically
// create the key, because we'll now asked about it.
privateParams = rsa.ExportParameters(true);
publicParams = rsa.ExportParameters(false);
// It shouldn't be changing things when it generated the key.
Assert.Equal(keySize, rsa.KeySize);
}
Assert.Null(publicParams.D);
Assert.NotNull(privateParams.D);
ValidateParameters(ref publicParams);
ValidateParameters(ref privateParams);
Assert.Equal(privateParams.Modulus, publicParams.Modulus);
Assert.Equal(privateParams.Exponent, publicParams.Exponent);
}
[ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void PaddedExport()
{
// OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued
// prefix bytes.
//
// The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown
// values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself
// the same size as Modulus).
//
// These two things, in combination, suggest that we ensure that all .NET
// implementations of RSA export their keys to the fixed array size suggested by their
// KeySize property.
RSAParameters diminishedDPParameters = TestData.DiminishedDPParameters;
RSAParameters exported;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(diminishedDPParameters);
exported = rsa.ExportParameters(true);
}
// DP is the most likely to fail, the rest just otherwise ensure that Export
// isn't losing data.
AssertKeyEquals(ref diminishedDPParameters, ref exported);
}
[ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void LargeKeyImportExport()
{
RSAParameters imported = TestData.RSA16384Params;
using (RSA rsa = RSAFactory.Create())
{
try
{
rsa.ImportParameters(imported);
}
catch (CryptographicException)
{
// The key is pretty big, perhaps it was refused.
return;
}
RSAParameters exported = rsa.ExportParameters(false);
Assert.Equal(exported.Modulus, imported.Modulus);
Assert.Equal(exported.Exponent, imported.Exponent);
Assert.Null(exported.D);
exported = rsa.ExportParameters(true);
AssertKeyEquals(ref imported, ref exported);
}
}
[ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void UnusualExponentImportExport()
{
// Most choices for the Exponent value in an RSA key use a Fermat prime.
// Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and
// frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same
// representation in both big- and little-endian.
//
// The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1).
// So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export.
RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters;
RSAParameters exported;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(unusualExponentParameters);
exported = rsa.ExportParameters(true);
}
// Exponent is the most likely to fail, the rest just otherwise ensure that Export
// isn't losing data.
AssertKeyEquals(ref unusualExponentParameters, ref exported);
}
[ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void ImportExport1032()
{
RSAParameters imported = TestData.RSA1032Parameters;
RSAParameters exported;
RSAParameters exportedPublic;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
exported = rsa.ExportParameters(true);
exportedPublic = rsa.ExportParameters(false);
}
AssertKeyEquals(ref imported, ref exported);
Assert.Equal(exportedPublic.Modulus, imported.Modulus);
Assert.Equal(exportedPublic.Exponent, imported.Exponent);
Assert.Null(exportedPublic.D);
}
[ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void ImportReset()
{
using (RSA rsa = RSAFactory.Create())
{
RSAParameters exported = rsa.ExportParameters(true);
RSAParameters imported;
// Ensure that we cause the KeySize value to change.
if (rsa.KeySize == 1024)
{
imported = TestData.RSA2048Params;
}
else
{
imported = TestData.RSA1024Params;
}
Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize);
Assert.NotEqual(imported.Modulus, exported.Modulus);
rsa.ImportParameters(imported);
Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize);
exported = rsa.ExportParameters(true);
AssertKeyEquals(ref imported, ref exported);
}
}
[Fact]
public static void ImportPrivateExportPublic()
{
RSAParameters imported = TestData.RSA1024Params;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
RSAParameters exportedPublic = rsa.ExportParameters(false);
Assert.Equal(imported.Modulus, exportedPublic.Modulus);
Assert.Equal(imported.Exponent, exportedPublic.Exponent);
Assert.Null(exportedPublic.D);
ValidateParameters(ref exportedPublic);
}
}
[ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void MultiExport()
{
RSAParameters imported = TestData.RSA1024Params;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
RSAParameters exportedPrivate = rsa.ExportParameters(true);
RSAParameters exportedPrivate2 = rsa.ExportParameters(true);
RSAParameters exportedPublic = rsa.ExportParameters(false);
RSAParameters exportedPublic2 = rsa.ExportParameters(false);
RSAParameters exportedPrivate3 = rsa.ExportParameters(true);
RSAParameters exportedPublic3 = rsa.ExportParameters(false);
AssertKeyEquals(ref imported, ref exportedPrivate);
Assert.Equal(imported.Modulus, exportedPublic.Modulus);
Assert.Equal(imported.Exponent, exportedPublic.Exponent);
Assert.Null(exportedPublic.D);
ValidateParameters(ref exportedPublic);
AssertKeyEquals(ref exportedPrivate, ref exportedPrivate2);
AssertKeyEquals(ref exportedPrivate, ref exportedPrivate3);
AssertKeyEquals(ref exportedPublic, ref exportedPublic2);
AssertKeyEquals(ref exportedPublic, ref exportedPublic3);
}
}
[Fact]
public static void PublicOnlyPrivateExport()
{
RSAParameters imported = new RSAParameters
{
Modulus = TestData.RSA1024Params.Modulus,
Exponent = TestData.RSA1024Params.Exponent,
};
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
Assert.ThrowsAny<CryptographicException>(() => rsa.ExportParameters(true));
}
}
[Fact]
public static void ImportNoExponent()
{
RSAParameters imported = new RSAParameters
{
Modulus = TestData.RSA1024Params.Modulus,
};
using (RSA rsa = RSAFactory.Create())
{
if (rsa is RSACng && PlatformDetection.IsFullFramework)
AssertExtensions.Throws<ArgumentException>(null, () => rsa.ImportParameters(imported));
else
Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported));
}
}
[Fact]
public static void ImportNoModulus()
{
RSAParameters imported = new RSAParameters
{
Exponent = TestData.RSA1024Params.Exponent,
};
using (RSA rsa = RSAFactory.Create())
{
if (rsa is RSACng && PlatformDetection.IsFullFramework)
AssertExtensions.Throws<ArgumentException>(null, () => rsa.ImportParameters(imported));
else
Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported));
}
}
[Fact]
#if TESTING_CNG_IMPLEMENTATION
[ActiveIssue(18882, TargetFrameworkMonikers.NetFramework)]
#endif
public static void ImportNoDP()
{
// Because RSAParameters is a struct, this is a copy,
// so assigning DP is not destructive to other tests.
RSAParameters imported = TestData.RSA1024Params;
imported.DP = null;
using (RSA rsa = RSAFactory.Create())
{
Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported));
}
}
internal static void AssertKeyEquals(ref RSAParameters expected, ref RSAParameters actual)
{
Assert.Equal(expected.Modulus, actual.Modulus);
Assert.Equal(expected.Exponent, actual.Exponent);
Assert.Equal(expected.P, actual.P);
Assert.Equal(expected.DP, actual.DP);
Assert.Equal(expected.Q, actual.Q);
Assert.Equal(expected.DQ, actual.DQ);
Assert.Equal(expected.InverseQ, actual.InverseQ);
if (expected.D == null)
{
Assert.Null(actual.D);
}
else
{
Assert.NotNull(actual.D);
// If the value matched expected, take that as valid and shortcut the math.
// If it didn't, we'll test that the value is at least legal.
if (!expected.D.SequenceEqual(actual.D))
{
VerifyDValue(ref actual);
}
}
}
internal static void ValidateParameters(ref RSAParameters rsaParams)
{
Assert.NotNull(rsaParams.Modulus);
Assert.NotNull(rsaParams.Exponent);
// Key compatibility: RSA as an algorithm is achievable using just N (Modulus),
// E (public Exponent) and D (private exponent). Having all of the breakdowns
// of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider
// have thrown if D is provided and the rest of the private key values are not.
// So, here we're going to assert that none of them were null for private keys.
if (rsaParams.D == null)
{
Assert.Null(rsaParams.P);
Assert.Null(rsaParams.DP);
Assert.Null(rsaParams.Q);
Assert.Null(rsaParams.DQ);
Assert.Null(rsaParams.InverseQ);
}
else
{
Assert.NotNull(rsaParams.P);
Assert.NotNull(rsaParams.DP);
Assert.NotNull(rsaParams.Q);
Assert.NotNull(rsaParams.DQ);
Assert.NotNull(rsaParams.InverseQ);
}
}
private static void VerifyDValue(ref RSAParameters rsaParams)
{
if (rsaParams.P == null)
{
return;
}
// Verify that the formula (D * E) % LCM(p - 1, q - 1) == 1
// is true.
//
// This is NOT the same as saying D = ModInv(E, LCM(p - 1, q - 1)),
// because D = ModInv(E, (p - 1) * (q - 1)) is a valid choice, but will
// still work through this formula.
BigInteger p = PositiveBigInteger(rsaParams.P);
BigInteger q = PositiveBigInteger(rsaParams.Q);
BigInteger e = PositiveBigInteger(rsaParams.Exponent);
BigInteger d = PositiveBigInteger(rsaParams.D);
BigInteger lambda = LeastCommonMultiple(p - 1, q - 1);
BigInteger modProduct = (d * e) % lambda;
Assert.Equal(BigInteger.One, modProduct);
}
private static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b)
{
BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b);
return BigInteger.Abs(a) / gcd * BigInteger.Abs(b);
}
private static BigInteger PositiveBigInteger(byte[] bigEndianBytes)
{
byte[] littleEndianBytes;
if (bigEndianBytes[0] >= 0x80)
{
// Insert a padding 00 byte so the number is treated as positive.
littleEndianBytes = new byte[bigEndianBytes.Length + 1];
Buffer.BlockCopy(bigEndianBytes, 0, littleEndianBytes, 1, bigEndianBytes.Length);
}
else
{
littleEndianBytes = (byte[])bigEndianBytes.Clone();
}
Array.Reverse(littleEndianBytes);
return new BigInteger(littleEndianBytes);
}
}
}
| |
// 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.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class ProductInfoHeaderValueTest
{
[Fact]
public void Ctor_ProductOverload_MatchExpectation()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue(new ProductHeaderValue("product"));
Assert.Equal(new ProductHeaderValue("product"), productInfo.Product);
Assert.Null(productInfo.Comment);
ProductHeaderValue input = null;
Assert.Throws<ArgumentNullException>(() => { new ProductInfoHeaderValue(input); });
}
[Fact]
public void Ctor_ProductStringOverload_MatchExpectation()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
Assert.Equal(new ProductHeaderValue("product", "1.0"), productInfo.Product);
Assert.Null(productInfo.Comment);
}
[Fact]
public void Ctor_CommentOverload_MatchExpectation()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("(this is a comment)");
Assert.Null(productInfo.Product);
Assert.Equal("(this is a comment)", productInfo.Comment);
Assert.Throws<ArgumentException>(() => { new ProductInfoHeaderValue((string)null); });
Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue("invalid comment"); });
Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue(" (leading space)"); });
Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue("(trailing space) "); });
}
[Fact]
public void ToString_UseDifferentProductInfos_AllSerializedCorrectly()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
Assert.Equal("product/1.0", productInfo.ToString());
productInfo = new ProductInfoHeaderValue("(comment)");
Assert.Equal("(comment)", productInfo.ToString());
}
[Fact]
public void ToString_Aggregate_AllSerializedCorrectly()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = string.Empty;
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
Assert.Equal("product/1.0", productInfo.ToString());
input += productInfo.ToString();
request.Headers.UserAgent.Add(productInfo);
productInfo = new ProductInfoHeaderValue("(comment)");
Assert.Equal("(comment)", productInfo.ToString());
input += " " + productInfo.ToString(); // Space delineated
request.Headers.UserAgent.Add(productInfo);
Assert.Equal(input, request.Headers.UserAgent.ToString());
}
[Fact]
public void GetHashCode_UseSameAndDifferentProductInfos_SameOrDifferentHashCodes()
{
ProductInfoHeaderValue productInfo1 = new ProductInfoHeaderValue("product", "1.0");
ProductInfoHeaderValue productInfo2 = new ProductInfoHeaderValue(new ProductHeaderValue("product", "1.0"));
ProductInfoHeaderValue productInfo3 = new ProductInfoHeaderValue("(comment)");
ProductInfoHeaderValue productInfo4 = new ProductInfoHeaderValue("(COMMENT)");
Assert.Equal(productInfo1.GetHashCode(), productInfo2.GetHashCode());
Assert.NotEqual(productInfo1.GetHashCode(), productInfo3.GetHashCode());
Assert.NotEqual(productInfo3.GetHashCode(), productInfo4.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions()
{
ProductInfoHeaderValue productInfo1 = new ProductInfoHeaderValue("product", "1.0");
ProductInfoHeaderValue productInfo2 = new ProductInfoHeaderValue(new ProductHeaderValue("product", "1.0"));
ProductInfoHeaderValue productInfo3 = new ProductInfoHeaderValue("(comment)");
ProductInfoHeaderValue productInfo4 = new ProductInfoHeaderValue("(COMMENT)");
Assert.False(productInfo1.Equals(null), "product/1.0 vs. <null>");
Assert.True(productInfo1.Equals(productInfo2), "product/1.0 vs. product/1.0");
Assert.False(productInfo1.Equals(productInfo3), "product/1.0 vs. (comment)");
Assert.False(productInfo3.Equals(productInfo4), "(comment) vs. (COMMENT)");
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
ProductInfoHeaderValue source = new ProductInfoHeaderValue("product", "1.0");
ProductInfoHeaderValue clone = (ProductInfoHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Product, clone.Product);
Assert.Null(clone.Comment);
source = new ProductInfoHeaderValue("(comment)");
clone = (ProductInfoHeaderValue)((ICloneable)source).Clone();
Assert.Null(clone.Product);
Assert.Equal(source.Comment, clone.Comment);
}
[Fact]
public void GetProductInfoLength_DifferentValidScenarios_AllReturnNonZero()
{
ProductInfoHeaderValue result = null;
CallGetProductInfoLength(" product / 1.0 ", 1, 14, out result);
Assert.Equal(new ProductHeaderValue("product", "1.0"), result.Product);
Assert.Null(result.Comment);
CallGetProductInfoLength("p/1.0", 0, 5, out result);
Assert.Equal(new ProductHeaderValue("p", "1.0"), result.Product);
Assert.Null(result.Comment);
CallGetProductInfoLength(" (this is a comment) , ", 1, 21, out result);
Assert.Null(result.Product);
Assert.Equal("(this is a comment)", result.Comment);
CallGetProductInfoLength("(c)", 0, 3, out result);
Assert.Null(result.Product);
Assert.Equal("(c)", result.Comment);
CallGetProductInfoLength("(comment/1.0)[", 0, 13, out result);
Assert.Null(result.Product);
Assert.Equal("(comment/1.0)", result.Comment);
}
[Fact]
public void GetRangeLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetProductInfoLength(" p/1.0", 0); // no leading whitespace allowed
CheckInvalidGetProductInfoLength(" (c)", 0); // no leading whitespace allowed
CheckInvalidGetProductInfoLength("(invalid", 0);
CheckInvalidGetProductInfoLength("product/", 0);
CheckInvalidGetProductInfoLength("product/(1.0)", 0);
CheckInvalidGetProductInfoLength("", 0);
CheckInvalidGetProductInfoLength(null, 0);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidParse("product", new ProductInfoHeaderValue("product", null));
CheckValidParse(" product ", new ProductInfoHeaderValue("product", null));
CheckValidParse(" (comment) ", new ProductInfoHeaderValue("(comment)"));
CheckValidParse(" Mozilla/5.0 ", new ProductInfoHeaderValue("Mozilla", "5.0"));
CheckValidParse(" (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ",
new ProductInfoHeaderValue("(compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("p/1.0,");
CheckInvalidParse("p/1.0\r\n"); // for \r\n to be a valid whitespace, it must be followed by space/tab
CheckInvalidParse("p/1.0(comment)");
CheckInvalidParse("(comment)[");
CheckInvalidParse(" Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ");
CheckInvalidParse("p/1.0 =");
// "User-Agent" and "Server" don't allow empty values (unlike most other headers supporting lists of values)
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
CheckInvalidParse(" ");
CheckInvalidParse("\t");
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidTryParse("product", new ProductInfoHeaderValue("product", null));
CheckValidTryParse(" product ", new ProductInfoHeaderValue("product", null));
CheckValidTryParse(" (comment) ", new ProductInfoHeaderValue("(comment)"));
CheckValidTryParse(" Mozilla/5.0 ", new ProductInfoHeaderValue("Mozilla", "5.0"));
CheckValidTryParse(" (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ",
new ProductInfoHeaderValue("(compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("p/1.0,");
CheckInvalidTryParse("p/1.0\r\n"); // for \r\n to be a valid whitespace, it must be followed by space/tab
CheckInvalidTryParse("p/1.0(comment)");
CheckInvalidTryParse("(comment)[");
CheckInvalidTryParse(" Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ");
CheckInvalidTryParse("p/1.0 =");
// "User-Agent" and "Server" don't allow empty values (unlike most other headers supporting lists of values)
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
CheckInvalidTryParse(" ");
CheckInvalidTryParse("\t");
}
#region Helper methods
private void CheckValidParse(string input, ProductInfoHeaderValue expectedResult)
{
ProductInfoHeaderValue result = ProductInfoHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { ProductInfoHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, ProductInfoHeaderValue expectedResult)
{
ProductInfoHeaderValue result = null;
Assert.True(ProductInfoHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
ProductInfoHeaderValue result = null;
Assert.False(ProductInfoHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void CallGetProductInfoLength(string input, int startIndex, int expectedLength,
out ProductInfoHeaderValue result)
{
Assert.Equal(expectedLength, ProductInfoHeaderValue.GetProductInfoLength(input, startIndex, out result));
}
private static void CheckInvalidGetProductInfoLength(string input, int startIndex)
{
ProductInfoHeaderValue result = null;
Assert.Equal(0, ProductInfoHeaderValue.GetProductInfoLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing.Dependencies;
namespace osu.Framework.Tests.Dependencies
{
[TestFixture]
public class DependencyContainerTest
{
[Test]
public void TestCacheAsMostDerivedType()
{
var baseObject = new BaseObject { TestValue = 1 };
var derivedObject = new DerivedObject { TestValue = 2 };
var dependencies = new DependencyContainer();
dependencies.Cache(baseObject);
dependencies.Cache(derivedObject);
BaseObject receivedBase = null;
BaseObject receivedDerived = null;
var receiver = new Receiver1
{
OnLoad = (b, d) =>
{
receivedBase = b;
receivedDerived = d;
}
};
dependencies.Inject(receiver);
Assert.AreEqual(typeof(BaseObject), receivedBase.GetType());
Assert.AreEqual(typeof(DerivedObject), receivedDerived.GetType());
Assert.AreEqual(1, receivedBase.TestValue);
Assert.AreEqual(2, receivedDerived.TestValue);
}
[Test]
public void TestInjectIntoNothing()
{
var baseObject = new BaseObject { TestValue = 1 };
var dependencies = new DependencyContainer();
dependencies.Cache(baseObject);
var receiver = new Receiver2();
Assert.DoesNotThrow(() => dependencies.Inject(receiver));
}
[Test]
public void TestInjectNullIntoNonNull()
{
var dependencies = new DependencyContainer();
var receiver = new Receiver1();
Assert.Throws<DependencyNotRegisteredException>(() => dependencies.Inject(receiver));
}
[Test]
public void TestInjectNullIntoNullable()
{
var dependencies = new DependencyContainer();
var receiver = new Receiver3();
Assert.DoesNotThrow(() => dependencies.Inject(receiver));
}
[Test]
public void TestInjectIntoSubClasses()
{
var dependencies = new DependencyContainer();
int count = 0, baseCount = 0, derivedCount = 0;
var receiver = new Receiver5
{
Loaded4 = () => baseCount = ++count,
Loaded5 = () => derivedCount = ++count
};
dependencies.Inject(receiver);
Assert.AreEqual(1, baseCount);
Assert.AreEqual(2, derivedCount);
}
[Test]
public void TestOverrideCache()
{
var testObject1 = new BaseObject { TestValue = 1 };
var testObject2 = new BaseObject { TestValue = 2 };
var dependencies1 = new DependencyContainer();
dependencies1.Cache(testObject1);
var dependencies2 = new DependencyContainer(dependencies1);
dependencies2.Cache(testObject2);
BaseObject receivedObject = null;
var receiver = new Receiver3
{
OnLoad = o => receivedObject = o
};
dependencies1.Inject(receiver);
Assert.AreEqual(receivedObject, testObject1);
dependencies2.Inject(receiver);
Assert.AreEqual(receivedObject, testObject2);
}
[Test]
public void TestMultipleCacheFails()
{
var testObject1 = new BaseObject { TestValue = 1 };
var testObject2 = new BaseObject { TestValue = 2 };
var dependencies = new DependencyContainer();
dependencies.Cache(testObject1);
Assert.Throws<TypeAlreadyCachedException>(() => dependencies.Cache(testObject2));
}
/// <summary>
/// Special case because "where T : class" also allows interfaces.
/// </summary>
[Test]
public void TestAttemptCacheStruct()
{
Assert.Throws<ArgumentException>(() => new DependencyContainer().Cache(new BaseStructObject()));
}
/// <summary>
/// Special case because "where T : class" also allows interfaces.
/// </summary>
[Test]
public void TestAttemptCacheAsStruct()
{
Assert.Throws<ArgumentException>(() => new DependencyContainer().CacheAs<IBaseInterface>(new BaseStructObject()));
}
/// <summary>
/// Special value type that remains internally consistent through copies.
/// </summary>
[Test]
public void TestCacheCancellationToken()
{
var source = new CancellationTokenSource();
var token = source.Token;
var dependencies = new DependencyContainer();
Assert.DoesNotThrow(() => dependencies.CacheValue(token));
var retrieved = dependencies.GetValue<CancellationToken>();
source.Cancel();
Assert.IsTrue(token.IsCancellationRequested);
Assert.IsTrue(retrieved.IsCancellationRequested);
}
[Test]
public void TestInvalidPublicAccessor()
{
var receiver = new Receiver6();
Assert.Throws<AccessModifierNotAllowedForLoaderMethodException>(() => new DependencyContainer().Inject(receiver));
}
[Test]
public void TestInvalidProtectedAccessor()
{
var receiver = new Receiver7();
Assert.Throws<AccessModifierNotAllowedForLoaderMethodException>(() => new DependencyContainer().Inject(receiver));
}
[Test]
public void TestInvalidInternalAccessor()
{
var receiver = new Receiver8();
Assert.Throws<AccessModifierNotAllowedForLoaderMethodException>(() => new DependencyContainer().Inject(receiver));
}
[Test]
public void TestInvalidProtectedInternalAccessor()
{
var receiver = new Receiver9();
Assert.Throws<AccessModifierNotAllowedForLoaderMethodException>(() => new DependencyContainer().Inject(receiver));
}
[Test]
public void TestReceiveStructInternal()
{
var receiver = new Receiver10();
var testObject = new CachedStructProvider();
var dependencies = DependencyActivator.MergeDependencies(testObject, new DependencyContainer());
Assert.DoesNotThrow(() => dependencies.Inject(receiver));
Assert.AreEqual(testObject.CachedObject.Value, receiver.TestObject.Value);
}
[TestCase(null)]
[TestCase(10)]
public void TestResolveNullableInternal(int? testValue)
{
var receiver = new Receiver11();
var testObject = new CachedNullableProvider();
testObject.SetValue(testValue);
var dependencies = DependencyActivator.MergeDependencies(testObject, new DependencyContainer());
dependencies.Inject(receiver);
Assert.AreEqual(testValue, receiver.TestObject);
}
[Test]
public void TestCacheNullInternal()
{
Assert.DoesNotThrow(() => new DependencyContainer().CacheValue(null));
Assert.DoesNotThrow(() => new DependencyContainer().CacheValueAs<object>(null));
}
[Test]
public void TestResolveStructWithoutNullPermits()
{
Assert.Throws<DependencyNotRegisteredException>(() => new DependencyContainer().Inject(new Receiver12()));
}
[Test]
public void TestResolveStructWithNullPermits()
{
var receiver = new Receiver13();
Assert.DoesNotThrow(() => new DependencyContainer().Inject(receiver));
Assert.AreEqual(0, receiver.TestObject);
}
[Test]
public void TestCacheAsNullableInternal()
{
int? testObject = 5;
var dependencies = new DependencyContainer();
dependencies.CacheValueAs(testObject);
Assert.AreEqual(testObject, dependencies.GetValue<int>());
Assert.AreEqual(testObject, dependencies.GetValue<int?>());
}
[Test]
public void TestCacheWithDependencyInfo()
{
var cases = new[]
{
default,
new CacheInfo("name"),
new CacheInfo(parent: typeof(object)),
new CacheInfo("name", typeof(object))
};
var dependencies = new DependencyContainer();
for (int i = 0; i < cases.Length; i++)
dependencies.CacheValueAs(i, cases[i]);
Assert.Multiple(() =>
{
for (int i = 0; i < cases.Length; i++)
Assert.AreEqual(i, dependencies.GetValue<int>(cases[i]));
});
}
[Test]
public void TestDependenciesOverrideParent()
{
var cases = new[]
{
default,
new CacheInfo("name"),
new CacheInfo(parent: typeof(object)),
new CacheInfo("name", typeof(object))
};
var dependencies = new DependencyContainer();
for (int i = 0; i < cases.Length; i++)
dependencies.CacheValueAs(i, cases[i]);
dependencies = new DependencyContainer(dependencies);
for (int i = 0; i < cases.Length; i++)
dependencies.CacheValueAs(cases.Length + i, cases[i]);
Assert.Multiple(() =>
{
for (int i = 0; i < cases.Length; i++)
Assert.AreEqual(cases.Length + i, dependencies.GetValue<int>(cases[i]));
});
}
private interface IBaseInterface
{
}
private class BaseObject
{
public int TestValue;
}
private struct BaseStructObject : IBaseInterface
{
}
private class DerivedObject : BaseObject
{
}
private class Receiver1
{
public Action<BaseObject, DerivedObject> OnLoad;
[BackgroundDependencyLoader]
private void load(BaseObject baseObject, DerivedObject derivedObject) => OnLoad?.Invoke(baseObject, derivedObject);
}
private class Receiver2
{
}
private class Receiver3
{
public Action<BaseObject> OnLoad;
[BackgroundDependencyLoader(true)]
private void load(BaseObject baseObject) => OnLoad?.Invoke(baseObject);
}
private class Receiver4
{
public Action Loaded4;
[BackgroundDependencyLoader]
private void load() => Loaded4?.Invoke();
}
private class Receiver5 : Receiver4
{
public Action Loaded5;
[BackgroundDependencyLoader]
private void load() => Loaded5?.Invoke();
}
private class Receiver6
{
[BackgroundDependencyLoader]
public void Load()
{
}
}
private class Receiver7
{
[BackgroundDependencyLoader]
protected void Load()
{
}
}
private class Receiver8
{
[BackgroundDependencyLoader]
internal void Load()
{
}
}
private class Receiver9
{
[BackgroundDependencyLoader]
protected internal void Load()
{
}
}
private class Receiver10
{
public CachedStructProvider.Struct TestObject { get; private set; }
[BackgroundDependencyLoader]
private void load(CachedStructProvider.Struct testObject) => TestObject = testObject;
}
private class Receiver11
{
public int? TestObject { get; private set; }
[BackgroundDependencyLoader]
private void load(int? testObject) => TestObject = testObject;
}
private class Receiver12
{
[BackgroundDependencyLoader]
private void load(int testObject)
{
}
}
private class Receiver13
{
public int? TestObject { get; private set; } = 1;
[BackgroundDependencyLoader(true)]
private void load(int testObject) => TestObject = testObject;
}
}
}
| |
/*
* Copyright (c) Brock Allen. All rights reserved.
* see license.txt
*
* Code borrowed from: https://github.com/brockallen/BrockAllen.MembershipReboot/tree/master/src/BrockAllen.MembershipReboot/Crypto
*/
namespace IdentityBase.Crypto
{
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
public interface ICrypto
{
string HashPassword(
string password,
int iterations);
bool VerifyPasswordHash(
string hashedPassword,
string password,
int iterations);
string GenerateSalt();
string Hash(string value);
}
public class DefaultCrypto : ICrypto
{
public const char PasswordHashingIterationCountSeparator = '.';
public string HashPassword(string password, int iterations)
{
if (iterations <= 0)
{
iterations = GetIterationsFromYear(GetCurrentYear());
}
string result = HashPasswordInternal(password, iterations);
return EncodeIterations(iterations) +
PasswordHashingIterationCountSeparator +
result;
}
public bool VerifyPasswordHash(
string hashedPassword,
string password,
int iterations)
{
if (!hashedPassword.Contains(
DefaultCrypto.PasswordHashingIterationCountSeparator))
{
return this.VerifyPasswordHashInternal(
hashedPassword,
password,
PBKDF2IterCount
);
}
string[] parts = hashedPassword
.Split(PasswordHashingIterationCountSeparator);
if (parts.Length != 2)
{
return false;
}
int count = DecodeIterations(parts[0]);
if (count <= 0)
{
return false;
}
hashedPassword = parts[1];
return this.VerifyPasswordHashInternal(
hashedPassword,
password,
count
);
}
// From OWASP : https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
public const int StartYear = 2016;
public const int StartCount = 1000;
public int GetIterationsFromYear(int year)
{
if (year <= StartYear)
{
return StartCount;
}
int diff = (year - StartYear) / 2;
int mul = (int)Math.Pow(2, diff);
int count = StartCount * mul;
// if we go negative, then we wrapped (expected in year ~2044).
// Int32.Max is best we can do at this point
if (count < 0)
{
count = Int32.MaxValue;
}
return count;
}
public virtual int GetCurrentYear()
{
return DateTime.Now.Year;
}
public string EncodeIterations(int count)
{
return count.ToString("X");
}
public const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
public const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
public const int SaltSize = 128 / 8; // 128 bits
public string HashPasswordInternal(string password, int iterations)
{
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
// Produce a version 0 (see comment above) password hash.
byte[] salt;
byte[] subkey;
using (var deriveBytes = new Rfc2898DeriveBytes(
password, SaltSize, iterations))
{
salt = deriveBytes.Salt;
subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
}
byte[] outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize,
PBKDF2SubkeyLength);
return Convert.ToBase64String(outputBytes);
}
public bool VerifyPasswordHashInternal(
string passwordHash,
string password,
int iterationCount)
{
if (passwordHash == null)
{
throw new ArgumentNullException("hashedPassword");
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] hashedPasswordBytes = Convert.FromBase64String(passwordHash);
// Verify a version 0 (see comment above) password hash.
if (hashedPasswordBytes.Length !=
(1 + SaltSize + PBKDF2SubkeyLength) ||
hashedPasswordBytes[0] != 0x00)
{
// Wrong length or version header.
return false;
}
byte[] salt = new byte[SaltSize];
Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize);
byte[] storedSubkey = new byte[PBKDF2SubkeyLength];
Buffer.BlockCopy(
hashedPasswordBytes,
1 + SaltSize,
storedSubkey,
0,
PBKDF2SubkeyLength
);
byte[] generatedSubkey;
using (Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(
password,
salt,
iterationCount)
)
{
generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
}
return ByteArraysEqual(storedSubkey, generatedSubkey);
}
public int DecodeIterations(string prefix)
{
int val;
if (Int32.TryParse(
prefix,
System.Globalization.NumberStyles.HexNumber,
null,
out val)
)
{
return val;
}
return -1;
}
/// <summary>
/// Compares two byte arrays for equality. The method is specifically
/// written so that the loop is not optimized.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.NoOptimization)]
public bool ByteArraysEqual(byte[] a, byte[] b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
bool areSame = true;
for (int i = 0; i < a.Length; i++)
{
areSame &= (a[i] == b[i]);
}
return areSame;
}
public string GenerateSalt()
{
var buf = new byte[SaltSize];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(buf);
}
return Convert.ToBase64String(buf);
}
public string Hash(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
return Hash(Encoding.UTF8.GetBytes(input));
}
public string Hash(byte[] input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
using (HashAlgorithm alg = SHA256.Create())
{
if (alg == null)
{
//String.Format(CultureInfo.InvariantCulture, HelpersResources.Crypto_NotSupportedHashAlg, algorithm));
throw new InvalidOperationException();
}
byte[] hashData = alg.ComputeHash(input);
return this.BinaryToHex(hashData);
}
}
internal string BinaryToHex(byte[] data)
{
char[] hex = new char[data.Length * 2];
for (int iter = 0; iter < data.Length; iter++)
{
byte hexChar = ((byte)(data[iter] >> 4));
hex[iter * 2] = (char)(hexChar > 9 ?
hexChar + 0x37 :
hexChar + 0x30);
hexChar = ((byte)(data[iter] & 0xF));
hex[(iter * 2) + 1] = (char)(hexChar > 9 ?
hexChar + 0x37 :
hexChar + 0x30);
}
return new string(hex);
}
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
using System.Linq;
namespace Zenject
{
// Zero parameter
public class CommandBindingFinalizer<TCommand, THandler>
: CommandBindingFinalizerBase<TCommand, THandler, Action>
where TCommand : Command
{
readonly Func<THandler, Action> _methodGetter;
public CommandBindingFinalizer(
BindInfo bindInfo,
Func<THandler, Action> methodGetter, Func<IProvider> handlerProviderFactory)
: base(bindInfo, handlerProviderFactory)
{
_methodGetter = methodGetter;
}
// The returned delegate is executed every time the command is executed
protected override Action GetCommandAction(
IProvider handlerProvider, InjectContext handlerInjectContext)
{
// Here we lazily create/get the handler instance when the command is called
// If using AsSingle this might re-use an existing instance
// If using AsTransient this will create a new instance
return () =>
{
var handler = (THandler)handlerProvider.TryGetInstance(handlerInjectContext);
// Null check is necessary when using ToOptionalResolve
if (handler != null)
{
_methodGetter(handler)();
}
};
}
}
// One parameter
public class CommandBindingFinalizer<TCommand, THandler, TParam1>
: CommandBindingFinalizerBase<TCommand, THandler, Action<TParam1>>
where TCommand : Command<TParam1>
{
readonly Func<THandler, Action<TParam1>> _methodGetter;
public CommandBindingFinalizer(
BindInfo bindInfo,
Func<THandler, Action<TParam1>> methodGetter,
Func<IProvider> handlerProviderFactory)
: base(bindInfo, handlerProviderFactory)
{
_methodGetter = methodGetter;
}
// The returned delegate is executed every time the command is executed
protected override Action<TParam1> GetCommandAction(
IProvider handlerProvider, InjectContext handlerInjectContext)
{
// Here we lazily create/get the handler instance when the command is called
// If using AsSingle this might re-use an existing instance
// If using AsTransient this will create a new instance
return (p1) =>
{
var handler = (THandler)handlerProvider.TryGetInstance(handlerInjectContext);
// Null check is necessary when using ToOptionalResolve
if (handler != null)
{
_methodGetter(handler)(p1);
}
};
}
}
// Two parameters
public class CommandBindingFinalizer<TCommand, THandler, TParam1, TParam2>
: CommandBindingFinalizerBase<TCommand, THandler, Action<TParam1, TParam2>>
where TCommand : Command<TParam1, TParam2>
{
readonly Func<THandler, Action<TParam1, TParam2>> _methodGetter;
public CommandBindingFinalizer(
BindInfo bindInfo,
Func<THandler, Action<TParam1, TParam2>> methodGetter,
Func<IProvider> handlerProviderFactory)
: base(bindInfo, handlerProviderFactory)
{
_methodGetter = methodGetter;
}
// The returned delegate is executed every time the command is executed
protected override Action<TParam1, TParam2> GetCommandAction(
IProvider handlerProvider, InjectContext handlerInjectContext)
{
// Here we lazily create/get the handler instance when the command is called
// If using AsSingle this might re-use an existing instance
// If using AsTransient this will create a new instance
return (p1, p2) =>
{
var handler = (THandler)handlerProvider.TryGetInstance(handlerInjectContext);
// Null check is necessary when using ToOptionalResolve
if (handler != null)
{
_methodGetter(handler)(p1, p2);
}
};
}
}
// Three parameters
public class CommandBindingFinalizer<TCommand, THandler, TParam1, TParam2, TParam3>
: CommandBindingFinalizerBase<TCommand, THandler, Action<TParam1, TParam2, TParam3>>
where TCommand : Command<TParam1, TParam2, TParam3>
{
readonly Func<THandler, Action<TParam1, TParam2, TParam3>> _methodGetter;
public CommandBindingFinalizer(
BindInfo bindInfo,
Func<THandler, Action<TParam1, TParam2, TParam3>> methodGetter,
Func<IProvider> handlerProviderFactory)
: base(bindInfo, handlerProviderFactory)
{
_methodGetter = methodGetter;
}
// The returned delegate is executed every time the command is executed
protected override Action<TParam1, TParam2, TParam3> GetCommandAction(
IProvider handlerProvider, InjectContext handlerInjectContext)
{
// Here we lazily create/get the handler instance when the command is called
// If using AsSingle this might re-use an existing instance
// If using AsTransient this will create a new instance
return (p1, p2, p3) =>
{
var handler = (THandler)handlerProvider.TryGetInstance(handlerInjectContext);
// Null check is necessary when using ToOptionalResolve
if (handler != null)
{
_methodGetter(handler)(p1, p2, p3);
}
};
}
}
// Four parameters
public class CommandBindingFinalizer<TCommand, THandler, TParam1, TParam2, TParam3, TParam4>
: CommandBindingFinalizerBase<TCommand, THandler, Action<TParam1, TParam2, TParam3, TParam4>>
where TCommand : Command<TParam1, TParam2, TParam3, TParam4>
{
readonly Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> _methodGetter;
public CommandBindingFinalizer(
BindInfo bindInfo,
Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter,
Func<IProvider> handlerProviderFactory)
: base(bindInfo, handlerProviderFactory)
{
_methodGetter = methodGetter;
}
// The returned delegate is executed every time the command is executed
protected override Action<TParam1, TParam2, TParam3, TParam4> GetCommandAction(
IProvider handlerProvider, InjectContext handlerInjectContext)
{
// Here we lazily create/get the handler instance when the command is called
// If using AsSingle this might re-use an existing instance
// If using AsTransient this will create a new instance
return (p1, p2, p3, p4) =>
{
var handler = (THandler)handlerProvider.TryGetInstance(handlerInjectContext);
// Null check is necessary when using ToOptionalResolve
if (handler != null)
{
_methodGetter(handler)(p1, p2, p3, p4);
}
};
}
}
// Five parameters
public class CommandBindingFinalizer<TCommand, THandler, TParam1, TParam2, TParam3, TParam4, TParam5>
: CommandBindingFinalizerBase<TCommand, THandler, ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5>>
where TCommand : Command<TParam1, TParam2, TParam3, TParam4, TParam5>
{
readonly Func<THandler, ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5>> _methodGetter;
public CommandBindingFinalizer(
BindInfo bindInfo,
Func<THandler, ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5>> methodGetter,
Func<IProvider> handlerProviderFactory)
: base(bindInfo, handlerProviderFactory)
{
_methodGetter = methodGetter;
}
// The returned delegate is executed every time the command is executed
protected override ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5> GetCommandAction(
IProvider handlerProvider, InjectContext handlerInjectContext)
{
// Here we lazily create/get the handler instance when the command is called
// If using AsSingle this might re-use an existing instance
// If using AsTransient this will create a new instance
return (p1, p2, p3, p4, p5) =>
{
var handler = (THandler)handlerProvider.TryGetInstance(handlerInjectContext);
// Null check is necessary when using ToOptionalResolve
if (handler != null)
{
_methodGetter(handler)(p1, p2, p3, p4, p5);
}
};
}
}
}
| |
using System;
namespace TomShane.Neoforce.External.Zip
{
internal class ZipEntry
{
private const int ZipEntrySignature = 0x04034b50;
private const int ZipEntryDataDescriptorSignature= 0x08074b50;
private bool _Debug = false;
private DateTime _LastModified;
public DateTime LastModified
{
get { return _LastModified; }
}
// when this is set, we trim the volume (eg C:\) off any fully-qualified pathname,
// before writing the ZipEntry into the ZipFile.
private bool _TrimVolumeFromFullyQualifiedPaths= true; // by default, trim them.
public bool TrimVolumeFromFullyQualifiedPaths
{
get { return _TrimVolumeFromFullyQualifiedPaths; }
set { _TrimVolumeFromFullyQualifiedPaths= value; }
}
private string _FileName;
public string FileName
{
get { return _FileName; }
}
private Int16 _VersionNeeded;
public Int16 VersionNeeded
{
get { return _VersionNeeded; }
}
private Int16 _BitField;
public Int16 BitField
{
get { return _BitField; }
}
private Int16 _CompressionMethod;
public Int16 CompressionMethod
{
get { return _CompressionMethod; }
}
private Int32 _CompressedSize;
public Int32 CompressedSize
{
get { return _CompressedSize; }
}
private Int32 _UncompressedSize;
public Int32 UncompressedSize
{
get { return _UncompressedSize; }
}
public Double CompressionRatio
{
get
{
return 100 * (1.0 - (1.0 * CompressedSize) / (1.0 * UncompressedSize));
}
}
private Int32 _LastModDateTime;
private Int32 _Crc32;
private byte[] _Extra;
private byte[] __filedata;
private byte[] _FileData
{
get
{
if (__filedata == null)
{
}
return __filedata;
}
}
private System.IO.MemoryStream _UnderlyingMemoryStream;
private System.IO.Compression.DeflateStream _CompressedStream;
private System.IO.Compression.DeflateStream CompressedStream
{
get
{
if (_CompressedStream == null)
{
_UnderlyingMemoryStream = new System.IO.MemoryStream();
bool LeaveUnderlyingStreamOpen = true;
_CompressedStream = new System.IO.Compression.DeflateStream(_UnderlyingMemoryStream,
System.IO.Compression.CompressionMode.Compress,
LeaveUnderlyingStreamOpen);
}
return _CompressedStream;
}
}
private byte[] _header;
internal byte[] Header
{
get
{
return _header;
}
}
private int _RelativeOffsetOfHeader;
private static bool ReadHeader(System.IO.Stream s, ZipEntry ze)
{
int signature = TomShane.Neoforce.External.Zip.Shared.ReadSignature(s);
// return null if this is not a local file header signature
if (SignatureIsNotValid(signature))
{
s.Seek(-4, System.IO.SeekOrigin.Current);
if (ze._Debug) System.Console.WriteLine(" ZipEntry::Read(): Bad signature ({0:X8}) at position {1}", signature, s.Position);
return false;
}
byte[] block = new byte[26];
int n = s.Read(block, 0, block.Length);
if (n != block.Length) return false;
int i = 0;
ze._VersionNeeded = (short)(block[i++] + block[i++] * 256);
ze._BitField = (short)(block[i++] + block[i++] * 256);
ze._CompressionMethod = (short)(block[i++] + block[i++] * 256);
ze._LastModDateTime = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
// the PKZIP spec says that if bit 3 is set (0x0008), then the CRC, Compressed size, and uncompressed size
// come directly after the file data. The only way to find it is to scan the zip archive for the signature of
// the Data Descriptor, and presume that that signature does not appear in the (compressed) data of the compressed file.
if ((ze._BitField & 0x0008) != 0x0008)
{
ze._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._CompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._UncompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
}
else
{
// the CRC, compressed size, and uncompressed size are stored later in the stream.
// here, we advance the pointer.
i += 12;
}
Int16 filenameLength = (short)(block[i++] + block[i++] * 256);
Int16 extraFieldLength = (short)(block[i++] + block[i++] * 256);
block = new byte[filenameLength];
n = s.Read(block, 0, block.Length);
ze._FileName = TomShane.Neoforce.External.Zip.Shared.StringFromBuffer(block, 0, block.Length);
ze._Extra = new byte[extraFieldLength];
n = s.Read(ze._Extra, 0, ze._Extra.Length);
// transform the time data into something usable
ze._LastModified = TomShane.Neoforce.External.Zip.Shared.PackedToDateTime(ze._LastModDateTime);
// actually get the compressed size and CRC if necessary
if ((ze._BitField & 0x0008) == 0x0008)
{
long posn = s.Position;
long SizeOfDataRead = TomShane.Neoforce.External.Zip.Shared.FindSignature(s, ZipEntryDataDescriptorSignature);
if (SizeOfDataRead == -1) return false;
// read 3x 4-byte fields (CRC, Compressed Size, Uncompressed Size)
block = new byte[12];
n = s.Read(block, 0, block.Length);
if (n != 12) return false;
i = 0;
ze._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._CompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._UncompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
if (SizeOfDataRead != ze._CompressedSize)
throw new Exception("Data format error (bit 3 is set)");
// seek back to previous position, to read file data
s.Seek(posn, System.IO.SeekOrigin.Begin);
}
return true;
}
private static bool SignatureIsNotValid(int signature)
{
return (signature != ZipEntrySignature);
}
public static ZipEntry Read(System.IO.Stream s)
{
return Read(s, false);
}
internal static ZipEntry Read(System.IO.Stream s, bool TurnOnDebug)
{
ZipEntry entry = new ZipEntry();
entry._Debug = TurnOnDebug;
if (!ReadHeader(s, entry)) return null;
entry.__filedata = new byte[entry.CompressedSize];
int n = s.Read(entry._FileData, 0, entry._FileData.Length);
if (n != entry._FileData.Length)
{
throw new Exception("badly formatted zip file.");
}
// finally, seek past the (already read) Data descriptor if necessary
if ((entry._BitField & 0x0008) == 0x0008)
{
s.Seek(16, System.IO.SeekOrigin.Current);
}
return entry;
}
internal static ZipEntry Create(String filename)
{
ZipEntry entry = new ZipEntry();
entry._FileName = filename;
entry._LastModified = System.IO.File.GetLastWriteTime(filename);
// adjust the time if the .NET BCL thinks it is in DST.
// see the note elsewhere in this file for more info.
if (entry._LastModified.IsDaylightSavingTime())
{
System.DateTime AdjustedTime = entry._LastModified - new System.TimeSpan(1, 0, 0);
entry._LastModDateTime = TomShane.Neoforce.External.Zip.Shared.DateTimeToPacked(AdjustedTime);
}
else
entry._LastModDateTime = TomShane.Neoforce.External.Zip.Shared.DateTimeToPacked(entry._LastModified);
// we don't actually slurp in the file until the caller invokes Write on this entry.
return entry;
}
public void Extract()
{
Extract(".");
}
public void Extract(System.IO.Stream s)
{
Extract(null, s);
}
public void Extract(string basedir)
{
Extract(basedir, null);
}
internal System.IO.Stream GetStream()
{
System.IO.MemoryStream memstream = new System.IO.MemoryStream(_FileData);
if (CompressedSize == UncompressedSize)
return memstream;
return new System.IO.Compression.DeflateStream(
memstream, System.IO.Compression.CompressionMode.Decompress);
}
// pass in either basedir or s, but not both.
// In other words, you can extract to a stream or to a directory, but not both!
private void Extract(string basedir, System.IO.Stream s)
{
string TargetFile = null;
if (basedir != null)
{
TargetFile = System.IO.Path.Combine(basedir, FileName);
// check if a directory
if (FileName.EndsWith("/"))
{
if (!System.IO.Directory.Exists(TargetFile))
System.IO.Directory.CreateDirectory(TargetFile);
return;
}
}
else if (s != null)
{
if (FileName.EndsWith("/"))
// extract a directory to streamwriter? nothing to do!
return;
}
else throw new Exception("Invalid input.");
using (System.IO.MemoryStream memstream = new System.IO.MemoryStream(_FileData))
{
System.IO.Stream input = null;
try
{
if (CompressedSize == UncompressedSize)
{
// the System.IO.Compression.DeflateStream class does not handle uncompressed data.
// so if an entry is not compressed, then we just translate the bytes directly.
input = memstream;
}
else
{
input = new System.IO.Compression.DeflateStream(memstream, System.IO.Compression.CompressionMode.Decompress);
}
if (TargetFile != null)
{
// ensure the target path exists
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(TargetFile)))
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(TargetFile));
}
}
System.IO.Stream output = null;
try
{
if (TargetFile != null)
output = new System.IO.FileStream(TargetFile, System.IO.FileMode.CreateNew);
else
output = s;
byte[] bytes = new byte[4096];
int n;
if (_Debug)
{
Console.WriteLine("{0}: _FileData.Length= {1}", TargetFile, _FileData.Length);
Console.WriteLine("{0}: memstream.Position: {1}", TargetFile, memstream.Position);
n = _FileData.Length;
if (n > 1000)
{
n = 500;
Console.WriteLine("{0}: truncating dump from {1} to {2} bytes...", TargetFile, _FileData.Length, n);
}
for (int j = 0; j < n; j += 2)
{
if ((j > 0) && (j % 40 == 0))
System.Console.WriteLine();
System.Console.Write(" {0:X2}", _FileData[j]);
if (j + 1 < n)
System.Console.Write("{0:X2}", _FileData[j + 1]);
}
System.Console.WriteLine("\n");
}
n = 1; // anything non-zero
while (n != 0)
{
if (_Debug) Console.WriteLine("{0}: about to read...", TargetFile);
n = input.Read(bytes, 0, bytes.Length);
if (_Debug) Console.WriteLine("{0}: got {1} bytes", TargetFile, n);
if (n > 0)
{
if (_Debug) Console.WriteLine("{0}: about to write...", TargetFile);
output.Write(bytes, 0, n);
}
}
}
finally
{
// we only close the output stream if we opened it.
if ((output != null) && (TargetFile != null))
{
output.Close();
output.Dispose();
}
}
if (TargetFile != null)
{
// We may have to adjust the last modified time to compensate
// for differences in how the .NET Base Class Library deals
// with daylight saving time (DST) versus how the Windows
// filesystem deals with daylight saving time. See
// http://blogs.msdn.com/oldnewthing/archive/2003/10/24/55413.aspx for some context.
// in a nutshell: Daylight savings time rules change regularly. In
// 2007, for example, the inception week of DST changed. In 1977,
// DST was in place all year round. in 1945, likewise. And so on.
// Win32 does not attempt to guess which time zone rules were in
// effect at the time in question. It will render a time as
// "standard time" and allow the app to change to DST as necessary.
// .NET makes a different choice.
// -------------------------------------------------------
// Compare the output of FileInfo.LastWriteTime.ToString("f") with
// what you see in the property sheet for a file that was last
// written to on the other side of the DST transition. For example,
// suppose the file was last modified on October 17, during DST but
// DST is not currently in effect. Explorer's file properties
// reports Thursday, October 17, 2003, 8:45:38 AM, but .NETs
// FileInfo reports Thursday, October 17, 2003, 9:45 AM.
// Win32 says, "Thursday, October 17, 2002 8:45:38 AM PST". Note:
// Pacific STANDARD Time. Even though October 17 of that year
// occurred during Pacific Daylight Time, Win32 displays the time as
// standard time because that's what time it is NOW.
// .NET BCL assumes that the current DST rules were in place at the
// time in question. So, .NET says, "Well, if the rules in effect
// now were also in effect on October 17, 2003, then that would be
// daylight time" so it displays "Thursday, October 17, 2003, 9:45
// AM PDT" - daylight time.
// So .NET gives a value which is more intuitively correct, but is
// also potentially incorrect, and which is not invertible. Win32
// gives a value which is intuitively incorrect, but is strictly
// correct.
// -------------------------------------------------------
// With this adjustment, I add one hour to the tweaked .NET time, if
// necessary. That is to say, if the time in question had occurred
// in what the .NET BCL assumed to be DST (an assumption that may be
// wrong given the constantly changing DST rules).
#if !XBOX
if (LastModified.IsDaylightSavingTime())
{
DateTime AdjustedLastModified = LastModified + new System.TimeSpan(1, 0, 0);
System.IO.File.SetLastWriteTime(TargetFile, AdjustedLastModified);
}
else
System.IO.File.SetLastWriteTime(TargetFile, LastModified);
#endif
}
}
finally
{
// we only close the output stream if we opened it.
// we cannot use using() here because in some cases we do not want to Dispose the stream!
if ((input != null) && (input != memstream))
{
input.Close();
input.Dispose();
}
}
}
}
internal void WriteCentralDirectoryEntry(System.IO.Stream s)
{
byte[] bytes = new byte[4096];
int i = 0;
// signature
bytes[i++] = (byte)(ZipDirEntry.ZipDirEntrySignature & 0x000000FF);
bytes[i++] = (byte)((ZipDirEntry.ZipDirEntrySignature & 0x0000FF00) >> 8);
bytes[i++] = (byte)((ZipDirEntry.ZipDirEntrySignature & 0x00FF0000) >> 16);
bytes[i++] = (byte)((ZipDirEntry.ZipDirEntrySignature & 0xFF000000) >> 24);
// Version Made By
bytes[i++] = Header[4];
bytes[i++] = Header[5];
// Version Needed, Bitfield, compression method, lastmod,
// crc, sizes, filename length and extra field length -
// are all the same as the local file header. So just copy them
int j = 0;
for (j = 0; j < 26; j++)
bytes[i + j] = Header[4 + j];
i += j; // positioned at next available byte
// File Comment Length
bytes[i++] = 0;
bytes[i++] = 0;
// Disk number start
bytes[i++] = 0;
bytes[i++] = 0;
// internal file attrs
bytes[i++] = 1;
bytes[i++] = 0;
// external file attrs
bytes[i++] = 0x20;
bytes[i++] = 0;
bytes[i++] = 0xb6;
bytes[i++] = 0x81;
// relative offset of local header (I think this can be zero)
bytes[i++] = (byte)(_RelativeOffsetOfHeader & 0x000000FF);
bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0xFF000000) >> 24);
if (_Debug) System.Console.WriteLine("\ninserting filename into CDS: (length= {0})", Header.Length - 30);
// actual filename (starts at offset 34 in header)
for (j = 0; j < Header.Length - 30; j++)
{
bytes[i + j] = Header[30 + j];
if (_Debug) System.Console.Write(" {0:X2}", bytes[i + j]);
}
if (_Debug) System.Console.WriteLine();
i += j;
s.Write(bytes, 0, i);
}
private void WriteHeader(System.IO.Stream s, byte[] bytes)
{
// write the header info
int i = 0;
// signature
bytes[i++] = (byte)(ZipEntrySignature & 0x000000FF);
bytes[i++] = (byte)((ZipEntrySignature & 0x0000FF00) >> 8);
bytes[i++] = (byte)((ZipEntrySignature & 0x00FF0000) >> 16);
bytes[i++] = (byte)((ZipEntrySignature & 0xFF000000) >> 24);
// version needed
Int16 FixedVersionNeeded = 0x14; // from examining existing zip files
bytes[i++] = (byte)(FixedVersionNeeded & 0x00FF);
bytes[i++] = (byte)((FixedVersionNeeded & 0xFF00) >> 8);
// bitfield
Int16 BitField = 0x00; // from examining existing zip files
bytes[i++] = (byte)(BitField & 0x00FF);
bytes[i++] = (byte)((BitField & 0xFF00) >> 8);
// compression method
Int16 CompressionMethod = 0x08; // 0x08 = Deflate
bytes[i++] = (byte)(CompressionMethod & 0x00FF);
bytes[i++] = (byte)((CompressionMethod & 0xFF00) >> 8);
// LastMod
bytes[i++] = (byte)(_LastModDateTime & 0x000000FF);
bytes[i++] = (byte)((_LastModDateTime & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_LastModDateTime & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_LastModDateTime & 0xFF000000) >> 24);
// CRC32 (Int32)
CRC32 crc32 = new CRC32();
UInt32 crc = 0;
using (System.IO.Stream input = System.IO.File.OpenRead(FileName))
{
crc = crc32.GetCrc32AndCopy(input, CompressedStream);
}
CompressedStream.Close(); // to get the footer bytes written to the underlying stream
bytes[i++] = (byte)(crc & 0x000000FF);
bytes[i++] = (byte)((crc & 0x0000FF00) >> 8);
bytes[i++] = (byte)((crc & 0x00FF0000) >> 16);
bytes[i++] = (byte)((crc & 0xFF000000) >> 24);
// CompressedSize (Int32)
Int32 isz = (Int32)_UnderlyingMemoryStream.Length;
UInt32 sz = (UInt32)isz;
bytes[i++] = (byte)(sz & 0x000000FF);
bytes[i++] = (byte)((sz & 0x0000FF00) >> 8);
bytes[i++] = (byte)((sz & 0x00FF0000) >> 16);
bytes[i++] = (byte)((sz & 0xFF000000) >> 24);
// UncompressedSize (Int32)
if (_Debug) System.Console.WriteLine("Uncompressed Size: {0}", crc32.TotalBytesRead);
bytes[i++] = (byte)(crc32.TotalBytesRead & 0x000000FF);
bytes[i++] = (byte)((crc32.TotalBytesRead & 0x0000FF00) >> 8);
bytes[i++] = (byte)((crc32.TotalBytesRead & 0x00FF0000) >> 16);
bytes[i++] = (byte)((crc32.TotalBytesRead & 0xFF000000) >> 24);
// filename length (Int16)
Int16 length = (Int16)FileName.Length;
// see note below about TrimVolumeFromFullyQualifiedPaths.
if ( (TrimVolumeFromFullyQualifiedPaths) && (FileName[1]==':') && (FileName[2]=='\\')) length-=3;
bytes[i++] = (byte)(length & 0x00FF);
bytes[i++] = (byte)((length & 0xFF00) >> 8);
// extra field length (short)
Int16 ExtraFieldLength = 0x00;
bytes[i++] = (byte)(ExtraFieldLength & 0x00FF);
bytes[i++] = (byte)((ExtraFieldLength & 0xFF00) >> 8);
// Tue, 27 Mar 2007 16:35
// Creating a zip that contains entries with "fully qualified" pathnames
// can result in a zip archive that is unreadable by Windows Explorer.
// Such archives are valid according to other tools but not to explorer.
// To avoid this, we can trim off the leading volume name and slash (eg
// c:\) when creating (writing) a zip file. We do this by default and we
// leave the old behavior available with the
// TrimVolumeFromFullyQualifiedPaths flag - set it to false to get the old
// behavior. It only affects zip creation.
// actual filename
char[] c = ( (TrimVolumeFromFullyQualifiedPaths) && (FileName[1]==':') && (FileName[2]=='\\')) ?
FileName.Substring(3).ToCharArray() : // trim off volume letter, colon, and slash
FileName.ToCharArray();
int j = 0;
if (_Debug)
{
System.Console.WriteLine("local header: writing filename, {0} chars", c.Length);
System.Console.WriteLine("starting offset={0}", i);
}
for (j = 0; (j < c.Length) && (i + j < bytes.Length); j++)
{
bytes[i + j] = System.BitConverter.GetBytes(c[j])[0];
if (_Debug) System.Console.Write(" {0:X2}", bytes[i + j]);
}
if (_Debug) System.Console.WriteLine();
i += j;
// extra field (we always write nothing in this implementation)
// ;;
// remember the file offset of this header
_RelativeOffsetOfHeader = (int)s.Length;
if (_Debug)
{
System.Console.WriteLine("\nAll header data:");
for (j = 0; j < i; j++)
System.Console.Write(" {0:X2}", bytes[j]);
System.Console.WriteLine();
}
// finally, write the header to the stream
s.Write(bytes, 0, i);
// preserve this header data for use with the central directory structure.
_header = new byte[i];
if (_Debug) System.Console.WriteLine("preserving header of {0} bytes", _header.Length);
for (j = 0; j < i; j++)
_header[j] = bytes[j];
}
internal void Write(System.IO.Stream s)
{
byte[] bytes = new byte[4096];
int n;
// write the header:
WriteHeader(s, bytes);
// write the actual file data:
_UnderlyingMemoryStream.Position = 0;
if (_Debug)
{
Console.WriteLine("{0}: writing compressed data to zipfile...", FileName);
Console.WriteLine("{0}: total data length: {1}", FileName, _UnderlyingMemoryStream.Length);
}
while ((n = _UnderlyingMemoryStream.Read(bytes, 0, bytes.Length)) != 0)
{
if (_Debug)
{
Console.WriteLine("{0}: transferring {1} bytes...", FileName, n);
for (int j = 0; j < n; j += 2)
{
if ((j > 0) && (j % 40 == 0))
System.Console.WriteLine();
System.Console.Write(" {0:X2}", bytes[j]);
if (j + 1 < n)
System.Console.Write("{0:X2}", bytes[j + 1]);
}
System.Console.WriteLine("\n");
}
s.Write(bytes, 0, n);
}
//_CompressedStream.Close();
//_CompressedStream= null;
_UnderlyingMemoryStream.Close();
_UnderlyingMemoryStream = null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MasterChef.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ZlibStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-31 14:53:33>
//
// ------------------------------------------------------------------
//
// This module defines the ZlibStream class, which is similar in idea to
// the System.IO.Compression.DeflateStream and
// System.IO.Compression.GZipStream classes in the .NET BCL.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace EpLibrary.cs
{
/// <summary>
/// Represents a Zlib stream for compression or decompression.
/// </summary>
/// <remarks>
///
/// <para>
/// The ZlibStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any
/// stream.
/// </para>
///
/// <para> Using this stream, applications can compress or decompress data via
/// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or
/// decompression can occur through either reading or writing. The compression
/// format used is ZLIB, which is documented in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed
/// Data Format Specification version 3.3". This implementation of ZLIB always uses
/// DEFLATE as the compression method. (see <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE
/// Compressed Data Format Specification version 1.3.") </para>
///
/// <para>
/// The ZLIB format allows for varying compression methods, window sizes, and dictionaries.
/// This implementation always uses the DEFLATE compression method, a preset dictionary,
/// and 15 window bits by default.
/// </para>
///
/// <para>
/// This class is similar to <see cref="DeflateStream"/>, except that it adds the
/// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects
/// the RFC1950 header and trailer bytes when decompressing. It is also similar to the
/// <see cref="GZipStream"/>.
/// </para>
/// </remarks>
/// <seealso cref="DeflateStream" />
/// <seealso cref="GZipStream" />
public class ZlibStream : System.IO.Stream
{
internal ZlibBaseStream _baseStream;
bool _disposed;
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c>
/// will use the default compression level. The "captive" stream will be
/// closed when the <c>ZlibStream</c> is closed.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example uses a <c>ZlibStream</c> to compress a file, and writes the
/// compressed data to another file.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".zlib")
/// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and
/// the specified <c>CompressionLevel</c>.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored.
/// The "captive" stream will be closed when the <c>ZlibStream</c> is closed.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the
/// compressed data to another file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (Stream compressor = new ZlibStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".zlib")
/// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and
/// explicitly specify whether the captive stream should be left open after
/// Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use
/// the default compression level.
/// </para>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// <see cref="System.IO.MemoryStream"/> that will be re-read after
/// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream
/// open.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
///
/// </remarks>
///
/// <param name="stream">The stream which will be read or written. This is called the
/// "captive" stream in other places in this documentation.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain
/// open after inflation/deflation.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>
/// and the specified <c>CompressionLevel</c>, and explicitly specify
/// whether the stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive
/// stream remain open after the deflation or inflation occurs. By
/// default, after <c>Close()</c> is called on the stream, the captive
/// stream is also closed. In some cases this is not desired, for example
/// if the stream is a <see cref="System.IO.MemoryStream"/> that will be
/// re-read after compression. Specify true for the <paramref
/// name="leaveOpen"/> parameter to leave the stream open.
/// </para>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is
/// ignored.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a ZlibStream to compress the data from a file,
/// and store the result into another file. The filestream remains open to allow
/// additional data to be written to it.
///
/// <code>
/// using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// // can write additional data to the output stream here
/// }
/// </code>
/// <code lang="VB">
/// Using output As FileStream = File.Create(fileToCompress & ".zlib")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// ' can write additional data to the output stream here.
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
///
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
///
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after
/// inflation/deflation.
/// </param>
///
/// <param name="level">
/// A tuning knob to trade speed for effectiveness. This parameter is
/// effective only when mode is <c>CompressionMode.Compress</c>.
/// </param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// Sorry, though, not sure exactly how to describe all the various settings.
/// </summary>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get { return this._baseStream._z.TotalBytesIn; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get { return this._baseStream._z.TotalBytesOut; }
}
#endregion
#region System.IO.Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// This method may be invoked in two distinct scenarios. If disposing
/// == true, the method has been called directly or indirectly by a
/// user's code, for example via the public Dispose() method. In this
/// case, both managed and unmanaged resources can be referenced and
/// disposed. If disposing == false, the method has been called by the
/// runtime from inside the object finalizer and this method should not
/// reference other objects; in that case only unmanaged resources must
/// be referenced or disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
this._baseStream.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotSupportedException"/>.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotSupportedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut;
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Read data from the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// If you wish to use the <c>ZlibStream</c> to compress data while reading,
/// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>,
/// providing an uncompressed data stream. Then call <c>Read()</c> on that
/// <c>ZlibStream</c>, and the data read will be compressed. If you wish to
/// use the <c>ZlibStream</c> to decompress data while reading, you can create
/// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a
/// readable compressed data stream. Then call <c>Read()</c> on that
/// <c>ZlibStream</c>, and the data will be decompressed as it is read.
/// </para>
///
/// <para>
/// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but
/// not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">
/// The buffer into which the read data should be placed.</param>
///
/// <param name="offset">
/// the offset within that data array to put the first byte read.</param>
///
/// <param name="count">the number of bytes to read.</param>
///
/// <returns>the number of bytes read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="offset">
/// The offset to seek to....
/// IF THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <param name="origin">
/// The reference specifying how to apply the offset.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
///
/// <returns>nothing. This method always throws.</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="value">
/// The new value for the stream length.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// If you wish to use the <c>ZlibStream</c> to compress data while writing,
/// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>,
/// and a writable output stream. Then call <c>Write()</c> on that
/// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to
/// the output stream will be the compressed form of the data written. If you
/// wish to use the <c>ZlibStream</c> to decompress data while writing, you
/// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that stream,
/// providing previously compressed data. The data sent to the output stream
/// will be the decompressed form of the data written.
/// </para>
///
/// <para>
/// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
_baseStream.Write(buffer, offset, count);
}
#endregion
/// <summary>
/// Compress a string into a byte array using ZLIB.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="ZlibStream.UncompressString(byte[])"/>
/// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
/// <seealso cref="GZipStream.CompressString(string)"/>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new MemoryStream())
{
Stream compressor =
new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using ZLIB.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="ZlibStream.CompressString(string)"/>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new MemoryStream())
{
Stream compressor =
new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a ZLIB-compressed byte array into a single string.
/// </summary>
///
/// <seealso cref="ZlibStream.CompressString(String)"/>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing ZLIB-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor =
new ZlibStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a ZLIB-compressed byte array into a byte array.
/// </summary>
///
/// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
/// <seealso cref="ZlibStream.UncompressString(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing ZLIB-compressed data.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor =
new ZlibStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Banzai.Utility;
namespace Banzai.Factories
{
/// <summary>
/// Allows the construction of a root flow.
/// </summary>
/// <typeparam name="T">Type of the flow subject.</typeparam>
public interface IFlowBuilder<out T>
{
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <typeparam name="TNode">Type of the node to add.</typeparam>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Flows default to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> AddRoot<TNode>(string name = null, string id = null) where TNode : INode<T>;
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <param name="nodeType">Type of the node to add.</param>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Flows default to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> AddRoot(Type nodeType, string name = null, string id = null);
}
/// <summary>
/// Allows the addition of flow components (nodes or subflows) to a parent flow or component.
/// </summary>
/// <typeparam name="T">Type of the flow subject.</typeparam>
public interface IFlowComponentBuilder<out T>
{
/// <summary>
/// Adds a previously registered flow by name as a child of this node.
/// </summary>
/// <param name="name">The name of the flow to add.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Defaults to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> AddFlow(string name, string id = null);
/// <summary>
/// Adds a previously registered flow by name as a child of this node.
/// </summary>
/// <param name="name">The name of the flow to add.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Defaults to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> AddFlow<TNode>(string name, string id = null);
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <typeparam name="TNode">Type of the node to add.</typeparam>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the node. This can be used for identification in debugging. Defaults to the node type with the name if included.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> AddChild<TNode>(string name = null, string id = null) where TNode : INode<T>;
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <param name="nodeType">Type of the node to add.</param>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the node. This can be used for identification in debugging. Defaults to the node type with the name if included.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> AddChild(Type nodeType, string name = null, string id = null);
/// <summary>
/// Adds a ShouldExecuteBlock to the flowcomponent (to be added to the resultant node).
/// </summary>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> SetShouldExecuteBlock<TBlock>() where TBlock : IShouldExecuteBlock<T>;
/// <summary>
/// Adds a ShouldExecuteBlock to the flowcomponent (to be added to the resultant node).
/// </summary>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> SetShouldExecuteBlock(Type blockType);
/// <summary>
/// Adds a ShouldExecuteAsync to the flowcomponent (to be added to the resultant node).
/// </summary>
/// <param name="shouldExecuteFunc">Function to add as ShouldExecute to the flowcomponent.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
IFlowComponentBuilder<T> SetShouldExecute(Func<IExecutionContext<T>, Task<bool>> shouldExecuteFunc);
/// <summary>
/// Allows metadata about the flow component to be added.
/// </summary>
/// <param name="key">Key of the data to add.</param>
/// <param name="data">Data to add.</param>
/// <returns></returns>
IFlowComponentBuilder<T> SetMetaData(string key, object data);
/// <summary>
/// Returns an instance of FlowComponent representing the requested child node.
/// </summary>
/// <typeparam name="TNode">Type of the node.</typeparam>
/// <param name="name">Optional name of the node in IOC registration.</param>
/// <param name="index">Index of the node if multiple matches are found in the parent. Defaults to first.</param>
/// <returns>A builder for the located child FlowComponent of this FlowComponent.</returns>
IFlowComponentBuilder<T> ForChild<TNode>(string name = null, int index = 0) where TNode : INode<T>;
/// <summary>
/// Returns an instance of FlowComponent representing the requested child node.
/// </summary>
/// <param name="nodeType">Type of the node.</param>
/// <param name="name">Optional name of the node in IOC registration.</param>
/// <param name="index">Index of the node if multiple matches are found in the parent. Defaults to first.</param>
/// <returns>A builder for the located child FlowComponent of this FlowComponent.</returns>
IFlowComponentBuilder<T> ForChild(Type nodeType, string name = null, int index = 0);
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the requested child flow.
/// </summary>
/// <param name="name">Optional name of the child flow in IOC registration.</param>
/// <param name="index">Index of the node if multiple matches are found in the parent. Defaults to first.</param>
/// <returns>A child FlowComponentBuilder of this FlowComponentBuilder.</returns>
IFlowComponentBuilder<T> ForChildFlow(string name = null, int index = 0);
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the last child of the current builder.
/// </summary>
/// <returns>A child FlowComponentBuilder of this FlowComponentBuilder.</returns>
IFlowComponentBuilder<T> ForLastChild();
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the requested parent.
/// </summary>
/// <returns>A parent FlowComponentBuilder of this FlowComponentBuilder.</returns>
IFlowComponentBuilder<T> ForParent();
}
/// <summary>
/// Allows the addition of flow components (nodes or subflows) to a parent flow or component.
/// Also underlies the FlowBuilder.
/// </summary>
/// <typeparam name="T">Type of the flow subject.</typeparam>
public class FlowComponentBuilder<T> : IFlowComponentBuilder<T>, IFlowBuilder<T>
{
private readonly FlowComponent<T> _component;
/// <summary>
/// Constructs a new FlowComponentBuilder.
/// </summary>
/// <param name="component">FlowComponent to build up.</param>
public FlowComponentBuilder(FlowComponent<T> component)
{
_component = component;
}
/// <summary>
/// Adds a previously registered flow by name as a child of this node.
/// </summary>
/// <param name="name">The name of the flow to add.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Defaults to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> AddFlow(string name, string id = null)
{
return AddFlow<T>(name, id);
}
/// <summary>
/// Adds a previously registered flow by name as a child of this node.
/// </summary>
/// <param name="name">The name of the flow to add.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Defaults to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> AddFlow<TNode>(string name, string id = null)
{
Guard.AgainstNullOrEmptyArgument("name", name);
if (!typeof(IMultiNode<T>).IsAssignableFrom(_component.Type))
throw new InvalidOperationException("In order to have children, nodeType must be assignable to IMultiNode<T>.");
_component.AddChild(new FlowComponent<T> { Type = typeof(TNode), Name = name, IsFlow = true, Id = string.IsNullOrEmpty(id)?name:id });
return this;
}
/// <summary>
/// Adds a root node to this flow.
/// </summary>
/// <typeparam name="TNode">Type of the node to add.</typeparam>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Flows default to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> AddRoot<TNode>(string name = null, string id = null) where TNode : INode<T>
{
return AddRoot(typeof(TNode), name, id);
}
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <param name="nodeType">Type of the node to add.</param>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the flow. This can be used for identification in debugging. Flows default to the flow name.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> AddRoot(Type nodeType, string name = null, string id = null)
{
if (!_component.IsFlow)
throw new InvalidOperationException("This method is only valid for flow components.");
if (!typeof(INode<T>).IsAssignableFrom(nodeType))
throw new ArgumentException("nodeType must be assignable to INode<T>.", nameof(nodeType));
var child = _component.AddChild(new FlowComponent<T> { Type = nodeType, Name = name, Id = string.IsNullOrEmpty(id)?name:id });
return new FlowComponentBuilder<T>(child);
}
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <typeparam name="TNode">Type of the node to add.</typeparam>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the node. This can be used for identification in debugging. Defaults to the node type with the name if included.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> AddChild<TNode>(string name = null, string id = null) where TNode : INode<T>
{
return AddChild(typeof(TNode), name, id);
}
/// <summary>
/// Adds a child node to this flow.
/// </summary>
/// <param name="nodeType">Type of the node to add.</param>
/// <param name="name">Optional name of the node if needed to find in IOC container.</param>
/// <param name="id">Id of the node. This can be used for identification in debugging. Defaults to the node type with the name if included.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> AddChild(Type nodeType, string name = null, string id = null)
{
if (!typeof(INode<T>).IsAssignableFrom(nodeType))
throw new ArgumentException("nodeType must be assignable to INode<T>.", nameof(nodeType));
if (!typeof(IMultiNode<T>).IsAssignableFrom(_component.Type))
throw new InvalidOperationException("In order to have children, nodeType must be assignable to IMultiNode<T>.");
_component.AddChild(new FlowComponent<T> { Type = nodeType, Name = name, Id = id });
return this;
}
/// <summary>
/// Adds a ShouldExecuteBlock to the flowcomponent (to be added to the resultant node).
/// </summary>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> SetShouldExecuteBlock<TBlock>() where TBlock : IShouldExecuteBlock<T>
{
_component.SetShouldExecute(typeof(TBlock));
return this;
}
/// <summary>
/// Adds a ShouldExecuteBlock to the flowcomponent (to be added to the resultant node).
/// </summary>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> SetShouldExecuteBlock(Type blockType)
{
_component.SetShouldExecute(blockType);
return this;
}
/// <summary>
/// Adds a ShouldExecuteAsync to the FlowComponent (to be added to the resultant node).
/// </summary>
/// <param name="shouldExecuteFunc">Function to add as ShouldExecute to the flowcomponent.</param>
/// <returns>The current FlowComponentBuilder instance.</returns>
public IFlowComponentBuilder<T> SetShouldExecute(Func<IExecutionContext<T>, Task<bool>> shouldExecuteFunc)
{
_component.SetShouldExecute(shouldExecuteFunc);
return this;
}
/// <summary>
/// Allows metadata about the flow component to be added.
/// </summary>
/// <param name="key">Key of the data to add.</param>
/// <param name="data">Data to add.</param>
/// <returns></returns>
public IFlowComponentBuilder<T> SetMetaData(string key, object data)
{
if (_component.MetaData.ContainsKey(key))
_component.MetaData[key] = data;
else
_component.MetaData.Add(key, data);
return this;
}
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the requested child node.
/// </summary>
/// <typeparam name="TNode">Type of the node.</typeparam>
/// <param name="name">Optional name of the node in IOC registration.</param>
/// <param name="index">Index of the node if multiple matches are found in the parent. Defaults to first.</param>
/// <returns>A child FlowComponentBuilder of this FlowComponentBuilder.</returns>
public IFlowComponentBuilder<T> ForChild<TNode>(string name = null, int index = 0) where TNode : INode<T>
{
return ForChild(typeof(TNode), name, index);
}
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the requested child node.
/// </summary>
/// <param name="nodeType">Type of the node.</param>
/// <param name="name">Optional name of the node in IOC registration.</param>
/// <param name="index">Index of the node if multiple matches are found in the parent. Defaults to first.</param>
/// <returns>A child FlowComponentBuilder of this FlowComponentBuilder.</returns>
public IFlowComponentBuilder<T> ForChild(Type nodeType, string name = null, int index = 0)
{
if (!typeof(INode<T>).IsAssignableFrom(nodeType))
throw new ArgumentException("nodeType must be assignable to INode<T>.", nameof(nodeType));
var items = _component.Children.Where(x => x.Type == nodeType);
if (name != null)
items = items.Where(x => x.Name == name);
IList<FlowComponent<T>> results = items.ToList();
if (index + 1 > results.Count)
throw new IndexOutOfRangeException("The requested child could not be found.");
var child = results[index];
return new FlowComponentBuilder<T>(child);
}
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the requested child flow.
/// </summary>
/// <param name="name">Optional name of the node in IOC registration.</param>
/// <param name="index">Index of the node if multiple matches are found in the parent. Defaults to first.</param>
/// <returns>A child FlowComponentBuilder of this FlowComponentBuilder.</returns>
public IFlowComponentBuilder<T> ForChildFlow(string name = null, int index = 0)
{
var items = _component.Children.Where(x => x.IsFlow);
if (name != null)
items = items.Where(x => x.Name == name);
IList<FlowComponent<T>> results = items.ToList();
if (index + 1 > results.Count)
throw new IndexOutOfRangeException("The requested child could not be found.");
var child = results[index];
return new FlowComponentBuilder<T>(child);
}
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the last child of the current builder.
/// </summary>
/// <returns>A child FlowComponentBuilder of this FlowComponentBuilder.</returns>
public IFlowComponentBuilder<T> ForLastChild()
{
if (_component.Children == null || _component.Children.Count == 0)
throw new IndexOutOfRangeException("This item has no children.");
FlowComponent<T> child = _component.Children.Last();
return new FlowComponentBuilder<T>(child);
}
/// <summary>
/// Returns an instance of FlowComponentBuilder representing the requested parent.
/// </summary>
/// <returns>A parent FlowComponentBuilder of this FlowComponentBuilder.</returns>
public IFlowComponentBuilder<T> ForParent()
{
FlowComponent<T> parent = _component.Parent;
if (parent == null)
throw new InvalidOperationException("This item has no parent.");
return new FlowComponentBuilder<T>(parent);
}
}
}
| |
namespace XenAdmin.TabPages
{
partial class VMStoragePage
{
/// <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)
{
UnregisterHandlers();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VMStoragePage));
this.AddButton = new XenAdmin.Commands.CommandButton();
this.EditButton = new System.Windows.Forms.Button();
this.AttachButton = new XenAdmin.Commands.CommandButton();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.DeactivateButtonContainer = new XenAdmin.Controls.ToolTipContainer();
this.DeactivateButton = new XenAdmin.Commands.CommandButton();
this.MoveButtonContainer = new XenAdmin.Controls.ToolTipContainer();
this.MoveButton = new XenAdmin.Commands.CommandButton();
this.DetachButtonContainer = new XenAdmin.Controls.ToolTipContainer();
this.DetachButton = new XenAdmin.Commands.CommandButton();
this.DeleteButtonContainer = new XenAdmin.Controls.ToolTipContainer();
this.DeleteButton = new XenAdmin.Commands.CommandButton();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripMenuItemAdd = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemAttach = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemDeactivate = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemMove = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemDelete = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemDetach = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItemProperties = new System.Windows.Forms.ToolStripMenuItem();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.dataGridViewStorage = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.ColumnDevicePosition = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSR = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSRVolume = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnReadOnly = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnPriority = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnActive = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDevicePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList();
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.pageContainerPanel.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.DeactivateButtonContainer.SuspendLayout();
this.MoveButtonContainer.SuspendLayout();
this.DetachButtonContainer.SuspendLayout();
this.DeleteButtonContainer.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).BeginInit();
this.SuspendLayout();
//
// pageContainerPanel
//
this.pageContainerPanel.Controls.Add(this.tableLayoutPanel1);
resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel");
//
// AddButton
//
resources.ApplyResources(this.AddButton, "AddButton");
this.AddButton.Name = "AddButton";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// EditButton
//
resources.ApplyResources(this.EditButton, "EditButton");
this.EditButton.Name = "EditButton";
this.EditButton.UseVisualStyleBackColor = true;
this.EditButton.Click += new System.EventHandler(this.EditButton_Click);
//
// AttachButton
//
resources.ApplyResources(this.AttachButton, "AttachButton");
this.AttachButton.Name = "AttachButton";
this.AttachButton.UseVisualStyleBackColor = true;
this.AttachButton.Click += new System.EventHandler(this.AttachButton_Click);
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.AddButton);
this.flowLayoutPanel1.Controls.Add(this.AttachButton);
this.flowLayoutPanel1.Controls.Add(this.DeactivateButtonContainer);
this.flowLayoutPanel1.Controls.Add(this.MoveButtonContainer);
this.flowLayoutPanel1.Controls.Add(this.DetachButtonContainer);
this.flowLayoutPanel1.Controls.Add(this.DeleteButtonContainer);
this.flowLayoutPanel1.Controls.Add(this.EditButton);
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// DeactivateButtonContainer
//
this.DeactivateButtonContainer.Controls.Add(this.DeactivateButton);
resources.ApplyResources(this.DeactivateButtonContainer, "DeactivateButtonContainer");
this.DeactivateButtonContainer.Name = "DeactivateButtonContainer";
//
// DeactivateButton
//
resources.ApplyResources(this.DeactivateButton, "DeactivateButton");
this.DeactivateButton.Name = "DeactivateButton";
this.DeactivateButton.UseVisualStyleBackColor = true;
//
// MoveButtonContainer
//
this.MoveButtonContainer.Controls.Add(this.MoveButton);
resources.ApplyResources(this.MoveButtonContainer, "MoveButtonContainer");
this.MoveButtonContainer.Name = "MoveButtonContainer";
//
// MoveButton
//
resources.ApplyResources(this.MoveButton, "MoveButton");
this.MoveButton.Name = "MoveButton";
this.MoveButton.UseVisualStyleBackColor = true;
//
// DetachButtonContainer
//
this.DetachButtonContainer.Controls.Add(this.DetachButton);
resources.ApplyResources(this.DetachButtonContainer, "DetachButtonContainer");
this.DetachButtonContainer.Name = "DetachButtonContainer";
//
// DetachButton
//
resources.ApplyResources(this.DetachButton, "DetachButton");
this.DetachButton.Name = "DetachButton";
this.DetachButton.UseVisualStyleBackColor = true;
//
// DeleteButtonContainer
//
this.DeleteButtonContainer.Controls.Add(this.DeleteButton);
resources.ApplyResources(this.DeleteButtonContainer, "DeleteButtonContainer");
this.DeleteButtonContainer.Name = "DeleteButtonContainer";
//
// DeleteButton
//
resources.ApplyResources(this.DeleteButton, "DeleteButton");
this.DeleteButton.Name = "DeleteButton";
this.DeleteButton.UseVisualStyleBackColor = true;
//
// contextMenuStrip1
//
this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemAdd,
this.toolStripMenuItemAttach,
this.toolStripMenuItemDeactivate,
this.toolStripMenuItemMove,
this.toolStripMenuItemDetach,
this.toolStripMenuItemDelete,
this.toolStripSeparator1,
this.toolStripMenuItemProperties});
this.contextMenuStrip1.Name = "contextMenuStrip1";
resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1");
this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening);
//
// toolStripMenuItemAdd
//
this.toolStripMenuItemAdd.Name = "toolStripMenuItemAdd";
resources.ApplyResources(this.toolStripMenuItemAdd, "toolStripMenuItemAdd");
this.toolStripMenuItemAdd.Click += new System.EventHandler(this.toolStripMenuItemAdd_Click);
//
// toolStripMenuItemAttach
//
this.toolStripMenuItemAttach.Name = "toolStripMenuItemAttach";
resources.ApplyResources(this.toolStripMenuItemAttach, "toolStripMenuItemAttach");
this.toolStripMenuItemAttach.Click += new System.EventHandler(this.toolStripMenuItemAttach_Click);
//
// toolStripMenuItemDeactivate
//
this.toolStripMenuItemDeactivate.Name = "toolStripMenuItemDeactivate";
resources.ApplyResources(this.toolStripMenuItemDeactivate, "toolStripMenuItemDeactivate");
this.toolStripMenuItemDeactivate.Click += new System.EventHandler(this.toolStripMenuItemDeactivate_Click);
//
// toolStripMenuItemMove
//
this.toolStripMenuItemMove.Name = "toolStripMenuItemMove";
resources.ApplyResources(this.toolStripMenuItemMove, "toolStripMenuItemMove");
this.toolStripMenuItemMove.Click += new System.EventHandler(this.toolStripMenuItemMove_Click);
//
// toolStripMenuItemDelete
//
this.toolStripMenuItemDelete.Name = "toolStripMenuItemDelete";
resources.ApplyResources(this.toolStripMenuItemDelete, "toolStripMenuItemDelete");
this.toolStripMenuItemDelete.Click += new System.EventHandler(this.toolStripMenuItemDelete_Click);
//
// toolStripMenuItemDetach
//
this.toolStripMenuItemDetach.Name = "toolStripMenuItemDetach";
resources.ApplyResources(this.toolStripMenuItemDetach, "toolStripMenuItemDetach");
this.toolStripMenuItemDetach.Click += new System.EventHandler(this.toolStripMenuItemDetach_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// toolStripMenuItemProperties
//
this.toolStripMenuItemProperties.Image = global::XenAdmin.Properties.Resources.edit_16;
resources.ApplyResources(this.toolStripMenuItemProperties, "toolStripMenuItemProperties");
this.toolStripMenuItemProperties.Name = "toolStripMenuItemProperties";
this.toolStripMenuItemProperties.Click += new System.EventHandler(this.toolStripMenuItemProperties_Click);
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.dataGridViewStorage, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.multipleDvdIsoList1, 0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// dataGridViewStorage
//
this.dataGridViewStorage.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridViewStorage.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridViewStorage.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridViewStorage.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnDevicePosition,
this.ColumnName,
this.ColumnDesc,
this.ColumnSR,
this.ColumnSRVolume,
this.ColumnSize,
this.ColumnReadOnly,
this.ColumnPriority,
this.ColumnActive,
this.ColumnDevicePath});
resources.ApplyResources(this.dataGridViewStorage, "dataGridViewStorage");
this.dataGridViewStorage.MultiSelect = true;
this.dataGridViewStorage.Name = "dataGridViewStorage";
this.dataGridViewStorage.ReadOnly = true;
this.dataGridViewStorage.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewStorage_CellMouseDoubleClick);
this.dataGridViewStorage.SelectionChanged += new System.EventHandler(this.dataGridViewStorage_SelectedIndexChanged);
this.dataGridViewStorage.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.dataGridViewStorage_SortCompare);
this.dataGridViewStorage.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridViewStorage_KeyUp);
this.dataGridViewStorage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dataGridViewStorage_MouseUp);
//
// ColumnDevicePosition
//
this.ColumnDevicePosition.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnDevicePosition, "ColumnDevicePosition");
this.ColumnDevicePosition.Name = "ColumnDevicePosition";
this.ColumnDevicePosition.ReadOnly = true;
//
// ColumnName
//
this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
resources.ApplyResources(this.ColumnName, "ColumnName");
this.ColumnName.Name = "ColumnName";
this.ColumnName.ReadOnly = true;
//
// ColumnDesc
//
this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.ColumnDesc, "ColumnDesc");
this.ColumnDesc.Name = "ColumnDesc";
this.ColumnDesc.ReadOnly = true;
//
// ColumnSR
//
this.ColumnSR.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
resources.ApplyResources(this.ColumnSR, "ColumnSR");
this.ColumnSR.Name = "ColumnSR";
this.ColumnSR.ReadOnly = true;
//
// ColumnSRVolume
//
this.ColumnSRVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
resources.ApplyResources(this.ColumnSRVolume, "ColumnSRVolume");
this.ColumnSRVolume.Name = "ColumnSRVolume";
this.ColumnSRVolume.ReadOnly = true;
//
// ColumnSize
//
this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnSize, "ColumnSize");
this.ColumnSize.Name = "ColumnSize";
this.ColumnSize.ReadOnly = true;
//
// ColumnReadOnly
//
this.ColumnReadOnly.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnReadOnly, "ColumnReadOnly");
this.ColumnReadOnly.Name = "ColumnReadOnly";
this.ColumnReadOnly.ReadOnly = true;
//
// ColumnPriority
//
this.ColumnPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnPriority, "ColumnPriority");
this.ColumnPriority.Name = "ColumnPriority";
this.ColumnPriority.ReadOnly = true;
//
// ColumnActive
//
this.ColumnActive.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnActive, "ColumnActive");
this.ColumnActive.Name = "ColumnActive";
this.ColumnActive.ReadOnly = true;
//
// ColumnDevicePath
//
this.ColumnDevicePath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnDevicePath, "ColumnDevicePath");
this.ColumnDevicePath.Name = "ColumnDevicePath";
this.ColumnDevicePath.ReadOnly = true;
//
// multipleDvdIsoList1
//
resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1");
this.multipleDvdIsoList1.LabelNewCdForeColor = System.Drawing.SystemColors.HotTrack;
this.multipleDvdIsoList1.LabelSingleDvdForeColor = System.Drawing.SystemColors.ControlText;
this.multipleDvdIsoList1.LinkLabelLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255)))));
this.multipleDvdIsoList1.Name = "multipleDvdIsoList1";
//
// dataGridViewTextBoxColumn1
//
this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1");
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
this.dataGridViewTextBoxColumn1.ReadOnly = true;
//
// dataGridViewTextBoxColumn2
//
this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2");
this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
this.dataGridViewTextBoxColumn2.ReadOnly = true;
//
// dataGridViewTextBoxColumn3
//
this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3");
this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
this.dataGridViewTextBoxColumn3.ReadOnly = true;
//
// dataGridViewTextBoxColumn4
//
this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4");
this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
this.dataGridViewTextBoxColumn4.ReadOnly = true;
//
// dataGridViewTextBoxColumn5
//
this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5");
this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
this.dataGridViewTextBoxColumn5.ReadOnly = true;
//
// dataGridViewTextBoxColumn6
//
this.dataGridViewTextBoxColumn6.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn6, "dataGridViewTextBoxColumn6");
this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6";
this.dataGridViewTextBoxColumn6.ReadOnly = true;
//
// dataGridViewTextBoxColumn7
//
this.dataGridViewTextBoxColumn7.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn7, "dataGridViewTextBoxColumn7");
this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7";
this.dataGridViewTextBoxColumn7.ReadOnly = true;
//
// dataGridViewTextBoxColumn8
//
this.dataGridViewTextBoxColumn8.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.dataGridViewTextBoxColumn8, "dataGridViewTextBoxColumn8");
this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8";
this.dataGridViewTextBoxColumn8.ReadOnly = true;
//
// dataGridViewTextBoxColumn9
//
this.dataGridViewTextBoxColumn9.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn9, "dataGridViewTextBoxColumn9");
this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9";
this.dataGridViewTextBoxColumn9.ReadOnly = true;
//
// dataGridViewTextBoxColumn10
//
this.dataGridViewTextBoxColumn10.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn10, "dataGridViewTextBoxColumn10");
this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10";
this.dataGridViewTextBoxColumn10.ReadOnly = true;
//
// VMStoragePage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.Transparent;
this.DoubleBuffered = true;
this.Name = "VMStoragePage";
this.Controls.SetChildIndex(this.pageContainerPanel, 0);
this.pageContainerPanel.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.DeactivateButtonContainer.ResumeLayout(false);
this.MoveButtonContainer.ResumeLayout(false);
this.DetachButtonContainer.ResumeLayout(false);
this.DeleteButtonContainer.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private XenAdmin.Commands.CommandButton AttachButton;
private XenAdmin.Commands.CommandButton AddButton;
private System.Windows.Forms.Button EditButton;
private XenAdmin.Commands.CommandButton DetachButton;
private XenAdmin.Commands.CommandButton DeleteButton;
private XenAdmin.Controls.ToolTipContainer DetachButtonContainer;
private XenAdmin.Controls.ToolTipContainer DeleteButtonContainer;
private XenAdmin.Controls.ToolTipContainer DeactivateButtonContainer;
private XenAdmin.Commands.CommandButton DeactivateButton;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1;
private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewStorage;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10;
private XenAdmin.Controls.ToolTipContainer MoveButtonContainer;
private XenAdmin.Commands.CommandButton MoveButton;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAdd;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAttach;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDeactivate;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemMove;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemProperties;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDelete;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDetach;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePosition;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSR;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSRVolume;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnReadOnly;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPriority;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnActive;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePath;
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Composite.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.AI.BehaviorTrees.Implementations.Composites
{
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Slash.AI.BehaviorTrees.Editor;
using Slash.AI.BehaviorTrees.Enums;
using Slash.AI.BehaviorTrees.Interfaces;
using Slash.AI.BehaviorTrees.Tree;
using Slash.Collections.Extensions;
using Slash.Collections.Utils;
/// <summary>
/// Task which contains array of references to other tasks.
/// </summary>
/// <typeparam name="TTaskData"> Task data. </typeparam>
[Serializable]
public abstract class Composite<TTaskData> : BaseTask<TTaskData>, IComposite
where TTaskData : ITaskData, new()
{
#region Fields
/// <summary>
/// Children of this group task.
/// </summary>
private List<ITask> children;
#endregion
#region Constructors and Destructors
/// <summary>
/// Constructor.
/// </summary>
protected Composite()
{
this.children = new List<ITask>();
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="deciders"> Child deciders. </param>
protected Composite(List<ITask> deciders)
{
this.children = deciders;
}
#endregion
#region Events
/// <summary>
/// Called when a child was added to the composite.
/// </summary>
public event CompositeChildAddedDelegate ChildAdded;
/// <summary>
/// Called when a child was removed from the composite.
/// </summary>
public event CompositeChildRemovedDelegate ChildRemoved;
#endregion
#region Properties
/// <summary>
/// Maximum number of children that the composite can take.
/// </summary>
[XmlIgnore]
public int Capacity
{
get
{
return int.MaxValue;
}
}
/// <summary>
/// Children of this group task. Read-only.
/// </summary>
[XmlIgnore]
public IList<ITask> Children
{
get
{
return this.children.AsReadOnly();
}
}
/// <summary>
/// Xml Serialization for decorated children.
/// </summary>
[XmlElement("Children")]
public XmlWrapperList ChildrenSerialized
{
get
{
return new XmlWrapperList(this.children);
}
set
{
this.children = value.List;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Adds a child to this group task.
/// </summary>
/// <param name="child"> Child to add. </param>
public void AddChild(ITask child)
{
this.children.Add(child);
this.InvokeChildAdded(child);
}
/// <summary>
/// Determines whether the specified <see cref="T:Composite" /> is equal to the current
/// <see cref="T:Composite" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:Composite" /> is equal to the current <see cref="T:Composite" />;
/// otherwise, false.
/// </returns>
/// <param name="other">The <see cref="T:Composite" /> to compare with the current <see cref="T:Composite" />. </param>
public bool Equals(Composite<TTaskData> other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return CollectionUtils.SequenceEqual(this.children, other.children);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to the current
/// <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />;
/// otherwise, false.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />. </param>
/// <filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (!obj.GetType().IsSubclassOf(typeof(Composite<TTaskData>)))
{
return false;
}
return this.Equals((Composite<TTaskData>)obj);
}
/// <summary>
/// Searches for tasks which forfill the passed predicate.
/// </summary>
/// <param name="taskNode"> Task node of this task. </param>
/// <param name="predicate"> Predicate to forfill. </param>
/// <param name="tasks"> List of tasks which forfill the passed predicate. </param>
public override void FindTasks(TaskNode taskNode, Func<ITask, bool> predicate, ref ICollection<TaskNode> tasks)
{
// Check children.
for (int index = 0; index < this.children.Count; index++)
{
ITask child = this.children[index];
TaskNode childTaskNode = taskNode.CreateChildNode(child, index);
if (predicate(child))
{
tasks.Add(childTaskNode);
}
// Find tasks in child.
child.FindTasks(childTaskNode, predicate, ref tasks);
}
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object" />.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
return this.children != null ? this.children.GetHashCode() : 0;
}
/// <summary>
/// Inserts a child to this group task at the passed index.
/// </summary>
/// <param name="index"> Position to add child to. </param>
/// <param name="child"> Child to insert. </param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if passed index isn't between 0 and Children.Count (inclusive).</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if passed index isn't between 0 and Capacity (exclusive).</exception>
public void InsertChild(int index, ITask child)
{
this.children.Insert(index, child);
this.InvokeChildAdded(child);
}
/// <summary>
/// Moves a child to the passed position inside the group.
/// </summary>
/// <param name="oldIndex"> Old position of the child. </param>
/// <param name="newIndex"> New position of the child. </param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if passed old index isn't between 0 and Children.Count
/// (exclusive).
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if passed new index isn't between 0 and Children.Count
/// (exclusive).
/// </exception>
public void MoveChild(int oldIndex, int newIndex)
{
this.children.Move(oldIndex, newIndex);
}
/// <summary>
/// Removes a child from this group task.
/// </summary>
/// <param name="child"> Child to remove. </param>
/// <returns> Indicates if the child was removed. </returns>
public bool RemoveChild(ITask child)
{
if (!this.children.Remove(child))
{
return false;
}
this.InvokeChildRemoved(child);
return true;
}
#endregion
#region Methods
/// <summary>
/// Activates the passed child. Does no index range checking.
/// </summary>
/// <param name="childIdx"> Child index. Has to be in correct range. </param>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data from the decide function. </param>
/// <returns> Execution status after the activation. </returns>
protected ExecutionStatus ActivateChild(int childIdx, IAgentData agentData, IDecisionData decisionData)
{
++agentData.CurrentDeciderLevel;
ExecutionStatus executionStatus = this.children[childIdx].Activate(agentData, decisionData);
--agentData.CurrentDeciderLevel;
return executionStatus;
}
/// <summary>
/// Deactivates the passed child. Does no index range checking.
/// </summary>
/// <param name="childIdx"> Child index. Has to be in correct range. </param>
/// <param name="agentData"> Agent data. </param>
protected void DeactivateChild(int childIdx, IAgentData agentData)
{
++agentData.CurrentDeciderLevel;
this.children[childIdx].Deactivate(agentData);
--agentData.CurrentDeciderLevel;
}
/// <summary>
/// Takes first task which wants to be active. Checks only a subset of the children from index 0 to passed lastChildIdx
/// (exclusive).
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="firstChildIdx"> First child index to check (inclusive). </param>
/// <param name="lastChildIdx"> Last child index to check (exclusive). </param>
/// <param name="childIdx"> Index of child which will be activated. </param>
/// <param name="childDecideValue"> Decide value of child which will be activated. </param>
/// <param name="childDecisionData"> Decision data of child to be used in activate method. </param>
/// <returns> True if there's a child which wants to be activated, else false. </returns>
protected bool DecideForFirstPossible(
IAgentData agentData,
int firstChildIdx,
int lastChildIdx,
ref int childIdx,
ref float childDecideValue,
ref IDecisionData childDecisionData)
{
for (int idx = firstChildIdx; idx < lastChildIdx; idx++)
{
ITask task = this.Children[idx];
float decideValue = task.Decide(agentData, ref childDecisionData);
if (decideValue <= 0.0f)
{
continue;
}
childIdx = idx;
childDecideValue = decideValue;
return true;
}
return false;
}
/// <summary>
/// Computes the relevancy for the decide method by taking the maximum relevancy of all children.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data. </param>
/// <returns> Maximum relevancy of the children. </returns>
protected float DelegateDecideToChildren(IAgentData agentData, ref IDecisionData decisionData)
{
float maxDecisionValue = 0.0f;
foreach (ITask decider in this.children)
{
IDecisionData childDecisionData = null;
float decisionValue = decider.Decide(agentData, ref childDecisionData);
if (decisionValue > maxDecisionValue)
{
maxDecisionValue = decisionValue;
decisionData = childDecisionData;
}
}
return maxDecisionValue;
}
/// <summary>
/// Gets the active tasks of the passed child. Does no index range checking.
/// </summary>
/// <param name="childIdx"> Child index. Has to be in correct range. </param>
/// <param name="agentData"> Agent data. </param>
/// <param name="childTaskNode"> Task node of child. </param>
/// <param name="activeTasks"> Collection of active tasks. </param>
protected void GetActiveChildTasks(
int childIdx,
IAgentData agentData,
TaskNode childTaskNode,
ref ICollection<TaskNode> activeTasks)
{
++agentData.CurrentDeciderLevel;
this.children[childIdx].GetActiveTasks(agentData, childTaskNode, ref activeTasks);
--agentData.CurrentDeciderLevel;
}
/*
/// <summary>
/// Called when the configuration should be read from xml. Can be overridden in derived classes to read
/// additional attributes from xml.
/// </summary>
/// <param name = "reader">Xml reader.</param>
protected override void OnReadXml(XmlReader reader)
{
int numChildren = Convert.ToInt32(reader.GetValue("Count"));
reader.ReadStartElement("Children");
for (int idx = 0; idx < numChildren; ++idx)
{
// Read child.
ITask task;
BehaviorTreeHelpers.ReadXml(reader, out task, "Child");
this.children.Add(task);
}
reader.ReadEndElement();
}
/// <summary>
/// Called when the configuration should be write to xml. Can be overridden in derived classes to write
/// additional attributes to xml.
/// </summary>
/// <param name = "writer">Xml writer.</param>
protected override void OnWriteXml(XmlWriter writer)
{
writer.WriteStartElement("Children");
writer.WriteAttributeString("Count", this.children.Count.ToString());
foreach (ITask task in this.children)
{
BehaviorTreeHelpers.WriteXml(writer, task, "Child");
}
writer.WriteEndElement();
}*/
/// <summary>
/// Updates the passed child. Does no index range checking.
/// </summary>
/// <param name="childIdx"> Child index. Has to be in correct range. </param>
/// <param name="agentData"> Agent data. </param>
/// <returns> New execution status. </returns>
protected ExecutionStatus UpdateChild(int childIdx, IAgentData agentData)
{
++agentData.CurrentDeciderLevel;
ExecutionStatus executionStatus = this.children[childIdx].Update(agentData);
--agentData.CurrentDeciderLevel;
return executionStatus;
}
private void InvokeChildAdded(ITask childTask)
{
CompositeChildAddedDelegate handler = this.ChildAdded;
if (handler != null)
{
handler(this, childTask);
}
}
private void InvokeChildRemoved(ITask childTask)
{
CompositeChildRemovedDelegate handler = this.ChildRemoved;
if (handler != null)
{
handler(this, childTask);
}
}
#endregion
}
}
| |
// Copyright (c) 2016-2018 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Xml;
using SIL.LCModel;
using SIL.LCModel.Core.KernelInterfaces;
namespace LfMerge.Core.DataConverters.CanonicalSources
{
public abstract class CanonicalItem
{
public const string ORC = "\ufffc";
public const char ORCchar = '\ufffc';
public const string KeyWs = "en";
// Might come from an XML source like GOLDEtic.xml, or SemDom.xml
// MUST have names and abbreviations
// MAY have description, potentially other data (e.g., semdom has questions, example words, LouwNida or OCM codes, etc.)
public string GuidStr { get; protected set; } // Canonical GUID for this item. NOT a Guid struct type, but a string.
public string Key { get; internal set; } // Official abbreviation *IN ENGLISH*. Not to be confused with the abbreviation list.
// Items are in a hiearchical list, and have parents and "children" (sub-items)
public CanonicalItem Parent { get; protected set; }
public List<CanonicalItem> Subitems { get; protected set; }
// The following are keyed by writing system name (a string)
public Dictionary<string, string> Abbrevs { get; protected set; }
public Dictionary<string, string> Names { get; protected set; }
public Dictionary<string, string> Descriptions { get; protected set; }
// Extra data is keyed by field name, like "Questions", "Example Words", or whatever. Values are objects so that derived classes can do what they like with this.
public Dictionary<string, object> ExtraData { get; protected set; }
public string ORCDelimitedKey {
get
{
if (Parent != null)
return Parent.ORCDelimitedKey + ORC + Key;
else
return Key;
}
}
public CanonicalItem()
{
GuidStr = System.Guid.Empty.ToString();
Key = string.Empty;
Parent = null;
Subitems = new List<CanonicalItem>();
Abbrevs = new Dictionary<string, string>();
Names = new Dictionary<string, string>();
Descriptions = new Dictionary<string, string>();
ExtraData = new Dictionary<string, object>();
}
/// <summary>
/// Given an XmlReader positioned on this node's XML representation, populate its names, abbrevs, etc. from the XML.
/// After running PopulateFromXml, the reader should be positioned just past this node's closing element.
/// E.g., after parsing item 1 from <item id=1><name>Foo</name></item><!-- next node --> the reader should be positioned
/// on the "next node" comment.
/// </summary>
/// <param name="reader">XmlReader instance, initially positioned on this node's XML representation.</param>
public abstract void PopulateFromXml(XmlReader reader);
/// <summary>
/// Gets an item from a dictionary keyed by strings. If key is not present, creates and returns a new item.
/// Since most derived classes will be storing some sort of lists in ExtraData (of questions, citations, examples, etc.),
/// this will be a very useful helper function: e.g., it could return an empty list.
/// </summary>
/// <returns>The item corresponding to that key, or the newly-created item.</returns>
/// <param name="dict">The dictionary to search.</param>
/// <param name="key">Key of the item to return.</param>
public T GetOrSetDefault<T>(IDictionary<string, object> dict, string key)
where T: class, new()
{
if (dict.ContainsKey(key))
return dict[key] as T;
var result = new T();
dict[key] = result;
return result;
}
/// <summary>
/// Like GetOrSetDefault, but specifically creating an empty list
/// </summary>
/// <returns>The list from dict.</returns>
/// <param name="dict">Dict.</param>
/// <param name="key">Key.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public List<T> GetListFromDict<T>(IDictionary<string, List<T>> dict, string key)
{
if (dict.ContainsKey(key))
return dict[key];
var result = new List<T>();
dict[key] = result;
return result;
}
/// <summary>
/// Gets a list from the extra data dictionary by key. If key is not present, creates and returns an empty list.
/// Since most derived classes will be storing some sort of lists in ExtraData (of questions, citations, examples, etc.),
/// this will be a very useful helper function.
/// </summary>
/// <returns>The list corresponding to that key, or the newly-created empty list.</returns>
/// <param name="key">Key.</param>
/// <param name="defaultIfNotPresent">Default if not present.</param>
public List<T> GetExtraDataList<T>(string key)
{
return GetOrSetDefault<List<T>>(ExtraData, key);
}
/// <summary>
/// Similar to GetExtraDataList, but returns a dictionary keyed by writing system
/// </summary>
/// <returns>The dictionary corresponding to this key, or the newly-created empty dictionary.</returns>
/// <param name="key">Key.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public Dictionary<string, List<T>> GetExtraDataWsDict<T>(string key)
{
return GetOrSetDefault<Dictionary<string, List<T>>>(ExtraData, key);
}
public void AppendChild(CanonicalItem child)
{
Subitems.Add(child);
child.Parent = this;
}
public void AddAbbrev(string ws, string data)
{
Abbrevs.Add(ws, data);
}
public void AddName(string ws, string data)
{
Names.Add(ws, data);
}
public void AddDescription(string ws, string data)
{
Descriptions.Add(ws, data);
}
private string SimplifyWs(string ws)
{
if (ws.StartsWith("zh")) // The only non-2-letter writing system in GOLDEtic.xml is zh-CN
return ws.Substring(0, 5);
else
return ws.Substring(0, 2);
}
public string NameByWs(string ws)
{
string name;
if (Names.TryGetValue(SimplifyWs(ws), out name))
return name;
else
return String.Empty;
}
public string ORCDelimitedNameByWs(string ws)
{
// NOTE: Doesn't handle cases where some ancestors have names for that writing system but others don't.
ws = SimplifyWs(ws);
string ORC = "\ufffc";
if (Parent != null)
return Parent.ORCDelimitedNameByWs(ws) + ORC + NameByWs(ws);
else
return NameByWs(ws);
}
public string AbbrevByWs(string ws)
{
string abbr;
if (Abbrevs.TryGetValue(SimplifyWs(ws), out abbr))
return abbr;
else
return String.Empty;
}
public string ORCDelimitedAbbrevByWs(string ws)
{
// NOTE: Doesn't handle cases where some ancestors have names for that writing system but others don't.
ws = SimplifyWs(ws);
string ORC = "\ufffc";
if (Parent != null)
return Parent.ORCDelimitedAbbrevByWs(ws) + ORC + AbbrevByWs(ws);
else
return AbbrevByWs(ws);
}
public void PopulatePossibility(ICmPossibility poss)
// Creating, assigning parent, etc., is handled elsewhere. This function only sets text values.
{
ILgWritingSystemFactory wsf = poss.Cache.WritingSystemFactory;
foreach (KeyValuePair<string, string> kv in Abbrevs)
{
int wsId = wsf.GetWsFromStr(kv.Key);
if (wsId != 0)
poss.Abbreviation.set_String(wsId, kv.Value);
}
foreach (KeyValuePair<string, string> kv in Descriptions)
{
int wsId = wsf.GetWsFromStr(kv.Key);
if (wsId != 0)
poss.Description.set_String(wsId, kv.Value);
}
foreach (KeyValuePair<string, string> kv in Names)
{
int wsId = wsf.GetWsFromStr(kv.Key);
if (wsId != 0)
poss.Name.set_String(wsId, kv.Value);
}
PopulatePossibilityFromExtraData(poss);
}
protected abstract void PopulatePossibilityFromExtraData(ICmPossibility poss);
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
namespace OpenSim.Framework
{
// ACL Class
// Modelled after the structure of the Zend ACL Framework Library
// with one key difference - the tree will search for all matching
// permissions rather than just the first. Deny permissions will
// override all others.
#region ACL Core Class
/// <summary>
/// Access Control List Engine
/// </summary>
public class ACL
{
private Dictionary<string, Resource> Resources = new Dictionary<string, Resource>();
private Dictionary<string, Role> Roles = new Dictionary<string, Role>();
public ACL AddRole(Role role)
{
if (Roles.ContainsKey(role.Name))
throw new AlreadyContainsRoleException(role);
Roles.Add(role.Name, role);
return this;
}
public ACL AddResource(Resource resource)
{
Resources.Add(resource.Name, resource);
return this;
}
public Permission HasPermission(string role, string resource)
{
if (!Roles.ContainsKey(role))
throw new KeyNotFoundException();
if (!Resources.ContainsKey(resource))
throw new KeyNotFoundException();
return Roles[role].RequestPermission(resource);
}
public ACL GrantPermission(string role, string resource)
{
if (!Roles.ContainsKey(role))
throw new KeyNotFoundException();
if (!Resources.ContainsKey(resource))
throw new KeyNotFoundException();
Roles[role].GivePermission(resource, Permission.Allow);
return this;
}
public ACL DenyPermission(string role, string resource)
{
if (!Roles.ContainsKey(role))
throw new KeyNotFoundException();
if (!Resources.ContainsKey(resource))
throw new KeyNotFoundException();
Roles[role].GivePermission(resource, Permission.Deny);
return this;
}
public ACL ResetPermission(string role, string resource)
{
if (!Roles.ContainsKey(role))
throw new KeyNotFoundException();
if (!Resources.ContainsKey(resource))
throw new KeyNotFoundException();
Roles[role].GivePermission(resource, Permission.None);
return this;
}
}
#endregion
#region Exceptions
/// <summary>
/// Thrown when an ACL attempts to add a duplicate role.
/// </summary>
public class AlreadyContainsRoleException : Exception
{
protected Role m_role;
public AlreadyContainsRoleException(Role role)
{
m_role = role;
}
public Role ErrorRole
{
get { return m_role; }
}
public override string ToString()
{
return "This ACL already contains a role called '" + m_role.Name + "'.";
}
}
#endregion
#region Roles and Resources
/// <summary>
/// Does this Role have permission to access a specified Resource?
/// </summary>
public enum Permission
{
Deny,
None,
Allow
} ;
/// <summary>
/// A role class, for use with Users or Groups
/// </summary>
public class Role
{
private string m_name;
private Role[] m_parents;
private Dictionary<string, Permission> m_resources = new Dictionary<string, Permission>();
public Role(string name)
{
m_name = name;
m_parents = null;
}
public Role(string name, Role[] parents)
{
m_name = name;
m_parents = parents;
}
public string Name
{
get { return m_name; }
}
public Permission RequestPermission(string resource)
{
return RequestPermission(resource, Permission.None);
}
public Permission RequestPermission(string resource, Permission current)
{
// Deny permissions always override any others
if (current == Permission.Deny)
return current;
Permission temp = Permission.None;
// Pickup non-None permissions
if (m_resources.ContainsKey(resource) && m_resources[resource] != Permission.None)
temp = m_resources[resource];
if (m_parents != null)
{
foreach (Role parent in m_parents)
{
temp = parent.RequestPermission(resource, temp);
}
}
return temp;
}
public void GivePermission(string resource, Permission perm)
{
m_resources[resource] = perm;
}
}
public class Resource
{
private string m_name;
public Resource(string name)
{
m_name = name;
}
public string Name
{
get { return m_name; }
}
}
#endregion
#region Tests
internal class ACLTester
{
public ACLTester()
{
ACL acl = new ACL();
Role Guests = new Role("Guests");
acl.AddRole(Guests);
Role[] parents = new Role[0];
parents[0] = Guests;
Role JoeGuest = new Role("JoeGuest", parents);
acl.AddRole(JoeGuest);
Resource CanBuild = new Resource("CanBuild");
acl.AddResource(CanBuild);
acl.GrantPermission("Guests", "CanBuild");
acl.HasPermission("JoeGuest", "CanBuild");
}
}
#endregion
}
| |
// <copyright file="By.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
/// <summary>
/// Provides a mechanism by which to find elements within a document.
/// </summary>
/// <remarks>It is possible to create your own locating mechanisms for finding documents.
/// In order to do this,subclass this class and override the protected methods. However,
/// it is expected that that all subclasses rely on the basic finding mechanisms provided
/// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName
/// </remarks>
[Serializable]
public class By
{
private string description = "OpenQA.Selenium.By";
private Func<ISearchContext, IWebElement> findElementMethod;
private Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod;
/// <summary>
/// Initializes a new instance of the <see cref="By"/> class.
/// </summary>
protected By()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="By"/> class using the given functions to find elements.
/// </summary>
/// <param name="findElementMethod">A function that takes an object implementing <see cref="ISearchContext"/>
/// and returns the found <see cref="IWebElement"/>.</param>
/// <param name="findElementsMethod">A function that takes an object implementing <see cref="ISearchContext"/>
/// and returns a <see cref="ReadOnlyCollection{T}"/> of the found<see cref="IWebElement">IWebElements</see>.
/// <see cref="IWebElement">IWebElements</see>/>.</param>
protected By(Func<ISearchContext, IWebElement> findElementMethod, Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod)
{
this.findElementMethod = findElementMethod;
this.findElementsMethod = findElementsMethod;
}
/// <summary>
/// Gets or sets the value of the description for this <see cref="By"/> class instance.
/// </summary>
protected string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Gets or sets the method used to find a single element matching specified criteria.
/// </summary>
protected Func<ISearchContext, IWebElement> FindElementMethod
{
get { return this.findElementMethod; }
set { this.findElementMethod = value; }
}
/// <summary>
/// Gets or sets the method used to find all elements matching specified criteria.
/// </summary>
protected Func<ISearchContext, ReadOnlyCollection<IWebElement>> FindElementsMethod
{
get { return this.findElementsMethod; }
set { this.findElementsMethod = value; }
}
/// <summary>
/// Determines if two <see cref="By"/> instances are equal.
/// </summary>
/// <param name="one">One instance to compare.</param>
/// <param name="two">The other instance to compare.</param>
/// <returns><see langword="true"/> if the two instances are equal; otherwise, <see langword="false"/>.</returns>
public static bool operator ==(By one, By two)
{
// If both are null, or both are same instance, return true.
if (object.ReferenceEquals(one, two))
{
return true;
}
// If one is null, but not both, return false.
if (((object)one == null) || ((object)two == null))
{
return false;
}
return one.Equals(two);
}
/// <summary>
/// Determines if two <see cref="By"/> instances are unequal.
/// </summary>s
/// <param name="one">One instance to compare.</param>
/// <param name="two">The other instance to compare.</param>
/// <returns><see langword="true"/> if the two instances are not equal; otherwise, <see langword="false"/>.</returns>
public static bool operator !=(By one, By two)
{
return !(one == two);
}
/// <summary>
/// Gets a mechanism to find elements by their ID.
/// </summary>
/// <param name="idToFind">The ID to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Id(string idToFind)
{
if (idToFind == null)
{
throw new ArgumentNullException("idToFind", "Cannot find elements with a null id attribute.");
}
By by = new By();
by.findElementMethod = (ISearchContext context) => ((IFindsById)context).FindElementById(idToFind);
by.findElementsMethod = (ISearchContext context) => ((IFindsById)context).FindElementsById(idToFind);
by.description = "By.Id: " + idToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their link text.
/// </summary>
/// <param name="linkTextToFind">The link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By LinkText(string linkTextToFind)
{
if (linkTextToFind == null)
{
throw new ArgumentNullException("linkTextToFind", "Cannot find elements when link text is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByLinkText)context).FindElementByLinkText(linkTextToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByLinkText)context).FindElementsByLinkText(linkTextToFind);
by.description = "By.LinkText: " + linkTextToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their name.
/// </summary>
/// <param name="nameToFind">The name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Name(string nameToFind)
{
if (nameToFind == null)
{
throw new ArgumentNullException("nameToFind", "Cannot find elements when name text is null.");
}
By by = new By();
by.findElementMethod = (ISearchContext context) => ((IFindsByName)context).FindElementByName(nameToFind);
by.findElementsMethod = (ISearchContext context) => ((IFindsByName)context).FindElementsByName(nameToFind);
by.description = "By.Name: " + nameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by an XPath query.
/// When searching within a WebElement using xpath be aware that WebDriver follows standard conventions:
/// a search prefixed with "//" will search the entire document, not just the children of this current node.
/// Use ".//" to limit your search to the children of this WebElement.
/// </summary>
/// <param name="xpathToFind">The XPath query to use.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By XPath(string xpathToFind)
{
if (xpathToFind == null)
{
throw new ArgumentNullException("xpathToFind", "Cannot find elements when the XPath expression is null.");
}
By by = new By();
by.findElementMethod = (ISearchContext context) => ((IFindsByXPath)context).FindElementByXPath(xpathToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByXPath)context).FindElementsByXPath(xpathToFind);
by.description = "By.XPath: " + xpathToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their CSS class.
/// </summary>
/// <param name="classNameToFind">The CSS class to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
/// <remarks>If an element has many classes then this will match against each of them.
/// For example if the value is "one two onone", then the following values for the
/// className parameter will match: "one" and "two".</remarks>
public static By ClassName(string classNameToFind)
{
if (classNameToFind == null)
{
throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByClassName)context).FindElementByClassName(classNameToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByClassName)context).FindElementsByClassName(classNameToFind);
by.description = "By.ClassName[Contains]: " + classNameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by a partial match on their link text.
/// </summary>
/// <param name="partialLinkTextToFind">The partial link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By PartialLinkText(string partialLinkTextToFind)
{
By by = new By();
by.findElementMethod =
(ISearchContext context) =>
((IFindsByPartialLinkText)context).FindElementByPartialLinkText(partialLinkTextToFind);
by.findElementsMethod =
(ISearchContext context) =>
((IFindsByPartialLinkText)context).FindElementsByPartialLinkText(partialLinkTextToFind);
by.description = "By.PartialLinkText: " + partialLinkTextToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their tag name.
/// </summary>
/// <param name="tagNameToFind">The tag name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By TagName(string tagNameToFind)
{
if (tagNameToFind == null)
{
throw new ArgumentNullException("tagNameToFind", "Cannot find elements when name tag name is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByTagName)context).FindElementByTagName(tagNameToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByTagName)context).FindElementsByTagName(tagNameToFind);
by.description = "By.TagName: " + tagNameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their cascading style sheet (CSS) selector.
/// </summary>
/// <param name="cssSelectorToFind">The CSS selector to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By CssSelector(string cssSelectorToFind)
{
if (cssSelectorToFind == null)
{
throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByCssSelector)context).FindElementByCssSelector(cssSelectorToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByCssSelector)context).FindElementsByCssSelector(cssSelectorToFind);
by.description = "By.CssSelector: " + cssSelectorToFind;
return by;
}
/// <summary>
/// Finds the first element matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
public virtual IWebElement FindElement(ISearchContext context)
{
return this.findElementMethod(context);
}
/// <summary>
/// Finds all elements matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
return this.findElementsMethod(context);
}
/// <summary>
/// Gets a string representation of the finder.
/// </summary>
/// <returns>The string displaying the finder content.</returns>
public override string ToString()
{
return this.description;
}
/// <summary>
/// Determines whether the specified <see cref="object">Object</see> is equal
/// to the current <see cref="object">Object</see>.
/// </summary>
/// <param name="obj">The <see cref="object">Object</see> to compare with the
/// current <see cref="object">Object</see>.</param>
/// <returns><see langword="true"/> if the specified <see cref="object">Object</see>
/// is equal to the current <see cref="object">Object</see>; otherwise,
/// <see langword="false"/>.</returns>
public override bool Equals(object obj)
{
var other = obj as By;
// TODO(dawagner): This isn't ideal
return other != null && this.description.Equals(other.description);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current <see cref="object">Object</see>.</returns>
public override int GetHashCode()
{
return this.description.GetHashCode();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithLowerAndUpperSingle()
{
var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSingle();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSingle
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector256<Single> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
Vector128<Single> lowerResult = value.GetLower();
Vector128<Single> upperResult = value.GetUpper();
ValidateGetResult(lowerResult, upperResult, values);
Vector256<Single> result = value.WithLower(upperResult);
result = result.WithUpper(lowerResult);
ValidateWithResult(result, values);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector256<Single> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
object lowerResult = typeof(Vector256)
.GetMethod(nameof(Vector256.GetLower))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value });
object upperResult = typeof(Vector256)
.GetMethod(nameof(Vector256.GetUpper))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value });
ValidateGetResult((Vector128<Single>)(lowerResult), (Vector128<Single>)(upperResult), values);
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.WithLower))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, upperResult });
result = typeof(Vector256)
.GetMethod(nameof(Vector256.WithUpper))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { result, lowerResult });
ValidateWithResult((Vector256<Single>)(result), values);
}
private void ValidateGetResult(Vector128<Single> lowerResult, Vector128<Single> upperResult, Single[] values, [CallerMemberName] string method = "")
{
Single[] lowerElements = new Single[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref lowerElements[0]), lowerResult);
Single[] upperElements = new Single[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref upperElements[0]), upperResult);
ValidateGetResult(lowerElements, upperElements, values, method);
}
private void ValidateGetResult(Single[] lowerResult, Single[] upperResult, Single[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (lowerResult[i] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single>.GetLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (upperResult[i - (ElementCount / 2)] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single>.GetUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
private void ValidateWithResult(Vector256<Single> result, Single[] values, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, method);
}
private void ValidateWithResult(Single[] result, Single[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (result[i] != values[i + (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.WithLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (result[i] != values[i - (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.WithUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System.Text;
using TouchScript.Pointers;
using TouchScript.Utils;
using UnityEngine;
using UnityEngine.UI;
namespace TouchScript.Behaviors.Cursors
{
/// <summary>
/// Abstract class for pointer cursors with text.
/// </summary>
/// <typeparam name="T">Pointer type.</typeparam>
/// <seealso cref="TouchScript.Behaviors.Cursors.PointerCursor" />
public abstract class TextPointerCursor<T> : PointerCursor where T : IPointer
{
#region Public properties
/// <summary>
/// Should the value of <see cref="Pointer.Id"/> be shown on screen on the cursor.
/// </summary>
public bool ShowPointerId = true;
/// <summary>
/// Should the value of <see cref="Pointer.Flags"/> be shown on screen on the cursor.
/// </summary>
public bool ShowFlags = false;
/// <summary>
/// The link to UI.Text component.
/// </summary>
public Text Text;
#endregion
#region Private variables
private static StringBuilder stringBuilder = new StringBuilder(64);
#endregion
#region Protected methods
/// <inheritdoc />
protected override void updateOnce(IPointer pointer)
{
base.updateOnce(pointer);
if (Text == null) return;
if (!textIsVisible())
{
Text.enabled = false;
return;
}
Text.enabled = true;
stringBuilder.Length = 0;
generateText((T) pointer, stringBuilder);
Text.text = stringBuilder.ToString();
}
/// <summary>
/// Generates text for pointer.
/// </summary>
/// <param name="pointer">The pointer.</param>
/// <param name="str">The string builder to use.</param>
protected virtual void generateText(T pointer, StringBuilder str)
{
if (ShowPointerId)
{
str.Append("Id: ");
str.Append(pointer.Id);
}
if (ShowFlags)
{
if (str.Length > 0) str.Append("\n");
str.Append("Flags: ");
BinaryUtils.ToBinaryString(pointer.Flags, str, 8);
}
}
/// <summary>
/// Indicates if text should be visible.
/// </summary>
/// <returns><c>True</c> if pointer text should be displayed; <c>false</c> otherwise.</returns>
protected virtual bool textIsVisible()
{
return ShowPointerId || ShowFlags;
}
/// <summary>
/// Typed version of <see cref="getPointerHash"/>. Returns a hash of a cursor state.
/// </summary>
/// <param name="pointer">The pointer.</param>
/// <returns>Integer hash.</returns>
protected virtual uint gethash(T pointer)
{
var hash = (uint) state;
if (ShowFlags) hash += pointer.Flags << 3;
return hash;
}
/// <inheritdoc />
protected sealed override uint getPointerHash(IPointer pointer)
{
return gethash((T) pointer);
}
#endregion
}
/// <summary>
/// Visual cursor implementation used by TouchScript.
/// </summary>
[HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Behaviors_Cursors_PointerCursor.htm")]
public class PointerCursor : MonoBehaviour
{
#region Consts
/// <summary>
/// Possible states of a cursor.
/// </summary>
public enum CursorState
{
/// <summary>
/// Not pressed.
/// </summary>
Released,
/// <summary>
/// Pressed.
/// </summary>
Pressed,
/// <summary>
/// Over something.
/// </summary>
Over,
/// <summary>
/// Over and pressed.
/// </summary>
OverPressed
}
#endregion
#region Public properties
/// <summary>
/// Cursor size in pixels.
/// </summary>
public float Size
{
get { return size; }
set
{
size = value;
if (size > 0)
{
rect.sizeDelta = Vector2.one * size;
}
else
{
size = 0;
rect.sizeDelta = Vector2.one * defaultSize;
}
}
}
#endregion
#region Private variables
/// <summary>
/// Current cursor state.
/// </summary>
protected CursorState state;
/// <summary>
/// CUrrent cursor state data.
/// </summary>
protected object stateData;
/// <summary>
/// Cached RectTransform.
/// </summary>
protected RectTransform rect;
/// <summary>
/// Cached Canvas.
/// </summary>
protected Canvas canvas;
/// <summary>
/// Cursor size.
/// </summary>
protected float size = 0;
/// <summary>
/// Initial cursor size in pixels.
/// </summary>
protected float defaultSize;
/// <summary>
/// Last data hash.
/// </summary>
protected uint hash = uint.MaxValue;
#endregion
#region Public methods
/// <summary>
/// Initializes (resets) the cursor.
/// </summary>
/// <param name="parent"> Parent container. </param>
/// <param name="pointer"> Pointer this cursor represents. </param>
public void Init(RectTransform parent, IPointer pointer)
{
hash = uint.MaxValue;
show();
rect.SetParent(parent);
rect.SetAsLastSibling();
state = CursorState.Released;
UpdatePointer(pointer);
}
/// <summary>
/// Updates the pointer. This method is called when the pointer is moved.
/// </summary>
/// <param name="pointer"> Pointer this cursor represents. </param>
public void UpdatePointer(IPointer pointer)
{
rect.anchoredPosition = pointer.Position;
var newHash = getPointerHash(pointer);
if (newHash != hash) updateOnce(pointer);
hash = newHash;
update(pointer);
}
/// <summary>
/// Sets the state of the cursor.
/// </summary>
/// <param name="pointer">The pointer.</param>
/// <param name="newState">The new state.</param>
/// <param name="data">State data.</param>
public void SetState(IPointer pointer, CursorState newState, object data = null)
{
state = newState;
stateData = data;
var newHash = getPointerHash(pointer);
if (newHash != hash) updateOnce(pointer);
hash = newHash;
}
/// <summary>
/// Hides this instance.
/// </summary>
public void Hide()
{
hide();
}
#endregion
#region Unity methods
private void Awake()
{
rect = transform as RectTransform;
if (rect == null)
{
Debug.LogError("PointerCursor must be on an UI element!");
enabled = false;
return;
}
canvas = GetComponent<Canvas>();
rect.anchorMin = rect.anchorMax = Vector2.zero;
defaultSize = rect.sizeDelta.x;
}
#endregion
#region Protected methods
/// <summary>
/// Hides (clears) this instance.
/// </summary>
protected virtual void hide()
{
canvas.enabled = false;
}
/// <summary>
/// Shows this instance.
/// </summary>
protected virtual void show()
{
canvas.enabled = true;
}
/// <summary>
/// This method is called once when the cursor is initialized.
/// </summary>
/// <param name="pointer"> The pointer. </param>
protected virtual void updateOnce(IPointer pointer) {}
/// <summary>
/// This method is called every time when the pointer changes.
/// </summary>
/// <param name="pointer"> The pointer. </param>
protected virtual void update(IPointer pointer) {}
/// <summary>
/// Returns pointer hash.
/// </summary>
/// <param name="pointer">The pointer.</param>
/// <returns>Integer hash value.</returns>
protected virtual uint getPointerHash(IPointer pointer)
{
return (uint) state;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.Sec
{
public sealed class SecNamedCurves
{
private SecNamedCurves()
{
}
private static BigInteger FromHex(
string hex)
{
return new BigInteger(1, Hex.Decode(hex));
}
/*
* secp112r1
*/
internal class Secp112r1Holder
: X9ECParametersHolder
{
private Secp112r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088");
BigInteger b = FromHex("659EF8BA043916EEDE8911702B22");
byte[] S = Hex.Decode("00F50B028E4D696E676875615175290472783FB1");
BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "09487239995A5EE76B55F9C2F098"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "09487239995A5EE76B55F9C2F098"
+ "A89CE5AF8724C0A23E0E0FF77500"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp112r2
*/
internal class Secp112r2Holder
: X9ECParametersHolder
{
private Secp112r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C");
BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709");
byte[] S = Hex.Decode("002757A1114D696E6768756151755316C05E0BD4");
BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "4BA30AB5E892B4E1649DD0928643"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "4BA30AB5E892B4E1649DD0928643"
+ "ADCD46F5882E3747DEF36E956E97"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r1
*/
internal class Secp128r1Holder
: X9ECParametersHolder
{
private Secp128r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3");
byte[] S = Hex.Decode("000E0D4D696E6768756151750CC03A4473D03679");
BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "161FF7528B899B2D0C28607CA52C5B86"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "161FF7528B899B2D0C28607CA52C5B86"
+ "CF5AC8395BAFEB13C02DA292DDED7A83"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r2
*/
internal class Secp128r2Holder
: X9ECParametersHolder
{
private Secp128r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1");
BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D");
byte[] S = Hex.Decode("004D696E67687561517512D8F03431FCE63B88F4");
BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "7B6AA5D85E572983E6FB32A7CDEBC140"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "7B6AA5D85E572983E6FB32A7CDEBC140"
+ "27B6916A894D3AEE7106FE805FC34B44"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160k1
*/
internal class Secp160k1Holder
: X9ECParametersHolder
{
private Secp160k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
+ "938CF935318FDCED6BC28286531733C3F03C4FEE"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r1
*/
internal class Secp160r1Holder
: X9ECParametersHolder
{
private Secp160r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^31 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
byte[] S = Hex.Decode("1053CDE42C14D696E67687561517533BF3F83345");
BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "4A96B5688EF573284664698968C38BB913CBFC82"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "4A96B5688EF573284664698968C38BB913CBFC82"
+ "23A628553168947D59DCC912042351377AC5FB32"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r2
*/
internal class Secp160r2Holder
: X9ECParametersHolder
{
private Secp160r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70");
BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA");
byte[] S = Hex.Decode("B99B99B099B323E02709A4D696E6768756151751");
BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D"
+ "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192k1
*/
internal class Secp192k1Holder
: X9ECParametersHolder
{
private Secp192k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(3);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
+ "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192r1
*/
internal class Secp192r1Holder
: X9ECParametersHolder
{
private Secp192r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^64 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
byte[] S = Hex.Decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
+ "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224k1
*/
internal class Secp224k1Holder
: X9ECParametersHolder
{
private Secp224k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(5);
byte[] S = null;
BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C"
+ "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224r1
*/
internal class Secp224r1Holder
: X9ECParametersHolder
{
private Secp224r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^96 + 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
byte[] S = Hex.Decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
+ "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256k1
*/
internal class Secp256k1Holder
: X9ECParametersHolder
{
private Secp256k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"
+ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256r1
*/
internal class Secp256r1Holder
: X9ECParametersHolder
{
private Secp256r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
byte[] S = Hex.Decode("C49D360886E704936A6678E1139D26B7819F7E90");
BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
+ "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp384r1
*/
internal class Secp384r1Holder
: X9ECParametersHolder
{
private Secp384r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^384 - 2^128 - 2^96 + 2^32 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC");
BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF");
byte[] S = Hex.Decode("A335926AA319A27A1D00896A6773A4827ACDAC73");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"
+ "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp521r1
*/
internal class Secp521r1Holder
: X9ECParametersHolder
{
private Secp521r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^521 - 1
BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00");
byte[] S = Hex.Decode("D09E8800291CB85396CC6717393284AAA0DA64BA");
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409");
BigInteger h = BigInteger.ValueOf(1);
ECCurve curve = new FpCurve(p, a, b);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"
+ "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r1
*/
internal class Sect113r1Holder
: X9ECParametersHolder
{
private Sect113r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r1Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7");
BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723");
byte[] S = Hex.Decode("10E723AB14D696E6768756151756FEBF8FCB49A9");
BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "009D73616F35F4AB1407D73562C10F"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "009D73616F35F4AB1407D73562C10F"
+ "00A52830277958EE84D1315ED31886"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r2
*/
internal class Sect113r2Holder
: X9ECParametersHolder
{
private Sect113r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r2Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7");
BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F");
byte[] S = Hex.Decode("10C0FB15760860DEF1EEF4D696E676875615175D");
BigInteger n = FromHex("010000000000000108789B2496AF93");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "01A57A6A7B26CA5EF52FCDB8164797"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "01A57A6A7B26CA5EF52FCDB8164797"
+ "00B3ADC94ED1FE674C06E695BABA1D"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r1
*/
internal class Sect131r1Holder
: X9ECParametersHolder
{
private Sect131r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r1Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8");
BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341");
byte[] S = Hex.Decode("4D696E676875615175985BD3ADBADA21B43A97E2");
BigInteger n = FromHex("0400000000000000023123953A9464B54D");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0081BAF91FDF9833C40F9C181343638399"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0081BAF91FDF9833C40F9C181343638399"
+ "078C6E7EA38C001F73C8134B1B4EF9E150"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r2
*/
internal class Sect131r2Holder
: X9ECParametersHolder
{
private Sect131r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r2Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2");
BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192");
byte[] S = Hex.Decode("985BD3ADBAD4D696E676875615175A21B43A97E3");
BigInteger n = FromHex("0400000000000000016954A233049BA98F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0356DCD8F2F95031AD652D23951BB366A8"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0356DCD8F2F95031AD652D23951BB366A8"
+ "0648F06D867940A5366D9E265DE9EB240F"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163k1
*/
internal class Sect163k1Holder
: X9ECParametersHolder
{
private Sect163k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163k1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8"
+ "0289070FB05D38FF58321F2E800536D538CCDAA3D9"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r1
*/
internal class Sect163r1Holder
: X9ECParametersHolder
{
private Sect163r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2");
BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9");
byte[] S = Hex.Decode("24B7B137C8A14D696E6768756151756FD0DA2E5C");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0369979697AB43897789566789567F787A7876A654"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0369979697AB43897789566789567F787A7876A654"
+ "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r2
*/
internal class Sect163r2Holder
: X9ECParametersHolder
{
private Sect163r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r2Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD");
byte[] S = Hex.Decode("85E25BFE5C86226CDB12016F7553F9D0E693A268");
BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "03F0EBA16286A2D57EA0991168D4994637E8343E36"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "03F0EBA16286A2D57EA0991168D4994637E8343E36"
+ "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r1
*/
internal class Sect193r1Holder
: X9ECParametersHolder
{
private Sect193r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r1Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01");
BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814");
byte[] S = Hex.Decode("103FAEC74D696E676875615175777FC5B191EF30");
BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1"
+ "0025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r2
*/
internal class Sect193r2Holder
: X9ECParametersHolder
{
private Sect193r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r2Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B");
BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE");
byte[] S = Hex.Decode("10B7B4D696E676875615175137C8A16FD0DA2211");
BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F"
+ "01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233k1
*/
internal class Sect233k1Holder
: X9ECParametersHolder
{
private Sect233k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233k1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126"
+ "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233r1
*/
internal class Sect233r1Holder
: X9ECParametersHolder
{
private Sect233r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233r1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD");
byte[] S = Hex.Decode("74D59FF07F6B413D0EA14B344B20A2DB049B50C3");
BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B"
+ "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect239k1
*/
internal class Sect239k1Holder
: X9ECParametersHolder
{
private Sect239k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect239k1Holder();
private const int m = 239;
private const int k = 158;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC"
+ "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283k1
*/
internal class Sect283k1Holder
: X9ECParametersHolder
{
private Sect283k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283k1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"
+ "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283r1
*/
internal class Sect283r1Holder
: X9ECParametersHolder
{
private Sect283r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283r1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5");
byte[] S = Hex.Decode("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"
+ "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409k1
*/
internal class Sect409k1Holder
: X9ECParametersHolder
{
private Sect409k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409k1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"
+ "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409r1
*/
internal class Sect409r1Holder
: X9ECParametersHolder
{
private Sect409r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409r1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F");
byte[] S = Hex.Decode("4099B5A457F9D69F79213D094C4BCD4D4262210B");
BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"
+ "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571k1
*/
internal class Sect571k1Holder
: X9ECParametersHolder
{
private Sect571k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571k1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(1);
byte[] S = null;
BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"
+ "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571r1
*/
internal class Sect571r1Holder
: X9ECParametersHolder
{
private Sect571r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571r1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.ValueOf(1);
BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A");
byte[] S = Hex.Decode("2AA058F73A0E33AB486B0F610410C53A7F132310");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"
+ "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B"));
return new X9ECParameters(curve, G, n, h, S);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(name, oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static SecNamedCurves()
{
DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, Secp112r1Holder.Instance);
DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, Secp112r2Holder.Instance);
DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, Secp128r1Holder.Instance);
DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, Secp128r2Holder.Instance);
DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, Secp160k1Holder.Instance);
DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, Secp160r1Holder.Instance);
DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, Secp160r2Holder.Instance);
DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, Secp192k1Holder.Instance);
DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, Secp192r1Holder.Instance);
DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, Secp224k1Holder.Instance);
DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, Secp224r1Holder.Instance);
DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, Secp256k1Holder.Instance);
DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, Secp256r1Holder.Instance);
DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, Secp384r1Holder.Instance);
DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, Secp521r1Holder.Instance);
DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, Sect113r1Holder.Instance);
DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, Sect113r2Holder.Instance);
DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, Sect131r1Holder.Instance);
DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, Sect131r2Holder.Instance);
DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, Sect163k1Holder.Instance);
DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, Sect163r1Holder.Instance);
DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, Sect163r2Holder.Instance);
DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, Sect193r1Holder.Instance);
DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, Sect193r2Holder.Instance);
DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, Sect233k1Holder.Instance);
DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, Sect233r1Holder.Instance);
DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, Sect239k1Holder.Instance);
DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, Sect283k1Holder.Instance);
DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, Sect283r1Holder.Instance);
DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, Sect409k1Holder.Instance);
DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, Sect409r1Holder.Instance);
DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, Sect571k1Holder.Instance);
DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
DerObjectIdentifier oid = (DerObjectIdentifier)
objIds[name.ToLower(CultureInfo.InvariantCulture)];
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier) objIds[name.ToLower(CultureInfo.InvariantCulture)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string) names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(objIds.Keys); }
}
}
}
| |
using System.Runtime.CompilerServices;
using Microsoft.Xna.Framework;
using Nez.PhysicsShapes;
namespace Nez.Verlet
{
/// <summary>
/// the root of the Verlet simulation. Create a World and call its update method each frame.
/// </summary>
public class VerletWorld
{
/// <summary>
/// gravity for the simulation
/// </summary>
public Vector2 gravity = new Vector2( 0, 980f );
/// <summary>
/// number of iterations that will be used for Constraint solving
/// </summary>
public int constraintIterations = 3;
/// <summary>
/// max number of iterations for the simulation as a whole
/// </summary>
public int maximumStepIterations = 5;
/// <summary>
/// Bounds of the Verlet World. Particles will be confined to this space if set.
/// </summary>
public Rectangle? simulationBounds;
/// <summary>
/// should Particles be allowed to be dragged?
/// </summary>
public bool allowDragging = true;
/// <summary>
/// squared selection radius of the mouse pointer
/// </summary>
public float selectionRadiusSquared = 20 * 20;
Particle _draggedParticle;
FastList<Composite> _composites = new FastList<Composite>();
// collision helpers
internal static Collider[] _colliders = new Collider[4];
Circle _tempCircle = new Circle( 1 );
// timing
float _leftOverTime;
float _fixedDeltaTime = 1f / 60;
int _iterationSteps;
float _fixedDeltaTimeSq;
public VerletWorld( Rectangle? simulationBounds = null )
{
this.simulationBounds = simulationBounds;
_fixedDeltaTimeSq = Mathf.pow( _fixedDeltaTime, 2 );
}
#region verlet simulation
public void update()
{
updateTiming();
if( allowDragging )
handleDragging();
for( var iteration = 1; iteration <= _iterationSteps; iteration++ )
{
for( var i = _composites.length - 1; i >= 0; i-- )
{
var composite = _composites.buffer[i];
// solve constraints
for( var s = 0; s < constraintIterations; s++ )
composite.solveConstraints();
// do the verlet integration
composite.updateParticles( _fixedDeltaTimeSq, gravity );
// handle collisions with Nez Colliders
composite.handleConstraintCollisions();
for( var j = 0; j < composite.particles.length; j++ )
{
var p = composite.particles.buffer[j];
// optinally constrain to bounds
if( simulationBounds.HasValue )
constrainParticleToBounds( p );
// optionally handle collisions with Nez Colliders
if( p.collidesWithColliders )
handleCollisions( p, composite.collidesWithLayers );
}
}
}
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void constrainParticleToBounds( Particle p )
{
var tempPos = p.position;
var bounds = simulationBounds.Value;
if( p.radius == 0 )
{
if( tempPos.Y > bounds.Height )
tempPos.Y = bounds.Height;
else if( tempPos.Y < bounds.Y )
tempPos.Y = bounds.Y;
if( tempPos.X < bounds.X )
tempPos.X = bounds.X;
else if( tempPos.X > bounds.Width )
tempPos.X = bounds.Width;
}
else
{
// special care for larger particles
if( tempPos.Y < bounds.Y + p.radius )
tempPos.Y = 2f * ( bounds.Y + p.radius ) - tempPos.Y;
if( tempPos.Y > bounds.Height - p.radius )
tempPos.Y = 2f * ( bounds.Height - p.radius ) - tempPos.Y;
if( tempPos.X > bounds.Width - p.radius )
tempPos.X = 2f * ( bounds.Width - p.radius ) - tempPos.X;
if( tempPos.X < bounds.X + p.radius )
tempPos.X = 2f * ( bounds.X + p.radius ) - tempPos.X;
}
p.position = tempPos;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void handleCollisions( Particle p, int collidesWithLayers )
{
var collidedCount = Physics.overlapCircleAll( p.position, p.radius, _colliders, collidesWithLayers );
for( var i = 0; i < collidedCount; i++ )
{
var collider = _colliders[i];
if( collider.isTrigger )
continue;
CollisionResult collisionResult;
// if we have a large enough Particle radius use a Circle for the collision check else fall back to a point
if( p.radius < 2 )
{
if( collider.shape.pointCollidesWithShape( p.position, out collisionResult ) )
{
// TODO: add a Dictionary of Collider,float that lets Colliders be setup as force volumes. The float can then be
// multiplied by the mtv here. It should be very small values, like 0.002f for example.
p.position -= collisionResult.minimumTranslationVector;
}
}
else
{
_tempCircle.radius = p.radius;
_tempCircle.position = p.position;
if( _tempCircle.collidesWithShape( collider.shape, out collisionResult ) )
{
p.position -= collisionResult.minimumTranslationVector;
}
}
}
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void updateTiming()
{
_leftOverTime += Time.deltaTime;
_iterationSteps = Mathf.truncateToInt( _leftOverTime / _fixedDeltaTime );
_leftOverTime -= (float)_iterationSteps * _fixedDeltaTime;
_iterationSteps = System.Math.Min( _iterationSteps, maximumStepIterations );
}
#endregion
#region Composite management
/// <summary>
/// adds a Composite to the simulation
/// </summary>
/// <returns>The composite.</returns>
/// <param name="composite">Composite.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T addComposite<T>( T composite ) where T : Composite
{
_composites.add( composite );
return composite;
}
/// <summary>
/// removes a Composite from the simulation
/// </summary>
/// <param name="composite">Composite.</param>
public void removeComposite( Composite composite )
{
_composites.remove( composite );
}
#endregion
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void handleDragging()
{
if( Input.leftMouseButtonPressed )
{
_draggedParticle = getNearestParticle( Input.mousePosition );
}
else if( Input.leftMouseButtonDown )
{
if( _draggedParticle != null )
_draggedParticle.position = Input.mousePosition;
}
else if( Input.leftMouseButtonReleased )
{
if( _draggedParticle != null )
_draggedParticle.position = Input.mousePosition;
_draggedParticle = null;
}
}
/// <summary>
/// gets the nearest Particle to the position. Uses the selectionRadiusSquared to determine if a Particle is near enough for consideration.
/// </summary>
/// <returns>The nearest particle.</returns>
/// <param name="position">Position.</param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public Particle getNearestParticle( Vector2 position )
{
// less than 64 and we count it
var nearestSquaredDistance = selectionRadiusSquared;
Particle particle = null;
// find nearest point
for( var j = 0; j < _composites.length; j++ )
{
var particles = _composites.buffer[j].particles;
for( var i = 0; i < particles.length; i++ )
{
var p = particles.buffer[i];
var squaredDistanceToParticle = Vector2.DistanceSquared( p.position, position );
if( squaredDistanceToParticle <= selectionRadiusSquared && ( particle == null || squaredDistanceToParticle < nearestSquaredDistance ) )
{
particle = p;
nearestSquaredDistance = squaredDistanceToParticle;
}
}
}
return particle;
}
public void debugRender( Batcher batcher )
{
for( var i = 0; i < _composites.length; i++ )
_composites.buffer[i].debugRender( batcher );
if( allowDragging )
{
if( _draggedParticle != null )
{
batcher.drawCircle( _draggedParticle.position, 8, Color.White );
}
else
{
// Highlight the nearest particle within the selection radius
var particle = getNearestParticle( Input.mousePosition );
if( particle != null )
batcher.drawCircle( particle.position, 8, Color.White * 0.4f );
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="StatusStrip.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Windows.Forms.Layout;
using System.Security.Permissions;
/// <include file='doc\StatusStrip.uex' path='docs/doc[@for="StatusStrip"]/*' />
[ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
SRDescription(SR.DescriptionStatusStrip)
]
public class StatusStrip : ToolStrip {
private const AnchorStyles AllAnchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Top;
private const AnchorStyles HorizontalAnchor = AnchorStyles.Left | AnchorStyles.Right;
private const AnchorStyles VerticalAnchor = AnchorStyles.Top | AnchorStyles.Bottom;
private BitVector32 state = new BitVector32();
private static readonly int stateSizingGrip = BitVector32.CreateMask();
private static readonly int stateCalledSpringTableLayout = BitVector32.CreateMask(stateSizingGrip);
private const int gripWidth = 12;
private RightToLeftLayoutGrip rtlLayoutGrip;
private Orientation lastOrientation = Orientation.Horizontal;
/// <include file='doc\StatusStrip.uex' path='docs/doc[@for="StatusStrip.StatusStrip"]/*' />
public StatusStrip() {
SuspendLayout();
this.CanOverflow = false;
this.LayoutStyle = ToolStripLayoutStyle.Table;
this.RenderMode = ToolStripRenderMode.System;
this.GripStyle = ToolStripGripStyle.Hidden;
SetStyle(ControlStyles.ResizeRedraw, true);
this.Stretch = true;
state[stateSizingGrip] = true;
ResumeLayout(true);
}
[
DefaultValue(false),
SRDescription(SR.ToolStripCanOverflowDescr),
SRCategory(SR.CatLayout),
Browsable(false)
]
public new bool CanOverflow {
get {
return base.CanOverflow;
}
set {
base.CanOverflow = value;
}
}
protected override bool DefaultShowItemToolTips {
get {
return false;
}
}
protected override Size DefaultSize {
get {
return new Size(200, 22);
}
}
protected override Padding DefaultPadding {
get {
if (Orientation == Orientation.Horizontal) {
if (RightToLeft == RightToLeft.No) {
return new Padding(1, 0, 14, 0);
}
else {
return new Padding(14, 0, 1, 0);
}
}
else {
// vertical
// the difference in symmetry here is that the grip does not actually rotate, it remains the same height it
// was before, so the DisplayRectangle needs to shrink up by its height.
return new Padding(1, 3, 1, DefaultSize.Height);
}
}
}
protected override DockStyle DefaultDock {
get {
return DockStyle.Bottom;
}
}
/// <include file='doc\StatusStrip.uex' path='docs/doc[@for="StatusStrip.Dock"]/*' />
[DefaultValue(DockStyle.Bottom)]
public override DockStyle Dock {
get {
return base.Dock;
}
set {
base.Dock = value;
}
}
[DefaultValue(ToolStripGripStyle.Hidden)]
public new ToolStripGripStyle GripStyle {
get {
return base.GripStyle;
}
set {
base.GripStyle = value;
}
}
[DefaultValue(ToolStripLayoutStyle.Table)]
public new ToolStripLayoutStyle LayoutStyle {
get { return base.LayoutStyle; }
set { base.LayoutStyle = value; }
}
// we do some custom stuff with padding to accomodate size grip.
// changing this is not supported at DT
[Browsable(false)]
public new Padding Padding {
get {
return base.Padding;
}
set {
base.Padding = value;
}
}
[Browsable(false)]
public new event EventHandler PaddingChanged {
add {
base.PaddingChanged += value;
}
remove {
base.PaddingChanged -= value;
}
}
private Control RTLGrip {
get{
if (rtlLayoutGrip == null) {
rtlLayoutGrip = new RightToLeftLayoutGrip();
}
return rtlLayoutGrip;
}
}
[DefaultValue(false)]
[SRDescription(SR.ToolStripShowItemToolTipsDescr)]
[SRCategory(SR.CatBehavior)]
public new bool ShowItemToolTips {
get {
return base.ShowItemToolTips;
}
set {
base.ShowItemToolTips = value;
}
}
// VSWhidbey 430251
// return whether we should paint the sizing grip.
private bool ShowSizingGrip {
get{
if (SizingGrip && IsHandleCreated) {
if (DesignMode) {
return true; // we dont care about the state of VS.
}
else {
HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this);
if (rootHwnd.Handle != IntPtr.Zero) {
return !UnsafeNativeMethods.IsZoomed(rootHwnd);
}
}
}
return false;
}
}
[
SRCategory(SR.CatAppearance),
DefaultValue(true),
SRDescription(SR.StatusStripSizingGripDescr)
]
public bool SizingGrip {
get {
return state[stateSizingGrip];
}
set {
if (value != state[stateSizingGrip]) {
state[stateSizingGrip] = value;
EnsureRightToLeftGrip();
Invalidate(true);
}
}
}
[Browsable(false)]
public Rectangle SizeGripBounds {
get {
if (SizingGrip) {
Size statusStripSize = this.Size;
// we cant necessarily make this the height of the status strip, as
// the orientation could change.
int gripHeight = Math.Min(DefaultSize.Height, statusStripSize.Height);
if (RightToLeft == RightToLeft.Yes) {
return new Rectangle(0, statusStripSize.Height - gripHeight, gripWidth, gripHeight);
}
else {
return new Rectangle(statusStripSize.Width - gripWidth, statusStripSize.Height - gripHeight, gripWidth, gripHeight);
}
}
return Rectangle.Empty;
}
}
[DefaultValue(true)]
[SRCategory(SR.CatLayout)]
[SRDescription(SR.ToolStripStretchDescr)]
public new bool Stretch {
get {
return base.Stretch;
}
set {
base.Stretch = value;
}
}
private TableLayoutSettings TableLayoutSettings {
get { return this.LayoutSettings as TableLayoutSettings; }
}
/// <include file='doc\StatusStrip.uex' path='docs/doc[@for="StatusStrip.CreateAccessibilityInstance"]/*' />
protected override AccessibleObject CreateAccessibilityInstance() {
return new StatusStripAccessibleObject(this);
}
protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) {
return new ToolStripStatusLabel(text,image,onClick);
}
protected override void Dispose( bool disposing ) {
if (disposing) {
if (rtlLayoutGrip != null) {
rtlLayoutGrip.Dispose();
rtlLayoutGrip = null;
}
}
base.Dispose(disposing);
}
// in RTL, we parent a transparent control over the grip to support mirroring.
private void EnsureRightToLeftGrip() {
if (SizingGrip && RightToLeft == RightToLeft.Yes) {
RTLGrip.Bounds = SizeGripBounds;
if (!this.Controls.Contains(RTLGrip)) {
WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection;
if (controlCollection != null) {
controlCollection.AddInternal(RTLGrip);
}
}
}
else if (rtlLayoutGrip != null) {
if (this.Controls.Contains(rtlLayoutGrip)) {
WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection;
if (controlCollection != null) {
controlCollection.RemoveInternal(rtlLayoutGrip);
}
rtlLayoutGrip.Dispose();
rtlLayoutGrip = null;
}
}
}
internal override Size GetPreferredSizeCore(Size proposedSize) {
if (LayoutStyle == ToolStripLayoutStyle.Table) {
if (proposedSize.Width == 1) {
proposedSize.Width = Int32.MaxValue;
}
if (proposedSize.Height == 1) {
proposedSize.Height = Int32.MaxValue;
}
if (Orientation == Orientation.Horizontal) {
return GetPreferredSizeHorizontal(this, proposedSize) + Padding.Size;
}
else {
return GetPreferredSizeVertical(this, proposedSize) + Padding.Size;
}
}
return base.GetPreferredSizeCore(proposedSize);
}
protected override void OnPaintBackground(PaintEventArgs e) {
base.OnPaintBackground(e);
if (ShowSizingGrip) {
Renderer.DrawStatusStripSizingGrip(new ToolStripRenderEventArgs(e.Graphics, this));
}
}
protected override void OnLayout(LayoutEventArgs levent) {
state[stateCalledSpringTableLayout] = false;
bool inDisplayedItemCollecton = false;
ToolStripItem item = levent.AffectedComponent as ToolStripItem;
int itemCount = DisplayedItems.Count;
if (item != null) {
inDisplayedItemCollecton = DisplayedItems.Contains(item);
}
if (this.LayoutStyle == ToolStripLayoutStyle.Table) {
OnSpringTableLayoutCore();
}
base.OnLayout(levent);
if (itemCount != DisplayedItems.Count || (item != null && (inDisplayedItemCollecton != DisplayedItems.Contains(item)))) {
// calling OnLayout has changed the displayed items collection
// the SpringTableLayoutCore requires the count of displayed items to
// be accurate.
// - so we need to perform layout again.
if (this.LayoutStyle == ToolStripLayoutStyle.Table) {
OnSpringTableLayoutCore();
base.OnLayout(levent);
}
}
EnsureRightToLeftGrip();
}
protected override void SetDisplayedItems() {
if (state[stateCalledSpringTableLayout]) {
bool rightToLeft = ((Orientation == Orientation.Horizontal) && (RightToLeft == RightToLeft.Yes));
// shove all items that dont fit one pixel outside the displayed region
Rectangle displayRect = DisplayRectangle;
Point noMansLand = displayRect.Location;
noMansLand.X += ClientSize.Width + 1;
noMansLand.Y += ClientSize.Height + 1;
bool overflow = false;
Rectangle lastItemBounds = Rectangle.Empty;
ToolStripItem lastItem = null;
for (int i = 0; i < Items.Count; i++) {
ToolStripItem item = Items[i];
// using spring layout we can get into a situation where there's extra items which arent
// visible.
if (overflow || ((IArrangedElement)item).ParticipatesInLayout) {
if (overflow || (SizingGrip && item.Bounds.IntersectsWith(SizeGripBounds))) {
// if the item collides with the size grip, set the location to nomansland.
SetItemLocation(item, noMansLand);
item.SetPlacement(ToolStripItemPlacement.None);
}
}
else if (lastItem != null && (lastItemBounds.IntersectsWith(item.Bounds))) {
// if it overlaps the previous element, set the location to nomansland.
SetItemLocation(item, noMansLand);
item.SetPlacement(ToolStripItemPlacement.None);
}
else if (item.Bounds.Width == 1) {
ToolStripStatusLabel panel = item as ToolStripStatusLabel;
if (panel != null && panel.Spring) {
// once we get down to one pixel, there can always be a one pixel
// distribution problem with the TLP - there's usually a spare hanging around.
// so set this off to nomansland as well.
SetItemLocation(item, noMansLand);
item.SetPlacement(ToolStripItemPlacement.None);
}
}
if (item.Bounds.Location != noMansLand){
// set the next item to inspect for collisions
lastItem = item;
lastItemBounds = lastItem.Bounds;
}
else {
// we cant fit an item, everything else after it should not be displayed
if (((IArrangedElement)item).ParticipatesInLayout) {
overflow = true;
}
}
}
}
base.SetDisplayedItems();
}
internal override void ResetRenderMode() {
RenderMode = ToolStripRenderMode.System;
}
internal override bool ShouldSerializeRenderMode() {
// We should NEVER serialize custom.
return (RenderMode != ToolStripRenderMode.System && RenderMode != ToolStripRenderMode.Custom);
}
/// <devdoc>
/// Override this function if you want to do custom table layouts for the
/// StatusStrip. The default layoutstyle is tablelayout, and we need to play
/// with the row/column styles
/// </devdoc>
protected virtual void OnSpringTableLayoutCore() {
if (this.LayoutStyle == ToolStripLayoutStyle.Table) {
state[stateCalledSpringTableLayout]= true;
this.SuspendLayout();
if (lastOrientation != Orientation) {
TableLayoutSettings settings = this.TableLayoutSettings;
settings.RowCount = 0;
settings.ColumnCount = 0;
settings.ColumnStyles.Clear();
settings.RowStyles.Clear();
}
lastOrientation = Orientation;
if (Orientation == Orientation.Horizontal) {
//
// Horizontal layout
//
TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddColumns;
int originalColumnCount = this.TableLayoutSettings.ColumnStyles.Count;
// iterate through the elements which are going to be displayed.
for (int i = 0; i < this.DisplayedItems.Count; i++) {
if (i >= originalColumnCount) {
// add if it's necessary.
this.TableLayoutSettings.ColumnStyles.Add(new ColumnStyle());
}
// determine if we "spring" or "autosize" the column
ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel;
bool spring = (panel != null && panel.Spring);
DisplayedItems[i].Anchor = (spring) ? AllAnchor : VerticalAnchor;
// spring is achieved by using 100% as the column style
ColumnStyle colStyle = this.TableLayoutSettings.ColumnStyles[i];
colStyle.Width = 100; // this width is ignored in AutoSize.
colStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize;
}
if (TableLayoutSettings.RowStyles.Count > 1 || TableLayoutSettings.RowStyles.Count == 0) {
TableLayoutSettings.RowStyles.Clear();
TableLayoutSettings.RowStyles.Add(new RowStyle());
}
TableLayoutSettings.RowCount = 1;
TableLayoutSettings.RowStyles[0].SizeType = SizeType.Absolute;
TableLayoutSettings.RowStyles[0].Height = Math.Max(0,this.DisplayRectangle.Height);
TableLayoutSettings.ColumnCount = DisplayedItems.Count+1; // add an extra cell so it fills the remaining space
// dont remove the extra column styles, just set them back to autosize.
for (int i = DisplayedItems.Count; i < TableLayoutSettings.ColumnStyles.Count; i++) {
this.TableLayoutSettings.ColumnStyles[i].SizeType = SizeType.AutoSize;
}
}
else {
//
// Vertical layout
//
TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddRows;
int originalRowCount = this.TableLayoutSettings.RowStyles.Count;
// iterate through the elements which are going to be displayed.
for (int i = 0; i < this.DisplayedItems.Count; i++) {
if (i >= originalRowCount) {
// add if it's necessary.
this.TableLayoutSettings.RowStyles.Add(new RowStyle());
}
// determine if we "spring" or "autosize" the row
ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel;
bool spring = (panel != null && panel.Spring);
DisplayedItems[i].Anchor = (spring) ? AllAnchor : HorizontalAnchor;
// spring is achieved by using 100% as the row style
RowStyle rowStyle = this.TableLayoutSettings.RowStyles[i];
rowStyle.Height = 100; // this width is ignored in AutoSize.
rowStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize;
}
TableLayoutSettings.ColumnCount = 1;
if (TableLayoutSettings.ColumnStyles.Count > 1 || TableLayoutSettings.ColumnStyles.Count == 0) {
TableLayoutSettings.ColumnStyles.Clear();
TableLayoutSettings.ColumnStyles.Add(new ColumnStyle());
}
TableLayoutSettings.ColumnCount = 1;
TableLayoutSettings.ColumnStyles[0].SizeType = SizeType.Absolute;
TableLayoutSettings.ColumnStyles[0].Width = Math.Max(0,this.DisplayRectangle.Width);
TableLayoutSettings.RowCount = DisplayedItems.Count+1; // add an extra cell so it fills the remaining space
// dont remove the extra column styles, just set them back to autosize.
for (int i = DisplayedItems.Count; i < TableLayoutSettings.RowStyles.Count; i++) {
this.TableLayoutSettings.RowStyles[i].SizeType = SizeType.AutoSize;
}
}
this.ResumeLayout(false);
}
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m) {
if ((m.Msg == NativeMethods.WM_NCHITTEST) && SizingGrip) {
// if we're within the grip bounds tell windows
// that we're the bottom right of the window.
Rectangle sizeGripBounds = SizeGripBounds;
int x = NativeMethods.Util.LOWORD(m.LParam);
int y = NativeMethods.Util.HIWORD(m.LParam);
if (sizeGripBounds.Contains(PointToClient(new Point(x, y)))) {
HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this);
// if the main window isnt maximized - we should paint a resize grip.
// double check that we're at the bottom right hand corner of the window.
if (rootHwnd.Handle != IntPtr.Zero && !UnsafeNativeMethods.IsZoomed(rootHwnd)) {
// get the client area of the topmost window. If we're next to the edge then
// the sizing grip is valid.
NativeMethods.RECT rootHwndClientArea = new NativeMethods.RECT();
UnsafeNativeMethods.GetClientRect(rootHwnd, ref rootHwndClientArea);
// map the size grip FROM statusStrip coords TO the toplevel window coords.
NativeMethods.POINT gripLocation;
if (RightToLeft == RightToLeft.Yes) {
gripLocation = new NativeMethods.POINT(SizeGripBounds.Left, SizeGripBounds.Bottom);
}
else {
gripLocation = new NativeMethods.POINT(SizeGripBounds.Right, SizeGripBounds.Bottom);
}
UnsafeNativeMethods.MapWindowPoints(new HandleRef(this, this.Handle), rootHwnd, gripLocation, 1);
int deltaBottomEdge = Math.Abs(rootHwndClientArea.bottom - gripLocation.y);
int deltaRightEdge = Math.Abs(rootHwndClientArea.right - gripLocation.x);
if (RightToLeft != RightToLeft.Yes) {
if ((deltaRightEdge + deltaBottomEdge) < 2) {
m.Result = (IntPtr)NativeMethods.HTBOTTOMRIGHT;
return;
}
}
}
}
}
base.WndProc(ref m);
}
// special transparent mirrored window which says it's the bottom left of the form.
private class RightToLeftLayoutGrip : Control {
public RightToLeftLayoutGrip() {
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Transparent;
}
protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
CreateParams cp = base.CreateParams;
cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL;
return cp;
}
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m) {
if (m.Msg == NativeMethods.WM_NCHITTEST) {
int x = NativeMethods.Util.LOWORD(m.LParam);
int y = NativeMethods.Util.HIWORD(m.LParam);
if (ClientRectangle.Contains(PointToClient(new Point(x, y)))) {
m.Result = (IntPtr)NativeMethods.HTBOTTOMLEFT;
return;
}
}
base.WndProc(ref m);
}
}
[System.Runtime.InteropServices.ComVisible(true)]
internal class StatusStripAccessibleObject : ToolStripAccessibleObject {
public StatusStripAccessibleObject(StatusStrip owner) : base(owner) {
}
public override AccessibleRole Role {
get {
AccessibleRole role = Owner.AccessibleRole;
if (role != AccessibleRole.Default) {
return role;
}
return AccessibleRole.StatusBar;
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Streams;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private readonly Logger logger;
private readonly Logger appLogger;
private readonly ClientConfiguration config;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects;
private readonly ProxiedMessageCenter transport;
private bool listenForMessages;
private CancellationTokenSource listeningCts;
private bool firstMessageReceived;
private readonly ClientProviderRuntime clientProviderRuntime;
private readonly StatisticsProviderManager statisticsProviderManager;
internal ClientStatisticsManager ClientStatistics;
private GrainId clientId;
private readonly GrainId handshakeClientId;
private IGrainTypeResolver grainInterfaceMap;
private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
private readonly Func<Message, bool> tryResendMessage;
private readonly Action<Message> unregisterCallback;
// initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min
private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1);
private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1);
private const string BARS = "----------";
private readonly GrainFactory grainFactory;
public IInternalGrainFactory InternalGrainFactory
{
get { return grainFactory; }
}
/// <summary>
/// Response timeout.
/// </summary>
private TimeSpan responseTimeout;
private static readonly Object staticLock = new Object();
private TypeMetadataCache typeCache;
private readonly AssemblyProcessor assemblyProcessor;
Logger IRuntimeClient.AppLogger
{
get { return appLogger; }
}
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public string CurrentActivationIdentity
{
get { return CurrentActivationAddress.ToString(); }
}
internal IList<Uri> Gateways
{
get
{
return transport.GatewayManager.ListProvider.GetGateways().GetResult();
}
}
public IStreamProviderManager CurrentStreamProviderManager { get; private set; }
public IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return clientProviderRuntime; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false)
{
this.typeCache = new TypeMetadataCache();
this.assemblyProcessor = new AssemblyProcessor(this.typeCache);
this.grainFactory = new GrainFactory(this, this.typeCache);
if (cfg == null)
{
Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
}
this.config = cfg;
if (!LogManager.IsInitialized) LogManager.Initialize(config);
StatisticsCollector.Initialize(config);
SerializationManager.Initialize(cfg.SerializationProviders, cfg.FallbackSerializationProvider);
this.assemblyProcessor.Initialize();
logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
appLogger = LogManager.GetLogger("Application", LoggerType.Application);
BufferPool.InitGlobalBufferPool(config);
this.handshakeClientId = GrainId.NewClientId();
tryResendMessage = TryResendMessage;
unregisterCallback = msg => UnRegisterCallback(msg.Id);
try
{
LoadAdditionalAssemblies();
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
if (!secondary)
{
UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
// Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
SerializationManager.GetDeserializer(typeof(String));
clientProviderRuntime = new ClientProviderRuntime(grainFactory, null);
statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
{
config.StatisticsProviderName = statsProviderName;
}
responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);
// Client init / sign-on message
logger.Info(ErrorCode.ClientInitializing, string.Format(
"{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
BARS, config.DNSHostName, localAddress, handshakeClientId));
string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
BARS, RuntimeVersion.Current, PrintAppDomainDetails());
startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
logger.Info(ErrorCode.ClientStarting, startMsg);
if (TestOnlyThrowExceptionDuringInit)
{
throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
}
config.CheckGatewayProviderSettings();
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
var gatewayListProvider = new GatewayProviderFactory(this.config).CreateGatewayListProvider();
gatewayListProvider.InitializeGatewayListProvider(this.config, LogManager.GetLogger(gatewayListProvider.GetType().Name)).WaitWithThrow(initTimeout);
transport = new ProxiedMessageCenter(config, localAddress, generation, handshakeClientId, gatewayListProvider);
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
private void StreamingInitialize()
{
var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result;
clientProviderRuntime.StreamingInitialize(implicitSubscriberTable);
var streamProviderManager = new Streams.StreamProviderManager();
streamProviderManager
.LoadStreamProviders(
this.config.ProviderConfigurations,
clientProviderRuntime)
.Wait();
CurrentStreamProviderManager = streamProviderManager;
}
private void LoadAdditionalAssemblies()
{
#if !NETSTANDARD_TODO
var logger = LogManager.GetLogger("AssemblyLoader.Client", LoggerType.Runtime);
var directories =
new Dictionary<string, SearchOption>
{
{
Path.GetDirectoryName(typeof(OutsideRuntimeClient).GetTypeInfo().Assembly.Location),
SearchOption.AllDirectories
}
};
var excludeCriteria =
new AssemblyLoaderPathNameCriterion[]
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies,
AssemblyLoaderCriteria.ExcludeSystemBinaries()
};
var loadProvidersCriteria =
new AssemblyLoaderReflectionCriterion[]
{
AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider))
};
this.assemblyProcessor.Initialize();
AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger);
#endif
}
private void UnhandledException(ISchedulingContext context, Exception exception)
{
logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception);
logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client.");
}
public void Start()
{
lock (staticLock)
{
if (RuntimeClient.Current != null)
throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain");
RuntimeClient.Current = this;
}
StartInternal();
logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + handshakeClientId);
}
// used for testing to (carefully!) allow two clients in the same process
internal void StartInternal()
{
transport.Start();
LogManager.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started.
CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, handshakeClientId);
ClientStatistics = new ClientStatisticsManager(config);
listeningCts = new CancellationTokenSource();
var ct = listeningCts.Token;
listenForMessages = true;
// Keeping this thread handling it very simple for now. Just queue task on thread pool.
Task.Factory.StartNew(() =>
{
try
{
RunClientMessagePump(ct);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
}
}
);
grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result;
ClientStatistics.Start(statisticsProviderManager, transport, clientId)
.WaitWithThrow(initTimeout);
StreamingInitialize();
}
private void RunClientMessagePump(CancellationToken ct)
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartExecution();
}
while (listenForMessages)
{
var message = transport.WaitMessage(Message.Categories.Application, ct);
if (message == null) // if wait was cancelled
break;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartProcessing();
}
#endif
// when we receive the first message, we update the
// clientId for this client because it may have been modified to
// include the cluster name
if (!firstMessageReceived)
{
firstMessageReceived = true;
if (!handshakeClientId.Equals(message.TargetGrain))
{
clientId = message.TargetGrain;
transport.UpdateClientId(clientId);
CurrentActivationAddress = ActivationAddress.GetAddress(transport.MyAddress, clientId, CurrentActivationAddress.Activation);
}
else
{
clientId = handshakeClientId;
}
}
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.DispatchToLocalObject(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message));
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopProcessing();
incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed();
}
#endif
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}
private void DispatchToLocalObject(Message message)
{
LocalObjectData objectData;
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
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 (localObjects.TryGetValue(observerId, out objectData))
this.InvokeLocalObjectAsync(objectData, message);
else
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void InvokeLocalObjectAsync(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.
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));
LocalObjectData ignore;
// Try to remove. If it's not there, we don't care.
localObjects.TryRemove(objectData.ObserverId, out ignore);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start);
if (start)
{
// we use Task.Run() 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());
Func<Task> asyncFunc =
async () =>
await this.LocalObjectMessagePumpAsync(objectData);
Task.Run(asyncFunc).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;
RequestContext.Import(message.RequestContextData);
var request = (InvokeMethodRequest)message.BodyObject;
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)
await this.SendResponseAsync(message, resultObject);
}
catch (Exception)
{
// ignore, keep looping.
}
}
}
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 Task
SendResponseAsync(
Message message,
object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
return TaskDone.Done;
object deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = SerializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
SendResponse(message, Response.ExceptionResponse(exc2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.", exc2);
return TaskDone.Done;
}
// the deep-copy succeeded.
SendResponse(message, new Response(deepCopy));
return TaskDone.Done;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.BodyObject;
switch (message.Direction)
{
default:
throw new InvalidOperationException();
case Message.Directions.OneWay:
{
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)SerializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
SendResponse(message, Response.ExceptionResponse(ex2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
SendResponse(message, response);
break;
}
}
}
private void SendResponse(Message request, Response response)
{
var message = request.CreateResponseMessage();
message.BodyObject = response;
transport.SendMessage(message);
}
/// <summary>
/// For testing only.
/// </summary>
public void Disconnect()
{
transport.Disconnect();
}
/// <summary>
/// For testing only.
/// </summary>
public void Reconnect()
{
transport.Reconnect();
}
#region Implementation of IRuntimeClient
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")]
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var message = Message.CreateMessage(request, options);
SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments);
}
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
message.TargetGrain = targetGrainId;
if (!String.IsNullOrEmpty(genericArguments))
message.GenericGrainType = genericArguments;
if (targetGrainId.IsSystemTarget)
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = target.SystemTargetSilo;
if (target.SystemTargetSilo != null)
{
message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo);
}
}
// Client sending messages to another client (observer). Yes, we support that.
if (target.IsObserverReference)
{
message.TargetObserverId = target.ObserverId;
}
if (debugContext != null)
{
message.DebugContext = debugContext;
}
if (message.IsExpirableMessage(config))
{
// don't set expiration for system target messages.
message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW;
}
if (!oneWay)
{
var callbackData = new CallbackData(
callback,
tryResendMessage,
context,
message,
unregisterCallback,
config);
callbacks.TryAdd(message.Id, callbackData);
callbackData.StartTimer(responseTimeout);
}
if (logger.IsVerbose2) logger.Verbose2("Send {0}", message);
transport.SendMessage(message);
}
private bool TryResendMessage(Message message)
{
if (!message.MayResend(config))
{
return false;
}
if (logger.IsVerbose) logger.Verbose("Resend {0}", message);
message.ResendCount = message.ResendCount + 1;
message.TargetHistory = message.GetTargetHistory();
if (!message.TargetGrain.IsSystemTarget)
{
message.TargetActivation = null;
message.TargetSilo = null;
message.ClearTargetAddress();
}
transport.SendMessage(message);
return true;
}
public void ReceiveResponse(Message response)
{
if (logger.IsVerbose2) logger.Verbose2("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest)
return;
CallbackData callbackData;
var found = callbacks.TryGetValue(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContext.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnRegisterCallback(CorrelationId id)
{
CallbackData ignore;
callbacks.TryRemove(id, out ignore);
}
public void Reset(bool cleanup)
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
});
Utils.SafeExecute(() =>
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset(cleanup).WaitWithThrow(resetTimeout);
}
}, logger, "Client.clientProviderRuntime.Reset");
Utils.SafeExecute(() =>
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.PrepareToStop();
}
}, logger, "Client.PrepareToStop-Transport");
listenForMessages = false;
Utils.SafeExecute(() =>
{
if (listeningCts != null)
{
listeningCts.Cancel();
}
}, logger, "Client.Stop-ListeningCTS");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
try
{
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
}
catch (Exception) { }
try
{
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception) { }
try
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}
catch (Exception) { }
try
{
LogManager.UnInitialize();
}
catch (Exception) { }
}
public void SetResponseTimeout(TimeSpan timeout)
{
responseTimeout = timeout;
}
public TimeSpan GetResponseTimeout()
{
return responseTimeout;
}
public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context, string activityName)
{
await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool
}
public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.");
GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId());
if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
{
throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
}
return gr;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference))
throw new ArgumentException("Argument reference is not a grain reference.");
var reference = (GrainReference)obj;
LocalObjectData ignore;
if (!localObjects.TryRemove(reference.ObserverId, out ignore))
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
#endregion Implementation of IRuntimeClient
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload,
String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails()));
LogManager.Flush();
}
catch (Exception)
{
// just ignore, make sure not to throw from here.
}
}
private string PrintAppDomainDetails()
{
#if NETSTANDARD_TODO
return "N/A";
#else
return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName);
#endif
}
private class LocalObjectData
{
internal WeakReference LocalObject { get; private set; }
internal IGrainMethodInvoker Invoker { get; private set; }
internal GuidId ObserverId { get; private set; }
internal Queue<Message> Messages { get; private set; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
LocalObject = new WeakReference(obj);
ObserverId = observerId;
Invoker = invoker;
Messages = new Queue<Message>();
Running = false;
}
}
public void Dispose()
{
if (listeningCts != null)
{
listeningCts.Dispose();
listeningCts = null;
this.assemblyProcessor.Dispose();
}
transport.Dispose();
if (ClientStatistics != null)
{
ClientStatistics.Dispose();
ClientStatistics = null;
}
GC.SuppressFinalize(this);
}
public IGrainTypeResolver GrainTypeResolver
{
get { return grainInterfaceMap; }
}
public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo)
{
foreach (var callback in callbacks)
{
if (deadSilo.Equals(callback.Value.Message.TargetSilo))
{
callback.Value.OnTargetSiloFail();
}
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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 CallButler.Telecom.Forms
{
partial class RequestLineCountForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RequestLineCountForm));
this.lblLineCount = new System.Windows.Forms.Label();
this.numLineCount = new System.Windows.Forms.NumericUpDown();
this.btnOK = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.numLineCount)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// lblLineCount
//
this.lblLineCount.AutoSize = true;
this.lblLineCount.BackColor = System.Drawing.Color.Transparent;
this.lblLineCount.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.lblLineCount.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblLineCount.Location = new System.Drawing.Point(18, 146);
this.lblLineCount.Name = "lblLineCount";
this.lblLineCount.Size = new System.Drawing.Size(41, 13);
this.lblLineCount.TabIndex = 17;
this.lblLineCount.Text = "Launch";
//
// numLineCount
//
this.numLineCount.Location = new System.Drawing.Point(61, 144);
this.numLineCount.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numLineCount.Name = "numLineCount";
this.numLineCount.Size = new System.Drawing.Size(50, 21);
this.numLineCount.TabIndex = 20;
this.numLineCount.Value = new decimal(new int[] {
4,
0,
0,
0});
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnOK.Location = new System.Drawing.Point(319, 147);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 21;
this.btnOK.Text = "&OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.label1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.label1.Location = new System.Drawing.Point(18, 58);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(376, 74);
this.label1.TabIndex = 22;
this.label1.Text = resources.GetString("label1.Text");
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.label2.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.label2.Location = new System.Drawing.Point(117, 146);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(124, 13);
this.label2.TabIndex = 23;
this.label2.Text = "concurrent Skype clients";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(58, 22);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(83, 13);
this.label3.TabIndex = 25;
this.label3.Text = "Skype Clients";
//
// pictureBox1
//
this.pictureBox1.Image = global::CallButler.Telecom.Properties.Resources.about;
this.pictureBox1.Location = new System.Drawing.Point(18, 13);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(32, 32);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 24;
this.pictureBox1.TabStop = false;
//
// RequestLineCountForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(412, 188);
this.Controls.Add(this.label3);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.numLineCount);
this.Controls.Add(this.lblLineCount);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "RequestLineCountForm";
this.Padding = new System.Windows.Forms.Padding(15, 10, 15, 15);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Concurrent Connections";
this.TopMost = true;
((System.ComponentModel.ISupportInitialize)(this.numLineCount)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblLineCount;
private System.Windows.Forms.NumericUpDown numLineCount;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PictureBox pictureBox1;
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// String.System.IConvertible.ToUInt16(IFormatProvider provider)
/// This method supports the .NET Framework infrastructure and is
/// not intended to be used directly from your code.
/// Converts the value of the current String object to a 16-bit unsigned integer.
/// </summary>
class IConvertibleToUInt16
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
IConvertibleToUInt16 iege = new IConvertibleToUInt16();
TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToUInt16(IFormatProvider)");
if (iege.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test scenarioes
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Random numeric string";
const string c_TEST_ID = "P001";
string strSrc;
IFormatProvider provider;
UInt16 i;
bool expectedValue = true;
bool actualValue = false;
i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (i == ((IConvertible)strSrc).ToUInt16(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Positive sign";
const string c_TEST_ID = "P002";
string strSrc;
IFormatProvider provider;
NumberFormatInfo ni = new NumberFormatInfo();
UInt16 i;
bool expectedValue = true;
bool actualValue = false;
i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSrc = ni.PositiveSign + i.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (i == ((IConvertible)strSrc).ToUInt16(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: string is Int16.MaxValue";
const string c_TEST_ID = "P003";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = UInt16.MaxValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (UInt16.MaxValue == ((IConvertible)strSrc).ToUInt16(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: string is Int16.MinValue";
const string c_TEST_ID = "P004";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = UInt16.MinValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (UInt16.MinValue == ((IConvertible)strSrc).ToUInt16(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion // end for positive test scenarioes
#region Negative test scenarios
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed";
const string c_TEST_ID = "N001";
string strSrc;
IFormatProvider provider;
strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN);
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToUInt16(provider);
TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue";
const string c_TEST_ID = "N002";
string strSrc;
IFormatProvider provider;
int i;
i = TestLibrary.Generator.GetInt16(-55) + UInt16.MaxValue + 1;
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToUInt16(provider);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue";
const string c_TEST_ID = "N003";
string strSrc;
IFormatProvider provider;
int i;
i = -1 * (TestLibrary.Generator.GetInt32(-55) % UInt16.MaxValue) + UInt16.MinValue - 1;
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToUInt16(provider);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion
private string GetDataString(string strSrc, IFormatProvider provider)
{
string str1, str2, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str2 = (null == provider) ? "null" : provider.ToString();
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Format provider string]\n {0}", str2);
return str;
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Resources;
using System.Text;
using System.Threading;
using log4net;
namespace Memcached.ClientLibrary
{
/// <summary>
/// Memcached C# client, utility class for Socket IO.
///
/// This class is a wrapper around a Socket and its streams.
/// </summary>
public class SockIO
{
// logger
private static ILog Log = LogManager.GetLogger(typeof(SockIO));
// id generator. Gives ids to all the SockIO instances
private static int IdGenerator;
// id
private int _id;
// time created
private DateTime _created;
// pool
private SockIOPool _pool;
// data
private String _host;
private Socket _socket;
private Stream _networkStream;
private SockIO()
{
_id = Interlocked.Increment(ref IdGenerator);
_created = DateTime.Now;
}
/// <summary>
/// creates a new SockIO object wrapping a socket
/// connection to host:port, and its input and output streams
/// </summary>
/// <param name="pool">Pool this object is tied to</param>
/// <param name="host">host to connect to</param>
/// <param name="port">port to connect to</param>
/// <param name="timeout">int ms to block on data for read</param>
/// <param name="connectTimeout">timeout (in ms) for initial connection</param>
/// <param name="noDelay">TCP NODELAY option?</param>
public SockIO(SockIOPool pool, String host, int port, int timeout, int connectTimeout, bool noDelay)
: this()
{
if (host == null || host.Length == 0)
throw new ArgumentNullException(GetLocalizedString("host"), GetLocalizedString("null host"));
_pool = pool;
if (connectTimeout > 0)
{
_socket = GetSocket(host, port, connectTimeout);
}
else
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(new IPEndPoint(IPAddress.Parse(host), port));
}
_networkStream = new BufferedStream(new NetworkStreamIgnoreSeek(_socket));
_host = host + ":" + port;
}
/// <summary>
/// creates a new SockIO object wrapping a socket
/// connection to host:port, and its input and output streams
/// </summary>
/// <param name="pool">Pool this object is tied to</param>
/// <param name="host">hostname:port</param>
/// <param name="timeout">read timeout value for connected socket</param>
/// <param name="connectTimeout">timeout for initial connections</param>
/// <param name="noDelay">TCP NODELAY option?</param>
public SockIO(SockIOPool pool, String host, int timeout, int connectTimeout, bool noDelay)
: this()
{
if (host == null || host.Length == 0)
throw new ArgumentNullException(GetLocalizedString("host"), GetLocalizedString("null host"));
_pool = pool;
String[] ip = host.Split(':');
// get socket: default is to use non-blocking connect
if (connectTimeout > 0)
{
_socket = GetSocket(ip[0], int.Parse(ip[1], new System.Globalization.NumberFormatInfo()), connectTimeout);
}
else
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(new IPEndPoint(IPAddress.Parse(ip[0]), int.Parse(ip[1], new System.Globalization.NumberFormatInfo())));
}
_networkStream = new BufferedStream(new NetworkStreamIgnoreSeek(_socket));
_host = host;
}
/// <summary>
/// Method which spawns thread to get a connection and then enforces a timeout on the initial
/// connection.
///
/// This should be backed by a thread pool. Any volunteers?
/// </summary>
/// <param name="host">host to establish connection to</param>
/// <param name="port">port on that host</param>
/// <param name="timeout">connection timeout in ms</param>
/// <returns>connected socket</returns>
protected static Socket GetSocket(String host, int port, int timeout)
{
// Create a new thread which will attempt to connect to host:port, and start it running
ConnectThread thread = new ConnectThread(host, port);
thread.Start();
int timer = 0;
int sleep = 25;
while (timer < timeout)
{
// if the thread has a connected socket
// then return it
if (thread.IsConnected)
return thread.Socket;
// if the thread had an error
// then throw a new IOException
if (thread.IsError)
throw new IOException();
try
{
// sleep for short time before polling again
Thread.Sleep(sleep);
}
catch (ThreadInterruptedException) { }
// Increment timer
timer += sleep;
}
// made it through loop without getting connection
// the connection thread will timeout on its own at OS timeout
throw new IOException(GetLocalizedString("connect timeout").Replace("$$timeout$$", timeout.ToString(new System.Globalization.NumberFormatInfo())));
}
/// <summary>
/// returns the host this socket is connected to
///
/// String representation of host (hostname:port)
/// </summary>
public string Host
{
get { return _host; }
}
/// <summary>
/// closes socket and all streams connected to it
/// </summary>
public void TrueClose()
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("true close socket").Replace("$$Socket$$", ToString()).Replace("$$Lifespan$$", DateTime.Now.Subtract(_created).ToString()));
}
bool err = false;
StringBuilder errMsg = new StringBuilder();
if (_socket == null || _networkStream == null)
{
err = true;
errMsg.Append(GetLocalizedString("socket already closed"));
}
if (_socket != null)
{
try
{
_socket.Close();
}
catch (IOException ioe)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host), ioe);
}
errMsg.Append(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host) + System.Environment.NewLine);
errMsg.Append(ioe.ToString());
err = true;
}
catch (SocketException soe)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host), soe);
}
errMsg.Append(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host) + System.Environment.NewLine);
errMsg.Append(soe.ToString());
err = true;
}
}
// check in to pool
if (_socket != null)
_pool.CheckIn(this, false);
_networkStream = null;
_socket = null;
if (err)
throw new IOException(errMsg.ToString());
}
/// <summary>
/// sets closed flag and checks in to connection pool
/// but does not close connections
/// </summary>
public void Close()
{
// check in to pool
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("close socket").Replace("$$ToString$$", ToString()));
}
_pool.CheckIn(this);
}
/// <summary>
/// Gets whether or not the socket is connected. Returns <c>true</c> if it is.
/// </summary>
public bool IsConnected
{
get { return _socket != null && _socket.Connected; }
}
/// <summary>
/// reads a line
/// intentionally not using the deprecated readLine method from DataInputStream
/// </summary>
/// <returns>String that was read in</returns>
public string ReadLine()
{
if (_socket == null || !_socket.Connected)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("read closed socket"));
}
throw new IOException(GetLocalizedString("read closed socket"));
}
byte[] b = new byte[1];
MemoryStream memoryStream = new MemoryStream();
bool eol = false;
while (_networkStream.Read(b, 0, 1) != -1)
{
if (b[0] == 13)
{
eol = true;
}
else
{
if (eol)
{
if (b[0] == 10)
break;
eol = false;
}
}
// cast byte into char array
memoryStream.Write(b, 0, 1);
}
if (memoryStream == null || memoryStream.Length <= 0)
{
throw new IOException(GetLocalizedString("closing dead stream"));
}
// else return the string
string temp = UTF8Encoding.UTF8.GetString(memoryStream.GetBuffer()).TrimEnd('\0', '\r', '\n');
return temp;
}
/// <summary>
/// reads up to end of line and returns nothing
/// </summary>
public void ClearEndOfLine()
{
if (_socket == null || !_socket.Connected)
{
Log.Error(GetLocalizedString("read closed socket"));
throw new IOException(GetLocalizedString("read closed socket"));
}
byte[] b = new byte[1];
bool eol = false;
while (_networkStream.Read(b, 0, 1) != -1)
{
// only stop when we see
// \r (13) followed by \n (10)
if (b[0] == 13)
{
eol = true;
continue;
}
if (eol)
{
if (b[0] == 10)
break;
eol = false;
}
}
}
/// <summary>
/// reads length bytes into the passed in byte array from stream
/// </summary>
/// <param name="b">byte array</param>
public void Read(byte[] bytes)
{
if (_socket == null || !_socket.Connected)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("read closed socket"));
}
throw new IOException(GetLocalizedString("read closed socket"));
}
if (bytes == null)
return;
int count = 0;
while (count < bytes.Length)
{
int cnt = _networkStream.Read(bytes, count, (bytes.Length - count));
count += cnt;
}
}
/// <summary>
/// flushes output stream
/// </summary>
public void Flush()
{
if (_socket == null || !_socket.Connected)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("write closed socket"));
}
throw new IOException(GetLocalizedString("write closed socket"));
}
_networkStream.Flush();
}
/// <summary>
/// writes a byte array to the output stream
/// </summary>
/// <param name="bytes">byte array to write</param>
public void Write(byte[] bytes)
{
Write(bytes, 0, bytes.Length);
}
/// <summary>
/// writes a byte array to the output stream
/// </summary>
/// <param name="bytes">byte array to write</param>
/// <param name="offset">offset to begin writing from</param>
/// <param name="count">count of bytes to write</param>
public void Write(byte[] bytes, int offset, int count)
{
if (_socket == null || !_socket.Connected)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("write closed socket"));
}
throw new IOException(GetLocalizedString("write closed socket"));
}
if (bytes != null)
_networkStream.Write(bytes, offset, count);
}
/// <summary>
/// returns the string representation of this socket
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (_socket == null)
return "";
return _id.ToString(new System.Globalization.NumberFormatInfo());
}
/// <summary>
/// Thread to attempt connection.
/// This will be polled by the main thread. We run the risk of filling up w/
/// threads attempting connections if network is down. However, the falling off
/// mech in the main code should limit this.
/// </summary>
private class ConnectThread
{
//thread
Thread _thread;
// logger
private static ILog Log = LogManager.GetLogger(typeof(ConnectThread));
private Socket _socket;
private String _host;
private int _port;
bool _error;
/// <summary>
/// Constructor
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
public ConnectThread(string host, int port)
{
_host = host;
_port = port;
_thread = new Thread(new ThreadStart(Connect));
_thread.IsBackground = true;
}
/// <summary>
/// The logic of the thread.
/// </summary>
private void Connect()
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(new IPEndPoint(IPAddress.Parse(_host), _port));
}
catch (IOException)
{
_error = true;
}
catch (SocketException ex)
{
_error = true;
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("socket connection exception"), ex);
}
}
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("connect thread connect").Replace("$$Host$$", _host));
}
}
/// <summary>
/// start thread running.
/// This attempts to establish a connection.
/// </summary>
public void Start()
{
_thread.Start();
}
/// <summary>
/// Is the new socket connected yet
/// </summary>
public bool IsConnected
{
get { return _socket != null && _socket.Connected; }
}
/// <summary>
/// Did we have an exception while connecting?
/// </summary>
/// <returns></returns>
public bool IsError
{
get { return _error; }
}
/// <summary>
/// Return the socket.
/// </summary>
public Socket Socket
{
get { return _socket; }
}
}
private static ResourceManager _resourceManager = new ResourceManager("Memcached.ClientLibrary.StringMessages", typeof(SockIO).Assembly);
private static string GetLocalizedString(string key)
{
return _resourceManager.GetString(key);
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
// Initialize the Toolbar
//==============================================================================
function SceneToolbar_GridSizeEdit::onValidate(%this) {
devLog(" SceneToolbar_GridSizeEdit::onValidate",%this.getText());
Lab.setGridSize( %this.getText());
}
//==============================================================================
function Lab::initAllToolbarGroups(%this) {
EGuiCustomizer-->saveToolbar.active = false;
if (!isObject(EToolbarDisabledDrop)) {
%new = new GuiContainer(EToolbarDisabledDrop) {
horizSizing = "width";
vertSizing = "height";
profile = "ToolsDefaultProfile_NoModal";
};
EditorGuiToolbar.add(%new);
}
EditorGuiToolbar.pushToBack(EToolbarDisabledDrop);
EToolbarDisabledDrop.fitIntoParents();
hide(EToolbarDisabledDrop);
if (isObject(EGuiCustom_ToolbarMenu)) {
EGuiCustom_ToolbarMenu.clear();
EGuiCustom_ToolbarMenu.add("All toolbar",%tb = 0);
foreach(%gui in LabToolbarGuiSet) {
Lab.initToolbarGroup(%gui);
EGuiCustom_ToolbarMenu.add(%gui.getName(),%tb++);
}
EGuiCustom_ToolbarMenu.setText("All toolbar");
}
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::initToolbarGroup(%this,%gui) {
if (%gui.plugin $= "")
%gui.plugin = strreplace(%gui.getName(),"Toolbar","");
%pluginObj = %gui.plugin@"Plugin";
if (isObject(%pluginObj)) {
%pluginObj.iconList = "";
%pluginObj.toolbarGui = %gui;
%pluginObj.toolbarGroups = "";
%toolbarName = %pluginObj.plugin;
}
if (%toolbarName $= "")
%toolbarName = strreplace(%gui.getName(),"Toolbar","");
%gui.toolbarName = %toolbarName;
//if (%gui.plugin !$= %pluginObj.plugin && %gui.plugin !$= "")
//%gui.plugin = "";
//if (!isObject(%pluginObj))
//warnLog("Can't find the plugin obj for gui:",%gui,%gui.getName());
%defaultStack = %gui;
if (%gui.getClassName() !$= "GuiStackControl")
%defaultStack = %gui.getObject(0);
%defaultStack.superClass = "ToolbarPluginStack";
%gui.defaultStack = %defaultStack;
%disabledDropContainer = EToolbarDisabledDrop.findObjectByInternalName(%gui.getName());
if (!isObject(%disabledDropContainer)) {
%disabledDropContainer = new GuiContainer() {
extent = %gui.extent;
horizSizing = "width";
profile = "ToolsOverlayDisabledProfile";
internalName = %gui.getName();
superClass = "PluginToolbarEnd";
};
EToolbarDisabledDrop.add(%disabledDropContainer);
}
LabGeneratedSet.add(EToolbarDisabledDrop); //Dont save those with EditorGui
%disabledDropContainer.profile = "ToolsFillDarkA_T50";
%disabledDropContainer.pluginName = %toolbarName;
%disabledDropContainer.toolbarName = %toolbarName;
%disabledDropContainer.setPosition(%gui.position.x,%gui.position.y);
hide(%disabledDropContainer);
Lab.getStackEndGui(%gui,false);
%disabled = %gui.defaultStack-->DisabledIcons;
if (!isObject(%disabled)) {
%disabled = new GuiContainer() {
extent = "84 30";
profile = "ToolsDefaultProfile";
internalName = "DisabledIcons";
visible = 0;
};
%defaultStack.add(%disabled);
}
%gui.disabledGroup = %disabled;
%defaultStack.pushToBack(%end);
foreach(%ctrl in %defaultStack) {
if (%ctrl.getClassName() $= "GuiStackControl") {
if (isObject(%pluginObj))
%pluginObj.toolbarGroups = strAddWord(%pluginObj.toolbarGroups,%ctrl.getId());
%gui.toolbarGroups = strAddWord(%gui.toolbarGroups,%ctrl.getId());
}
}
%gui.stackLists = "";
%this.scanPluginToolbarGroup(%defaultStack,"",%toolbarName,%pluginObj,%gui);
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::scanPluginToolbarGroup(%this,%group,%level,%toolbarName,%pluginObj,%gui) {
%pluginText = "";
%pluginName= "";
if (isObject(%pluginObj)) {
%pluginName = %pluginObj.plugin;
}
foreach(%ctrl in %group) {
%ctrl.pluginName = %pluginName;
%ctrl.toolbarName = %toolbarName;
if (%ctrl.isMemberOfClass("GuiStackControl")) {
Lab.getStackEndGui(%ctrl,true);
%gui.stackLists = strAddWord(%gui.stackLists,%ctrl.getId(),true);
%this.scanPluginToolbarStack(%ctrl,%toolbarName,%pluginObj,%gui);
//%this.scanPluginToolbarGroup(%ctrl,%level++,%pluginObj,%gui);
continue;
}
if (%ctrl.isMemberOfClass("GuiIconButtonCtrl")) {
%ctrl.superClass = "ToolbarIcon";
%ctrl.useMouseEvents = true;
%ctrl.toolbar = %pluginObj.toolbarGui;
%pluginObj.iconList = strAddWord(%pluginObj.iconList,%ctrl.getId());
}
continue;
if (%ctrl.isMemberOfClass("GuiContainer")) {
%this.scanPluginToolbarGroup(%ctrl,%level++,%toolbarName,%pluginObj,%gui);
continue;
}
if (%ctrl.isMemberOfClass("GuiMouseEventCtrl")) {
%ctrl.superClass = "ToolbarGroup";
%this.scanPluginToolbarGroup(%ctrl,%level++,%toolbarName,%pluginObj,%gui);
continue;
} else if (%group.isMemberOfClass("GuiStackControl")) {
%ctrl.toolbar = %pluginObj.toolbarGui;
%pluginObj.iconList = strAddWord(%pluginObj.iconList,%ctrl.getId());
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::scanPluginToolbarStack(%this,%stack,%toolbarName,%pluginObj,%gui) {
%pluginText = "";
%pluginName = "";
if (isObject(%pluginObj)) {
%pluginName = %pluginObj.plugin;
}
foreach(%ctrl in %stack) {
%ctrl.pluginName = %pluginName;
%ctrl.toolbarName = %toolbarName;
%ctrl.toolbar = %gui;
if (%ctrl.isMemberOfClass("GuiContainer")) {
%dropTarget = %stack.getObjectIndex(%ctrl);
foreach(%subCtrl in %ctrl) {
if (%subCtrl.isMemberOfClass("GuiMouseEventCtrl")) {
%subCtrl.internalName = "MouseStart";
%subCtrl.superClass = "MouseBox";
%subCtrl.dropTarget = %dropTarget;
%subCtrl.pluginName = %pluginName;
%subCtrl.toolbarName = %toolbarName;
%subCtrl.iconStack = %stack;
}
}
continue;
}
if (%ctrl.isMemberOfClass("GuiIconButtonCtrl")) {
%ctrl.superClass = "ToolbarIcon";
%ctrl.useMouseEvents = true;
//%ctrl.toolbar = %gui;
if (isObject(%pluginObj)) {
%pluginObj.iconList = strAddWord(%pluginObj.iconList,%ctrl.getId());
}
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::getStackEndGui(%this,%gui,%isSubStack) {
if (%isSubStack) {
%end = %gui-->StackEnd;
delObj(%end);
%end = %gui-->SubStackEnd;
delObj(%end);
if (!isObject(%end)) {
%end = new GuiContainer() {
extent = "18 32";
profile = "ToolsBoxDarkC";
isContainer = "1";
internalName = "SubStackEnd";
superClass = "SubStackEnd";
new GuiBitmapCtrl() {
bitmap = "tlab/art/icons/toolbar/DropLeft.png";
wrap = "0";
position = "4 7";
extent = "12 16";
internalName = "SubStackEndImg";
superClass = "SubStackEndImg";
};
};
%gui.add(%end);
}
%end.setExtent(18,32);
hide(%end);
} else {
%end = %gui-->StackEnd;
delObj(%end);
if (!isObject(%end)) {
%end = new GuiContainer() {
extent = "27 32";
profile = "ToolsBoxDarkC";
isContainer = "1";
internalName = "StackEnd";
superClass = "StackEnd";
new GuiBitmapCtrl() {
bitmap = "tlab/art/icons/toolbar/DropLeft.png";
wrap = "0";
position = "6 5";
extent = "17 22";
internalName = "StackEndImg";
superClass = "StackEndImg";
};
};
%gui.add(%end);
}
%end.setExtent(27,32);
hide(%end);
}
%end.toolbarName = %gui.toolbarName;
}
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
//==============================================================================
function Lab::toggleToolbarGroupVisible(%this,%groupId,%itemId) {
%menu = Lab.currentEditor.toolbarMenu;
%checked = %menu.isItemChecked(%itemId);
toggleVisible(%groupId);
%groupId.visible = !%checked;
%menu.checkItem(%itemId,!%checked);
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::setToolbarDirty(%this,%toolbar) {
%toolbarName = %toolbar.toolbarName;
if (%toolbarName $= "") {
%toolbarName = %toolbar.pluginName;
if (%toolbarName $= "") {
warnlog("setToolbarDirty for invalid Toolbar:",%toolbar);
return;
}
}
Lab.toolbarDirtyList = strAddWord(Lab.toolbarDirtyList ,%toolbarName,true);
EGuiCustomizer-->saveToolbar.active = %isDirty;
Lab.toolbarIsDirty = %isDirty;
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::saveToolbar(%this,%icon,%disabled) {
//EGuiCustomizer-->saveToolbar.active = false;
//Lab.toolbarIsDirty = true;
Lab.storePluginsToolbarState();
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::storePluginsToolbarState(%this) {
if (Lab.toolbarDirtyList $= "" )
return;
foreach$(%toolbar in Lab.toolbarDirtyList) {
%gui = %toolbar@"Toolbar";
if (!isObject(%gui)) {
warnLog("Invalid toolbar listed for saving:",%gui);
continue;
}
%file = %gui.getFilename();
if (strFind(%file,"EditorGui.gui")) {
warnLog("EditorGui found in file name:",%file);
continue;
}
if (isFile( %file))
%gui.save(%file);
else
warnLog(%gui.getName()," saving skipped because file don't exist:",%file);
}
Lab.toolbarDirtyList = "";
//Lab.setToolbarDirty(false);
}
//------------------------------------------------------------------------------
//==============================================================================
// Show Popup Options
//==============================================================================
//==============================================================================
function Lab::rebuildAllToolbarPluginMenus(%this) {
foreach(%gui in LabToolbarGuiSet) {
%pluginObj = %gui.plugin@"Plugin";
delObj(%pluginObj.toolbarMenu);
}
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::ShowToolbarOptionMenu(%this) {
%plugObj = Lab.currentEditor;
if (!isObject(%plugObj.toolbarMenu)) {
%menu = new PopupMenu() {
superClass = "ContextMenu";
isPopup = true;
object = -1;
profile = $LabCfg_ContextMenuProfile;
};
%itemId = 0;
foreach$(%toolbarGroup in %plugObj.toolbarGroups) {
%line = "Toggle" SPC %toolbarGroup.internalName TAB "" TAB "Lab.toggleToolbarGroupVisible("@%toolbarGroup.getId()@","@%itemId@");";
%menu.addItem(%itemId,%line);
%menu.groupItem[%itemId] = %toolbarGroup.getId();
%menu.itemGroup[%toolbarGroup.getId()] = %itemId;
if (%toolbarGroup.isVisible())
%menu.checkItem(%itemId,true);
else
%menu.checkItem(%itemId,false);
%itemId++;
}
%plugObj.toolbarMenu = %menu;
}
%plugObj.toolbarMenu.showPopup(Canvas);
}
//------------------------------------------------------------------------------
//==============================================================================
function ToolbarArea::onRightMouseDown(%this,%modifier,%point,%clicks) {
devLog("ToolbarArea::onRightMouseDown(%this,%modifier,%point,%clicks) ",%this,%modifier,%point,%clicks);
Lab.ShowToolbarOptionMenu();
}
//------------------------------------------------------------------------------
//==============================================================================
function ToolbarBoxChild::onRightMouseDown(%this,%modifier,%point,%clicks) {
devLog("ToolbarBoxChild::onRightMouseDown(%this,%modifier,%point,%clicks) ",%this,%modifier,%point,%clicks);
Lab.ShowToolbarOptionMenu();
}
//------------------------------------------------------------------------------
//==============================================================================
function ToolbarIcon::onRightClick(%this,%modifier,%point,%clicks) {
devLog("ToolbarIcon::onRightClick(%this,%modifier,%point,%clicks) ",%this,%modifier,%point,%clicks);
Lab.ShowToolbarOptionMenu();
}
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
function Lab::resetAllDisabledIcons(%this) {
foreach(%gui in LabToolbarStack) {
%addToStack = "";
%break = false;
foreach(%ctrl in %gui) {
if(%break)
continue;
if (%ctrl.getClassName() $= "GuiStackControl") {
%addToStack = %ctrl;
%break = true;
}
//if(%break)
//break;
}
%disabledGroup = %gui-->DisabledIcons;
if (!isObject(%disabledGroup) || !isObject(%addToStack))
continue;
for(%i=%disabledGroup.getCount()-1; %i >=0; %i--) {
%ctrl = %disabledGroup.getObject(%i);
%ctrl.locked = 0;
%addToStack.add(%ctrl);
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Dragged control dropped in Toolbar Trash Bin
function Lab::getIconRootStack(%this, %ctrl) {
%test = %ctrl;
for(%i=0; %i<8; %i++) {
%parent = %test.parentGroup;
devLog("Test Parent Name = ",%parent.getName());
if (%parent.getName() $= "LabToolbarStack" ) {
%toolbar = %test;
%i = 99;
} else
%test = %parent;
}
if (isObject(%toolbar))
return %toolbar;
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::updateAllToolbarStacks(%this) {
foreach(%gui in LabToolbarStack) {
if (!%gui.isMemberOfClass("GuiStackControl"))
continue;
%this.updateToolbarStack(%gui,true);
}
}
//------------------------------------------------------------------------------
//==============================================================================
function Lab::updateToolbarStack(%this,%stack,%fixStructure) {
%stack.updateStack();
if(!%fixStructure)
return;
%DisabledGroup = %stack->DisabledIcons;
if (isObject(%DisabledGroup)) {
%stack.bringToFront(%DisabledGroup);
}
%StackEnd = %stack->StackEnd;
if (isObject(%StackEnd)) {
%stack.pushToBack(%StackEnd);
}
}
//------------------------------------------------------------------------------
| |
/* Copyright (c) 2006 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.
*/
/*
* Created by Morten Christensen, http://blog.sitereactor.dk | http://twitter.com/sitereactor
*/
using System;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Google.GData.WebmasterTools
{
#region Ananlytics specific constants
public class WebmasterToolsNameTable
{
/// <summary>
/// base uri for user based feeds
/// </summary>
public const string BaseUserUri = "https://www.google.com/webmasters/tools/feeds/";
// <summary>GData webmaster tools extension namespace</summary>
public const string gWebmasterToolsNamspace = "http://schemas.google.com/webmasters/tools/2007";
/// <summary>prefix for gWebmasterToolsNamspace if writing</summary>
public const string gWebmasterToolsPrefix = "wt";
public const string mWebmasterToolsPrefix = "mobile";
/// Sites feed
/// <summary>xmlelement for wt:crawl-rate</summary>
public const string XmlCrawlRateElement = "crawl-rate";
/// <summary>xmlelement for wt:geolocation</summary>
public const string XmlGeoLocationElement = "geolocation";
/// <summary>xmlelement for wt:preferred-domain</summary>
public const string XmlPreferredDomainElement = "preferred-domain";
/// <summary>xmlelement for wt:verification-method</summary>
public const string XmlVerificationMethodElement = "verification-method";
/// <summary>xml attribute type for wt:verification-method</summary>
public const string XmlAttributeType = "type";
/// <summary>xml attribute in-use for wt:verification-method</summary>
public const string XmlAttributeInUse = "in-use";
/// <summary>xmlelement for wt:verified</summary>
public const string XmlVerifiedElement = "verified";
/// <summary>xmlelement for wt:date</summary>
public const string XmlDateElement = "date";
/// Keywords feed
/// <summary>xmlelement for wt:keyword</summary>
public const string XmlKeywordElement = "keyword";
/// <summary>xml attribute source for wt:keyword</summary>
public const string XmlAttributeSource = "source";
/// Sitemaps feed
/// <summary>xmlelement for mobile:mobile</summary>
public const string XmlMobileElement = "mobile";
/// <summary>xmlelement for wt:sitemap-last-downloaded</summary>
public const string XmlSitemapLastDownloadedElement = "sitemap-last-downloaded";
/// <summary>xmlelement for wt:sitemap-mobile</summary>
public const string XmlSitemapMobileElement = "sitemap-mobile";
/// <summary>xmlelement for wt:sitemap-mobile-markup-language</summary>
public const string XmlSitemapMobileMarkupLanguageElement = "sitemap-mobile-markup-language";
/// <summary>xmlelement for wt:sitemap-news</summary>
public const string XmlSitemapNewsElement = "sitemap-news";
/// <summary>xmlelement for wt:sitemap-news-publication-label</summary>
public const string XmlSitemapNewsPublicationLabelElement = "sitemap-news-publication-label";
/// <summary>xmlelement for wt:sitemap-type</summary>
public const string XmlSitemapTypeElement = "sitemap-type";
/// <summary>xmlelement for wt:sitemap-url-count</summary>
public const string XmlSitemapUrlCountElement = "sitemap-url-count";
/// Messages feed
/// <summary>xmlelement for wt:body</summary>
public const string XmlBodyElement = "body";
/// wt:date already exists
/// <summary>xmlelement for wt:language</summary>
public const string XmlLanguageElement = "language";
/// <summary>xml attribute language for wt:language</summary>
public const string XmlAttributeLanguage = "language";
/// <summary>xmlelement for wt:read</summary>
public const string XmlReadElement = "read";
/// <summary>xmlelement for wt:subject</summary>
public const string XmlSubjectElement = "subject";
/// <summary>xml attribute subject for wt:subject</summary>
public const string XmlAttributeSubject = "subject";
/// Crawl Issues feed
/// <summary>xmlelement for wt:crawl-type</summary>
public const string XmlCrawlTypeElement = "crawl-type";
/// <summary>xmlelement for wt:issue-type</summary>
public const string XmlIssueTypeElement = "issue-type";
/// <summary>xmlelement for wt:issue-detail</summary>
public const string XmlIssueDetailElement = "issue-detail";
/// <summary>xmlelement for wt:linked-from</summary>
public const string XmlLinkedFromElement = "linked-from";
/// <summary>xmlelement for wt:date-detected</summary>
public const string XmlDateDetectedElement = "date-detected";
}
#endregion
/// <summary>
/// wt:crawl-rate schema extension describing a Webmaster Tools Crawl Rate
/// </summary>
public class CrawlRate : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public CrawlRate()
: base(WebmasterToolsNameTable.XmlCrawlRateElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public CrawlRate(string initValue)
: base(WebmasterToolsNameTable.XmlCrawlRateElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:geolocation schema extension describing a Webmaster Tools Geolocation
/// </summary>
public class GeoLocation : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public GeoLocation()
: base(WebmasterToolsNameTable.XmlGeoLocationElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public GeoLocation(string initValue)
: base(WebmasterToolsNameTable.XmlGeoLocationElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:perferred-domain schema extension describing a Webmaster Tools Perferred Domain
/// </summary>
public class PreferredDomain : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public PreferredDomain()
: base(WebmasterToolsNameTable.XmlPreferredDomainElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public PreferredDomain(string initValue)
: base(WebmasterToolsNameTable.XmlPreferredDomainElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:verification-method schema extension describing a Webmaster Tools Verification Method
/// </summary>
public class VerificationMethod : SimpleNameValueAttribute
{
/// <summary>
/// default constructor
/// </summary>
public VerificationMethod()
: base(WebmasterToolsNameTable.XmlVerificationMethodElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeType, null);
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeInUse, null);
}
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="type"></param>
/// <param name="inUse"></param>
public VerificationMethod(String type, String inUse)
: base(WebmasterToolsNameTable.XmlVerificationMethodElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeType, type);
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeInUse, inUse);
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the Type attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Type
{
get
{
return this.Attributes[WebmasterToolsNameTable.XmlAttributeType] as string;
}
set
{
this.Attributes[WebmasterToolsNameTable.XmlAttributeType] = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the In Use attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string InUse
{
get
{
return this.Attributes[WebmasterToolsNameTable.XmlAttributeInUse] as string;
}
set
{
this.Attributes[WebmasterToolsNameTable.XmlAttributeInUse] = value;
}
}
}
/// <summary>
/// wt:verified schema extension describing a Webmaster Tools Verified
/// </summary>
public class Verified : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public Verified()
: base(WebmasterToolsNameTable.XmlVerifiedElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public Verified(string initValue)
: base(WebmasterToolsNameTable.XmlVerifiedElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:date schema extension describing a Webmaster Tools Date
/// </summary>
public class Date : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public Date()
: base(WebmasterToolsNameTable.XmlDateElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public Date(string initValue)
: base(WebmasterToolsNameTable.XmlDateElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class Keyword : SimpleNameValueAttribute
{
/// <summary>
/// default constructor
/// </summary>
public Keyword()
: base(WebmasterToolsNameTable.XmlKeywordElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeSource, null);
}
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="value"></param>
public Keyword(String value)
: base(WebmasterToolsNameTable.XmlKeywordElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeSource, value);
}
}
public class Mobile : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public Mobile()
: base(WebmasterToolsNameTable.XmlMobileElement, WebmasterToolsNameTable.mWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public Mobile(string initValue)
: base(WebmasterToolsNameTable.XmlMobileElement, WebmasterToolsNameTable.mWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapLastDownloaded : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapLastDownloaded()
: base(WebmasterToolsNameTable.XmlSitemapLastDownloadedElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{}
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapLastDownloaded(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapLastDownloadedElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapMobile : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapMobile()
: base(WebmasterToolsNameTable.XmlSitemapMobileElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapMobile(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapMobileElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapMobileMarkupLanguage : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapMobileMarkupLanguage()
: base(WebmasterToolsNameTable.XmlSitemapMobileMarkupLanguageElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapMobileMarkupLanguage(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapMobileMarkupLanguageElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapNews : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapNews()
: base(WebmasterToolsNameTable.XmlSitemapNewsElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapNews(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapNewsElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapNewsPublicationLabel : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapNewsPublicationLabel()
: base(WebmasterToolsNameTable.XmlSitemapNewsPublicationLabelElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapNewsPublicationLabel(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapNewsPublicationLabelElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapType : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapType()
: base(WebmasterToolsNameTable.XmlSitemapTypeElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapType(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapTypeElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class SitemapUrlCount : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public SitemapUrlCount()
: base(WebmasterToolsNameTable.XmlSitemapUrlCountElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public SitemapUrlCount(string initValue)
: base(WebmasterToolsNameTable.XmlSitemapUrlCountElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class Body : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public Body()
: base(WebmasterToolsNameTable.XmlBodyElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public Body(string initValue)
: base(WebmasterToolsNameTable.XmlBodyElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class Language : SimpleNameValueAttribute
{
/// <summary>
/// default constructor
/// </summary>
public Language()
: base(WebmasterToolsNameTable.XmlVerificationMethodElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeLanguage, null);
}
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="value"></param>
public Language(String value)
: base(WebmasterToolsNameTable.XmlAttributeLanguage, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlAttributeLanguage, value);
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the Language attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string LanguageAttribute
{
get
{
return this.Attributes[WebmasterToolsNameTable.XmlAttributeLanguage] as string;
}
set
{
this.Attributes[WebmasterToolsNameTable.XmlAttributeLanguage] = value;
}
}
}
public class Read : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public Read()
: base(WebmasterToolsNameTable.XmlReadElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public Read(string initValue)
: base(WebmasterToolsNameTable.XmlReadElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
public class Subject : SimpleNameValueAttribute
{
/// <summary>
/// default constructor
/// </summary>
public Subject()
: base(WebmasterToolsNameTable.XmlSubjectElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlSubjectElement, null);
}
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="value"></param>
public Subject(String value)
: base(WebmasterToolsNameTable.XmlSubjectElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{
this.Attributes.Add(WebmasterToolsNameTable.XmlSubjectElement, value);
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the Subject attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string SubjectAttribute
{
get
{
return this.Attributes[WebmasterToolsNameTable.XmlSubjectElement] as string;
}
set
{
this.Attributes[WebmasterToolsNameTable.XmlSubjectElement] = value;
}
}
}
/// <summary>
/// wt:crawl-type schema extension describing a Webmaster Tools Crawl Type
/// </summary>
public class CrawlType : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public CrawlType()
: base(WebmasterToolsNameTable.XmlCrawlTypeElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public CrawlType(string initValue)
: base(WebmasterToolsNameTable.XmlCrawlTypeElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:issue-type schema extension describing a Webmaster Tools Issue Type
/// </summary>
public class IssueType : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public IssueType()
: base(WebmasterToolsNameTable.XmlIssueTypeElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public IssueType(string initValue)
: base(WebmasterToolsNameTable.XmlIssueTypeElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:issue-detail schema extension describing a Webmaster Tools Issue Detail
/// </summary>
public class IssueDetail : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public IssueDetail()
: base(WebmasterToolsNameTable.XmlIssueDetailElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public IssueDetail(string initValue)
: base(WebmasterToolsNameTable.XmlIssueDetailElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:linked-from schema extension describing a Webmaster Tools Linked From
/// </summary>
public class LinkedFrom : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public LinkedFrom()
: base(WebmasterToolsNameTable.XmlLinkedFromElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public LinkedFrom(string initValue)
: base(WebmasterToolsNameTable.XmlLinkedFromElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
/// <summary>
/// wt:date-detected schema extension describing a Webmaster Tools Date Detected
/// </summary>
public class DateDetected : SimpleElement
{
/// <summary>
/// default constructor
/// </summary>
public DateDetected()
: base(WebmasterToolsNameTable.XmlDateDetectedElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace)
{ }
/// <summary>
/// constructor taking the initial value
/// </summary>
/// <param name="initValue"></param>
public DateDetected(string initValue)
: base(WebmasterToolsNameTable.XmlDateDetectedElement, WebmasterToolsNameTable.gWebmasterToolsPrefix, WebmasterToolsNameTable.gWebmasterToolsNamspace, initValue)
{ }
}
}
| |
using System;
using System.Linq;
using PlayMe.Common.Model;
using PlayMe.Plumbing.Diagnostics;
using PlayMe.Server.Player;
using PlayMe.Server.Providers.SpotifyProvider.Mappers;
using SpotiFire.SpotifyLib;
using Album = PlayMe.Common.Model.Album;
using Artist = PlayMe.Common.Model.Artist;
using Track = PlayMe.Common.Model.Track;
namespace PlayMe.Server.Providers.SpotifyProvider
{
public sealed class SpotifyMusicProvider : IMusicProvider, IDisposable
{
private readonly ISession session;
private readonly ILogger logger;
private readonly IBufferedPlayer player;
private readonly ITrackMapper trackMapper;
private readonly IAlbumMapper albumMapper;
private readonly ISpotifySettings spotifySettings;
public SpotifyMusicProvider(ILogger logger,IBufferedPlayer player, ITrackMapper trackMapper, IAlbumMapper albumMapper, ISpotifySettings spotifySettings)
{
this.spotifySettings = spotifySettings;
this.albumMapper = albumMapper;
this.trackMapper = trackMapper;
this.logger = logger;
this.player = player;
logger.Debug("Creating Spotify session");
session = Spotify.CreateSession(spotifySettings.ApplicationKey, "c:\\temp", "c:\\temp", "Spotifire");
//session.VolumeNormalization = true;
session.MusicDeliver += session_MusicDelivered;
session.EndOfTrack += session_EndOfTrack;
session.ConnectionError += session_ConnectionError;
Login();
}
#region Spotify session events
void session_ConnectionError(ISession sender, SessionEventArgs e)
{
if (e == null) throw new ArgumentNullException("e");
logger.Error("session_connectionError {0}", e.Message);
Login();
}
void session_EndOfTrack(ISession sender, SessionEventArgs e)
{
if (TrackEnded != null)
{
TrackEnded(this, new EventArgs());
}
}
void session_MusicDelivered(ISession sender, MusicDeliveryEventArgs e)
{
e.ConsumedFrames = e.Samples.Length > 0 ? player.EnqueueSamples(e.Channels, e.Rate, e.Samples, e.Frames) : 0;
}
#endregion
public event EventHandler TrackEnded;
public Track GetTrack(string link, string user)
{
var track = GetSpotifireTrack(link);
return trackMapper.Map(track, this, user, true, true);
}
private ITrack GetSpotifireTrack(string link)
{
const string prefix = "spotify:track:";
using (var l = session.ParseLink(prefix + link))
{
var track = l.As<ITrack>();
var trackTask = track.Load();
trackTask.Wait();
return track;
}
}
private void Login()
{
if (session.ConnectionState == sp_connectionstate.LOGGED_IN || session.ConnectionState == sp_connectionstate.OFFLINE) return;
logger.Debug("Logging into Spotify with username '{0}'", spotifySettings.UserName);
session.Login(spotifySettings.UserName, spotifySettings.Password, false);
var result = session.WaitForLoginComplete();
if (result != sp_error.OK) logger.Error("Spotify Login failed");
}
#region Browse and Search
public SearchResults SearchAll(string searchTerm, string user)
{
Login();
using (var search = session.Search(searchTerm, 0, 30, 0, 15, 0, 15, 0, 0, sp_search_type.STANDARD))
{
search.WaitForCompletion();
if (!search.IsComplete)
{
logger.Error("Search for {0} timed out", searchTerm);
return null;
}
var results = new SearchResults();
//set up artists
var pagedArtists = new ArtistPagedList
{
Total = search.TotalArtists,
Artists = search.Artists.Select(a => new ArtistMapper().Map(a, this)).ToArray()
};
//set up albums
var pagedAlbums = new AlbumPagedList
{
Total = search.TotalAlbums,
Albums = search.Albums.Where(a => a.IsAvailable)
.Select(a => albumMapper.Map(a, this, true))
.ToArray()
};
////set up tracks
var pagedTracks = new TrackPagedList
{
Total = search.TotalTracks,
Tracks = search.Tracks
.Select(t => trackMapper.Map(t, this, user, true, true))
.Where(t => t.IsAvailable)
.ToArray()
};
results.PagedArtists = pagedArtists;
results.PagedAlbums = pagedAlbums;
results.PagedTracks = pagedTracks;
return results;
}
}
public Artist BrowseArtist(string link, bool mapTracks)
{
Login();
logger.Debug("Artist Browse started for link {0}",link);
const string prefix = "spotify:artist:";
var browseTypeEnum = mapTracks ? sp_artistbrowse_type.FULL : sp_artistbrowse_type.NO_TRACKS;
using (var artist = session.ParseLink(prefix + link).As<IArtist>())
using (var browse = artist.Browse(browseTypeEnum))
{
browse.WaitForCompletion();
if (!browse.IsComplete) logger.Error("Artist Browse timed out");
var albums = browse.Albums
.Where(a => a.IsAvailable)
.Select(a => albumMapper.Map(a, this))
.ToArray();
var artistResult = new ArtistMapper().Map(artist, this);
artistResult.Profile = new ArtistProfile
{
Biography = browse.Biography,
SimilarArtists = browse.SimilarArtists
.Select(a => new ArtistMapper().Map(a, this))
.ToArray()
};
artistResult.Albums = albums;
logger.Debug("Artist Browse completed for link {0}", link);
return artistResult;
}
}
public Album BrowseAlbum(string link, string user)
{
Login();
logger.Debug("Album Browse started for link {0}", link);
const string prefix = "spotify:album:";
using (var album = session.ParseLink(prefix + link).As<IAlbum>())
{
using (var browse = album.Browse())
{
browse.WaitForCompletion();
if (!browse.IsComplete)
{
logger.Error("Album Browse timed out");
return null;
}
var albumResult = albumMapper.Map(album, this, true);
var tracks = browse.Tracks
.Select(t => trackMapper.Map(t, this, user, false, true))
.Where(t => t.IsAvailable)
.ToArray();
albumResult.Tracks = tracks;
logger.Debug("Album Browse completed for link {0}", link);
return albumResult;
}
}
}
#endregion
public void Dispose()
{
session.Dispose();
}
public void PlayTrack(Track track)
{
var spotifireTrack = GetSpotifireTrack(track.Link);
session.PlayerLoad(spotifireTrack);
session.PlayerPlay();
}
public void EndTrack()
{
player.Resume();
player.Reset();
session.PlayerUnload();
}
public bool IsEnabled { get { return spotifySettings.IsEnabled; } }
public IPlayer Player
{
get { return player; }
}
public MusicProviderDescriptor Descriptor
{
get
{
return new MusicProviderDescriptor
{
Identifier = "sp",
Name = "Spotify"
};
}
}
public Uri ExternalLinkBaseUrl
{
get { return new Uri("http://open.spotify.com/"); }
}
public int Priority
{
get { return 0; }
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public class MegaPolyShape
{
public List<Vector3> points = new List<Vector3>();
public List<float> length = new List<float>();
}
// TODO: Twist
// TODO: offset over height
// shape to line or tube
// add mat ids to splines
[ExecuteInEditMode]
[AddComponentMenu("MegaShapes/Lathe")]
[RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))]
public class MegaShapeLathe : MonoBehaviour
{
public MegaShape shape;
public int curve;
public float degrees = 360.0f;
public float startang = 0.0f;
public int segments = 8;
public MegaAxis direction = MegaAxis.X;
public Vector3 axis;
//public int align;
public bool genuvs = true;
public int steps = 8;
public bool update = true;
public bool flip = false;
public bool doublesided = false;
//public bool captop = false;
//public bool capbase = false;
public bool buildTangents = false;
public float twist = 0.0f;
public AnimationCurve twistcrv = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1));
public bool useprofilecurve = false;
public float profileamt = 1.0f;
public AnimationCurve profilecrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public float globalscale = 1.0f;
public Vector3 scale = Vector3.one;
public bool usescalecrv = false;
public AnimationCurve scalexcrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public AnimationCurve scaleycrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public AnimationCurve scalezcrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public AnimationCurve scaleamthgt = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1));
//public bool PhysUV = false;
public Vector2 uvoffset = Vector2.zero;
public Vector2 uvscale = Vector2.one;
public float uvrotate;
public bool pivotbase = false;
// No inspector
public Mesh mesh;
public Vector3 limits = Vector3.zero;
public Vector3 min = Vector3.zero;
public Vector3 max = Vector3.zero;
public MegaPolyShape pshape = null;
public Vector3 pivot = Vector3.zero;
// Need to allow multiple curves.
List<Vector3> verts = new List<Vector3>();
List<Vector2> uvs = new List<Vector2>();
List<int> tris = new List<int>();
List<int> dtris = new List<int>();
List<Vector3> normals = new List<Vector3>();
void LateUpdate()
{
if ( mesh == null )
{
mesh = new Mesh();
mesh.name = "Lathe";
MeshFilter mf = GetComponent<MeshFilter>();
mf.sharedMesh = mesh;
}
if ( update )
BuildMesh(mesh);
}
// If handles are not equal at a knot then make it sharp by adding extra vertex
MegaPolyShape MakePolyShape(MegaShape shape, int steps)
{
if ( pshape == null )
pshape = new MegaPolyShape();
// build interpolated data
pshape.length.Clear();
pshape.points.Clear();
int first = 0;
float length = 0.0f;
Vector3 lp = shape.splines[curve].knots[0].p + axis;
Vector3 p = Vector3.zero;
min = lp;
max = lp;
pivot = Vector3.zero;
//pshape.length.Add(0.0f);
bool closed = shape.splines[curve].closed;
int kcount = shape.splines[curve].knots.Count - 1;
if ( closed )
kcount++;
int k1 = 0;
int k2 = 0;
//for ( int i = 0; i < shape.splines[curve].knots.Count - 1; i++ )
for ( int i = 0; i < kcount; i++ )
{
k1 = i;
k2 = i + 1;
if ( k2 >= shape.splines[curve].knots.Count )
k2 = 0;
for ( int j = first; j < steps; j++ )
{
float alpha = (float)j / (float)steps;
p = shape.splines[curve].knots[k1].InterpolateCS(alpha, shape.splines[curve].knots[k2]); //] .Interpolate(i, alpha, true);
p += axis;
pshape.points.Add(p);
//pshape.flags.Add(0); // All smooth for now
length += Vector3.Distance(p, lp);
pshape.length.Add(length);
if ( p.x < min.x )
min.x = p.x;
if ( p.y < min.y )
min.y = p.y;
if ( p.z < min.z )
min.z = p.z;
if ( p.x > max.x )
max.x = p.x;
if ( p.y > max.y )
max.y = p.y;
if ( p.z > max.z )
max.z = p.z;
lp = p;
}
// if smooth then first = 1 so we dont repeat, or use mesh builder and smth grps
first = 0; //1;
}
p = shape.splines[curve].knots[k2].p;
p += axis;
pshape.points.Add(p);
length += Vector3.Distance(p, lp);
pshape.length.Add(length);
//pshape.flags.Add(0); // All smooth for now
//length += Vector3.Distance(p, lp);
limits = max - min;
if ( pivotbase )
{
pivot.z = max.z;
max.z -= min.z;
min.z = 0.0f;
}
if ( useprofilecurve )
{
float halpha = 0.0f;
for ( int v = 0; v < pshape.points.Count; v++ )
{
Vector3 lsp = pshape.points[v]; //Vector3.Scale(pshape.points[v], scl);
lsp.z -= pivot.z; //max.z;
if ( !pivotbase )
halpha = 1.0f - ((lsp.z - min.z) / limits.z);
else
halpha = -((lsp.z - min.z) / limits.z);
lsp.x += profilecrv.Evaluate(halpha) * profileamt;
//lsp.z -= min.z;
if ( lsp.x > max.x )
max.x = lsp.x;
if ( lsp.x < min.x )
min.x = lsp.x;
pshape.points[v] = lsp;
}
}
else
{
for ( int v = 0; v < pshape.points.Count; v++ )
{
Vector3 lsp = pshape.points[v]; //Vector3.Scale(pshape.points[v], scl);
lsp.z -= pivot.z; //max.z;
//lsp.z -= min.z;
pshape.points[v] = lsp;
}
}
Collider col = GetComponent<Collider>();
//if ( collider != null && collider.GetType() == typeof(BoxCollider) )
if ( col != null && col is BoxCollider )
{
BoxCollider box = (BoxCollider)col;
Vector3 extent = Vector3.zero;
Vector3 center = Vector3.zero;
if ( pivotbase )
center.z = (-(max.z - min.z) * 0.5f); // - pivot.z;
box.center = center;
extent.x = Mathf.Abs(min.x);
extent.y = extent.x;
extent.z = (max.z - min.z) * 0.5f;
box.size = extent;
}
return pshape;
}
public void BuildMesh(Mesh mesh)
{
if ( shape == null )
return;
verts.Clear();
uvs.Clear();
tris.Clear();
dtris.Clear();
normals.Clear();
pshape = MakePolyShape(shape, steps);
Matrix4x4 axismat = Matrix4x4.identity;
Quaternion q = Quaternion.identity;
switch ( direction )
{
case MegaAxis.X: q = Quaternion.Euler(90.0f, 0.0f, 0.0f); break;
case MegaAxis.Y: q = Quaternion.Euler(0.0f, 90.0f, 0.0f); break;
case MegaAxis.Z: q = Quaternion.Euler(0.0f, 0.0f, 90.0f); break;
}
int vertLevels = segments + 1;
axismat.SetTRS(axis, q, Vector3.one);
Matrix4x4 iaxis = axismat.inverse;
Matrix4x4 rotmat = Matrix4x4.identity;
float totlen = pshape.length[pshape.length.Count - 1];
Vector2 uv = Vector2.zero;
Vector2 uv1 = uv;
Matrix4x4 uvmat = Matrix4x4.identity;
uvmat.SetTRS(Vector3.zero, Quaternion.Euler(0.0f, 0.0f, uvrotate), Vector3.one);
Vector3 p = Vector3.zero;
Vector3 scl = scale;
Vector3 norm = Vector3.zero;
Vector3 lsp = Vector3.zero;
int vindex = 0;
float alphasub = 0.0f;
if ( !pivotbase )
{
alphasub = 1.0f;
}
for ( int level = 0; level < vertLevels; level++ )
{
uv.y = (float)level / (float)segments;
float ang = (uv.y * degrees) + startang; //360.0f;
rotmat = Matrix4x4.identity;
MegaMatrix.RotateZ(ref rotmat, ang * Mathf.Deg2Rad);
Matrix4x4 tm = iaxis * rotmat * axismat;
Vector3 lp = Vector3.zero;
float cumlen = 0.0f;
int nix = normals.Count;
//Debug.Log("minz " + min.z + " limz " + limits.z);
for ( int v = 0; v < pshape.points.Count; v++ )
{
lsp = pshape.points[v]; //Vector3.Scale(pshape.points[v], scl);
//float halpha = 1.0f - ((lsp.z - min.z) / limits.z);
float halpha = alphasub - ((lsp.z - min.z) / limits.z);
//lsp.x += profilecrv.Evaluate(halpha);
//lsp.y += offsetycrv.Evaluate(halpha);
if ( usescalecrv )
{
//float halpha = (lsp.z - min.z) / limits.z;
float adj = scaleamthgt.Evaluate(halpha) * globalscale;
scl.x = 1.0f + (scalexcrv.Evaluate(uv.y) * adj);
scl.y = 1.0f + (scaleycrv.Evaluate(uv.y) * adj);
scl.z = 1.0f + (scalezcrv.Evaluate(uv.y) * adj);
}
lsp.x *= scl.x;
lsp.y *= scl.y;
lsp.z *= scl.z;
if ( twist != 0.0f )
{
float tang = ((twist * halpha * twistcrv.Evaluate(halpha)) + ang) * Mathf.Deg2Rad;
float c = Mathf.Cos(tang);
float s = Mathf.Sin(tang);
rotmat[0, 0] = c;
rotmat[0, 1] = s;
rotmat[1, 0] = -s;
rotmat[1, 1] = c;
tm = iaxis * rotmat * axismat;
}
#if false
norm.x = -(lsp.y - lp.y);
norm.y = lsp.x - lp.x;
norm.z = 0.0f; //lsp.z - lp.z;
#endif
norm.x = -(lsp.z - lp.z); //- (lsp.y - lp.y);
norm.y = 0.0f; //lsp.x - lp.x;
norm.z = lsp.x - lp.x; //0.0f; //lsp.z - lp.z;
lp = lsp;
p = tm * lsp; //Vector3.Scale(lsp, scl);
//p.x += offsetxcrv.Evaluate(halpha);
//p.y += offsetycrv.Evaluate(halpha);
verts.Add(p);
if ( v == 0 )
{
}
else
{
if ( v == 1 )
{
if ( flip )
normals.Add(tm.MultiplyVector(norm).normalized);
else
normals.Add(-tm.MultiplyVector(norm).normalized);
}
if ( flip )
normals.Add(tm.MultiplyVector(norm).normalized);
else
normals.Add(-tm.MultiplyVector(norm).normalized);
}
cumlen = pshape.length[v];
uv.x = cumlen / totlen; // / cumlen;
uv1 = uv;
uv1.x *= uvscale.x;
uv1.y *= uvscale.y;
uv1 += uvoffset;
uv1 = uvmat.MultiplyPoint(uv1);
uvs.Add(uv1);
}
if ( shape.splines[curve].closed )
{
normals[normals.Count - 1] = normals[nix];
}
}
// Faces
int vcount = pshape.points.Count;
for ( int level = 0; level < vertLevels - 1; level++ )
{
int voff = level * vcount;
for ( int p1 = 0; p1 < pshape.points.Count - 1; p1++ )
{
int v1 = p1 + voff;
int v2 = v1 + 1;
int v3 = level == vertLevels - 1 ? p1 : v1 + vcount;
int v4 = v3 + 1;
if ( flip )
{
tris.Add(v1);
tris.Add(v4);
tris.Add(v2);
tris.Add(v1);
tris.Add(v3);
tris.Add(v4);
}
else
{
tris.Add(v2);
tris.Add(v4);
tris.Add(v1);
tris.Add(v4);
tris.Add(v3);
tris.Add(v1);
}
}
}
if ( doublesided )
{
int vc = verts.Count;
for ( int i = 0; i < vc; i++ )
{
verts.Add(verts[i]);
uvs.Add(uvs[i]);
normals.Add(-normals[i]);
vindex++;
}
for ( int i = 0; i < tris.Count; i += 3 )
{
int v1 = tris[i];
int v2 = tris[i + 1];
int v3 = tris[i + 2];
dtris.Add(v3 + vc);
dtris.Add(v2 + vc);
dtris.Add(v1 + vc);
}
}
//MeshFilter mf = GetComponent<MeshFilter>();
//mesh = mf.sharedMesh;
//if ( mesh == null )
//{
// mesh = new Mesh();
// mesh.name = "Lathe";
// mf.sharedMesh = mesh;
//}
mesh.vertices = verts.ToArray();
mesh.uv = uvs.ToArray();
if ( doublesided )
mesh.subMeshCount = 2;
else
mesh.subMeshCount = 1;
mesh.SetTriangles(tris.ToArray(), 0);
if ( doublesided )
mesh.SetTriangles(dtris.ToArray(), 1);
mesh.RecalculateBounds();
mesh.normals = normals.ToArray();
if ( buildTangents )
{
MegaUtils.BuildTangents(mesh);
}
}
// TODO: Shell thickness
// General function
// TODO: UV scaling
// TODO: vert scaling
// TODO: support mutliple curves
// TODO: matids per curve and per knot
}
// 428
// 367
#if false
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public class MegaPolyShape
{
public List<Vector3> points = new List<Vector3>();
//public List<Vector3> normals = new List<Vector3>();
public List<float> length = new List<float>();
//public List<int> flags = new List<int>();
}
// shape to line or tube
// add mat ids to splines
// Most of the code here can be used for Extrude
[ExecuteInEditMode]
[AddComponentMenu("MegaShapes/Lathe")]
[RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))]
public class MegaShapeLathe : MonoBehaviour
{
public MegaShape shape;
public int curve;
public float degrees = 360.0f;
public float startang = 0.0f;
public int segments = 8;
public MegaAxis direction = MegaAxis.X;
public Vector3 axis;
public int align;
public bool genuvs = true;
public int steps = 8;
public bool update = true;
public bool flip = false;
public bool doublesided = false;
public bool captop = false;
public bool capbase = false;
public bool buildTangents = false;
public Vector3 scale = Vector3.one;
public bool usescalecrv = false;
public AnimationCurve scalexcrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public AnimationCurve scaleycrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public AnimationCurve scalezcrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public AnimationCurve scaleamthgt = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public bool PhysUV = false;
public Vector2 uvoffset = Vector2.zero;
public Vector2 uvscale = Vector2.one;
public float uvrotate;
public Mesh mesh;
void LateUpdate()
{
if ( mesh == null )
{
mesh = new Mesh();
mesh.name = "Lathe";
MeshFilter mf = GetComponent<MeshFilter>();
mf.sharedMesh = mesh;
}
if ( update )
BuildMesh(mesh);
}
Vector3 limits = Vector3.zero;
Vector3 min = Vector3.zero;
Vector3 max = Vector3.zero;
MegaPolyShape pshape = null;
// If handles are not equal at a knot then make it sharp by adding extra vertex
MegaPolyShape MakePolyShape(MegaShape shape, int steps)
{
if ( pshape == null )
pshape = new MegaPolyShape();
// build interpolated data
pshape.length.Clear();
pshape.points.Clear();
int first = 0;
float length = 0.0f;
Vector3 lp = shape.splines[0].knots[0].p + axis;
Vector3 p = Vector3.zero;
min = lp;
max = lp;
//pshape.length.Add(0.0f);
for ( int i = 0; i < shape.splines[0].knots.Count - 1; i++ )
{
for ( int j = first; j < steps; j++ )
{
float alpha = (float)j / (float)steps;
p = shape.splines[0].knots[i].InterpolateCS(alpha, shape.splines[0].knots[i + 1]); //] .Interpolate(i, alpha, true);
p += axis;
pshape.points.Add(p);
//pshape.flags.Add(0); // All smooth for now
length += Vector3.Distance(p, lp);
pshape.length.Add(length);
if ( p.x < min.x )
min.x = p.x;
if ( p.y < min.y )
min.y = p.y;
if ( p.z < min.z )
min.z = p.z;
if ( p.x > max.x )
max.x = p.x;
if ( p.y > max.y )
max.y = p.y;
if ( p.z > max.z )
max.z = p.z;
lp = p;
}
// if smooth then first = 1 so we dont repeat, or use mesh builder and smth grps
first = 0; //1;
}
p = shape.splines[0].knots[shape.splines[0].knots.Count - 1].p;
p += axis;
pshape.points.Add(p);
length += Vector3.Distance(p, lp);
pshape.length.Add(length);
//pshape.flags.Add(0); // All smooth for now
//length += Vector3.Distance(p, lp);
limits = max - min;
return pshape;
}
// Need to allow multiple curves.
List<Vector3> verts = new List<Vector3>();
List<Vector2> uvs = new List<Vector2>();
List<int> tris = new List<int>();
List<int> dtris = new List<int>();
List<Vector3> normals = new List<Vector3>();
public void BuildMesh(Mesh mesh)
{
if ( shape == null )
return;
verts.Clear();
uvs.Clear();
tris.Clear();
dtris.Clear();
normals.Clear();
pshape = MakePolyShape(shape, steps);
Matrix4x4 axismat = Matrix4x4.identity;
Quaternion q = Quaternion.identity;
switch ( direction )
{
case MegaAxis.X: q = Quaternion.Euler(90.0f, 0.0f, 0.0f); break;
case MegaAxis.Y: q = Quaternion.Euler(0.0f, 90.0f, 0.0f); break;
case MegaAxis.Z: q = Quaternion.Euler(0.0f, 0.0f, 90.0f); break;
}
int vertLevels = segments + 1;
axismat.SetTRS(axis, q, Vector3.one);
Matrix4x4 iaxis = axismat.inverse;
Matrix4x4 rotmat = Matrix4x4.identity;
float totlen = pshape.length[pshape.length.Count - 1];
Vector2 uv = Vector2.zero;
Vector2 uv1 = uv;
Matrix4x4 uvmat = Matrix4x4.identity;
uvmat.SetTRS(Vector3.zero, Quaternion.Euler(0.0f, 0.0f, uvrotate), Vector3.one);
Vector3 p = Vector3.zero;
Vector3 scl = scale;
Vector3 norm = Vector3.zero;
Vector3 lsp = Vector3.zero;
int vindex = 0;
for ( int level = 0; level < vertLevels; level++ )
{
uv.y = (float)level / (float)segments;
float ang = (uv.y * degrees) + startang; //360.0f;
rotmat = Matrix4x4.identity;
MegaMatrix.RotateZ(ref rotmat, ang * Mathf.Deg2Rad);
Matrix4x4 tm = iaxis * rotmat * axismat;
Vector3 lp = Vector3.zero;
float cumlen = 0.0f;
for ( int v = 0; v < pshape.points.Count; v++ )
{
lsp = pshape.points[v]; //Vector3.Scale(pshape.points[v], scl);
if ( usescalecrv )
{
float halpha = (lsp.z - min.z) / limits.z;
float adj = scaleamthgt.Evaluate(halpha);
scl.x = 1.0f + (scalexcrv.Evaluate(uv.y) * adj);
scl.y = 1.0f + (scaleycrv.Evaluate(uv.y) * adj);
scl.z = 1.0f + (scalezcrv.Evaluate(uv.y) * adj);
}
lsp.x *= scl.x;
lsp.y *= scl.y;
lsp.z *= scl.z;
#if false
norm.x = -(lsp.y - lp.y);
norm.y = lsp.x - lp.x;
norm.z = 0.0f; //lsp.z - lp.z;
#endif
norm.x = -(lsp.z - lp.z); //- (lsp.y - lp.y);
norm.y = 0.0f; //lsp.x - lp.x;
norm.z = lsp.x - lp.x; //0.0f; //lsp.z - lp.z;
lp = lsp;
p = tm * lsp; //Vector3.Scale(lsp, scl);
verts.Add(p);
if ( v == 0 )
{
}
else
{
if ( v == 1 )
{
normals.Add(-tm.MultiplyVector(norm).normalized);
}
normals.Add(-tm.MultiplyVector(norm).normalized);
}
cumlen = pshape.length[v];
uv.x = cumlen / totlen; // / cumlen;
uv1 = uv;
uv1.x *= uvscale.x;
uv1.y *= uvscale.y;
uv1 += uvoffset;
uv1 = uvmat.MultiplyPoint(uv1);
uvs.Add(uv1);
}
}
// Faces
int vcount = pshape.points.Count;
for ( int level = 0; level < vertLevels - 1; level++ )
{
int voff = level * vcount;
for ( int p1 = 0; p1 < pshape.points.Count - 1; p1++ )
{
int v1 = p1 + voff;
int v2 = v1 + 1;
int v3 = level == vertLevels - 1 ? p1 : v1 + vcount;
int v4 = v3 + 1;
if ( flip )
{
tris.Add(v1);
tris.Add(v4);
tris.Add(v2);
tris.Add(v1);
tris.Add(v3);
tris.Add(v4);
}
else
{
tris.Add(v2);
tris.Add(v4);
tris.Add(v1);
tris.Add(v4);
tris.Add(v3);
tris.Add(v1);
}
}
}
if ( doublesided )
{
int vc = verts.Count;
for ( int i = 0; i < vc; i++ )
{
verts.Add(verts[i]);
uvs.Add(uvs[i]);
normals.Add(-normals[i]);
vindex++;
}
for ( int i = 0; i < tris.Count; i += 3 )
{
int v1 = tris[i];
int v2 = tris[i + 1];
int v3 = tris[i + 2];
dtris.Add(v3 + vc);
dtris.Add(v2 + vc);
dtris.Add(v1 + vc);
}
}
mesh.vertices = verts.ToArray();
mesh.uv = uvs.ToArray();
if ( doublesided )
mesh.subMeshCount = 2;
else
mesh.subMeshCount = 1;
mesh.SetTriangles(tris.ToArray(), 0);
if ( doublesided )
mesh.SetTriangles(dtris.ToArray(), 1);
mesh.RecalculateBounds();
mesh.normals = normals.ToArray();
if ( buildTangents )
{
MegaUtils.BuildTangents(mesh);
}
}
// TODO: Shell thickness
// General function
// TODO: UV scaling
// TODO: vert scaling
// TODO: support mutliple curves
// TODO: matids per curve and per knot
}
// 428
// 367
#endif
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Globalization;
using System.Text;
namespace ZXing.PDF417.Internal
{
/// <summary>
///
/// </summary>
/// <author>Guenther Grau</author>
public class DetectionResult
{
private const int ADJUST_ROW_NUMBER_SKIP = 2;
public BarcodeMetadata Metadata { get; private set; }
public DetectionResultColumn[] DetectionResultColumns { get; set; }
public BoundingBox Box { get; internal set; }
public int ColumnCount { get; private set; }
public int RowCount
{
get { return Metadata.RowCount; }
}
public int ErrorCorrectionLevel
{
get { return Metadata.ErrorCorrectionLevel; }
}
public DetectionResult(BarcodeMetadata metadata, BoundingBox box)
{
Metadata = metadata;
Box = box;
ColumnCount = metadata.ColumnCount;
DetectionResultColumns = new DetectionResultColumn[ColumnCount + 2];
}
/// <summary>
/// Returns the DetectionResult Columns. This does a fair bit of calculation, so call it sparingly.
/// </summary>
/// <returns>The detection result columns.</returns>
public DetectionResultColumn[] getDetectionResultColumns()
{
adjustIndicatorColumnRowNumbers(DetectionResultColumns[0]);
adjustIndicatorColumnRowNumbers(DetectionResultColumns[ColumnCount + 1]);
int unadjustedCodewordCount = PDF417Common.MAX_CODEWORDS_IN_BARCODE;
int previousUnadjustedCount;
do
{
previousUnadjustedCount = unadjustedCodewordCount;
unadjustedCodewordCount = adjustRowNumbers();
} while (unadjustedCodewordCount > 0 && unadjustedCodewordCount < previousUnadjustedCount);
return DetectionResultColumns;
}
/// <summary>
/// Adjusts the indicator column row numbers.
/// </summary>
/// <param name="detectionResultColumn">Detection result column.</param>
private void adjustIndicatorColumnRowNumbers(DetectionResultColumn detectionResultColumn)
{
if (detectionResultColumn != null)
{
((DetectionResultRowIndicatorColumn) detectionResultColumn)
.adjustCompleteIndicatorColumnRowNumbers(Metadata);
}
}
/// <summary>
/// return number of codewords which don't have a valid row number. Note that the count is not accurate as codewords .
/// will be counted several times. It just serves as an indicator to see when we can stop adjusting row numbers
/// </summary>
/// <returns>The row numbers.</returns>
private int adjustRowNumbers()
{
// TODO ensure that no detected codewords with unknown row number are left
// we should be able to estimate the row height and use it as a hint for the row number
// we should also fill the rows top to bottom and bottom to top
int unadjustedCount = adjustRowNumbersByRow();
if (unadjustedCount == 0)
{
return 0;
}
for (int barcodeColumn = 1; barcodeColumn < ColumnCount + 1; barcodeColumn++)
{
Codeword[] codewords = DetectionResultColumns[barcodeColumn].Codewords;
for (int codewordsRow = 0; codewordsRow < codewords.Length; codewordsRow++)
{
if (codewords[codewordsRow] == null)
{
continue;
}
if (!codewords[codewordsRow].HasValidRowNumber)
{
adjustRowNumbers(barcodeColumn, codewordsRow, codewords);
}
}
}
return unadjustedCount;
}
/// <summary>
/// Adjusts the row numbers by row.
/// </summary>
/// <returns>The row numbers by row.</returns>
private int adjustRowNumbersByRow()
{
adjustRowNumbersFromBothRI(); // RI = RowIndicators
// TODO we should only do full row adjustments if row numbers of left and right row indicator column match.
// Maybe it's even better to calculated the height (in codeword rows) and divide it by the number of barcode
// rows. This, together with the LRI and RRI row numbers should allow us to get a good estimate where a row
// number starts and ends.
int unadjustedCount = adjustRowNumbersFromLRI();
return unadjustedCount + adjustRowNumbersFromRRI();
}
/// <summary>
/// Adjusts the row numbers from both Row Indicators
/// </summary>
/// <returns> zero </returns>
private void adjustRowNumbersFromBothRI()
{
if (DetectionResultColumns[0] == null || DetectionResultColumns[ColumnCount + 1] == null)
{
return;
}
Codeword[] LRIcodewords = DetectionResultColumns[0].Codewords;
Codeword[] RRIcodewords = DetectionResultColumns[ColumnCount + 1].Codewords;
for (int codewordsRow = 0; codewordsRow < LRIcodewords.Length; codewordsRow++)
{
if (LRIcodewords[codewordsRow] != null &&
RRIcodewords[codewordsRow] != null &&
LRIcodewords[codewordsRow].RowNumber == RRIcodewords[codewordsRow].RowNumber)
{
for (int barcodeColumn = 1; barcodeColumn <= ColumnCount; barcodeColumn++)
{
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword == null)
{
continue;
}
codeword.RowNumber = LRIcodewords[codewordsRow].RowNumber;
if (!codeword.HasValidRowNumber)
{
// LOG.info("Removing codeword with invalid row number, cw[" + codewordsRow + "][" + barcodeColumn + "]");
DetectionResultColumns[barcodeColumn].Codewords[codewordsRow] = null;
}
}
}
}
}
/// <summary>
/// Adjusts the row numbers from Right Row Indicator.
/// </summary>
/// <returns>The unadjusted row count.</returns>
private int adjustRowNumbersFromRRI()
{
if (DetectionResultColumns[ColumnCount + 1] == null)
{
return 0;
}
int unadjustedCount = 0;
Codeword[] codewords = DetectionResultColumns[ColumnCount + 1].Codewords;
for (int codewordsRow = 0; codewordsRow < codewords.Length; codewordsRow++)
{
if (codewords[codewordsRow] == null)
{
continue;
}
int rowIndicatorRowNumber = codewords[codewordsRow].RowNumber;
int invalidRowCounts = 0;
for (int barcodeColumn = ColumnCount + 1; barcodeColumn > 0 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; barcodeColumn--)
{
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword != null)
{
invalidRowCounts = adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);
if (!codeword.HasValidRowNumber)
{
unadjustedCount++;
}
}
}
}
return unadjustedCount;
}
/// <summary>
/// Adjusts the row numbers from Left Row Indicator.
/// </summary>
/// <returns> Unadjusted row Count.</returns>
private int adjustRowNumbersFromLRI()
{
if (DetectionResultColumns[0] == null)
{
return 0;
}
int unadjustedCount = 0;
Codeword[] codewords = DetectionResultColumns[0].Codewords;
for (int codewordsRow = 0; codewordsRow < codewords.Length; codewordsRow++)
{
if (codewords[codewordsRow] == null)
{
continue;
}
int rowIndicatorRowNumber = codewords[codewordsRow].RowNumber;
int invalidRowCounts = 0;
for (int barcodeColumn = 1; barcodeColumn < ColumnCount + 1 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; barcodeColumn++)
{
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword != null)
{
invalidRowCounts = adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);
if (!codeword.HasValidRowNumber)
{
unadjustedCount++;
}
}
}
}
return unadjustedCount;
}
/// <summary>
/// Adjusts the row number if valid.
/// </summary>
/// <returns>The invalid rows</returns>
/// <param name="rowIndicatorRowNumber">Row indicator row number.</param>
/// <param name="invalidRowCounts">Invalid row counts.</param>
/// <param name="codeword">Codeword.</param>
private static int adjustRowNumberIfValid(int rowIndicatorRowNumber, int invalidRowCounts, Codeword codeword)
{
if (codeword == null)
{
return invalidRowCounts;
}
if (!codeword.HasValidRowNumber)
{
if (codeword.IsValidRowNumber(rowIndicatorRowNumber))
{
codeword.RowNumber = rowIndicatorRowNumber;
invalidRowCounts = 0;
}
else
{
++invalidRowCounts;
}
}
return invalidRowCounts;
}
/// <summary>
/// Adjusts the row numbers.
/// </summary>
/// <param name="barcodeColumn">Barcode column.</param>
/// <param name="codewordsRow">Codewords row.</param>
/// <param name="codewords">Codewords.</param>
private void adjustRowNumbers(int barcodeColumn, int codewordsRow, Codeword[] codewords)
{
Codeword codeword = codewords[codewordsRow];
Codeword[] previousColumnCodewords = DetectionResultColumns[barcodeColumn - 1].Codewords;
Codeword[] nextColumnCodewords = previousColumnCodewords;
if (DetectionResultColumns[barcodeColumn + 1] != null)
{
nextColumnCodewords = DetectionResultColumns[barcodeColumn + 1].Codewords;
}
Codeword[] otherCodewords = new Codeword[14];
otherCodewords[2] = previousColumnCodewords[codewordsRow];
otherCodewords[3] = nextColumnCodewords[codewordsRow];
if (codewordsRow > 0)
{
otherCodewords[0] = codewords[codewordsRow - 1];
otherCodewords[4] = previousColumnCodewords[codewordsRow - 1];
otherCodewords[5] = nextColumnCodewords[codewordsRow - 1];
}
if (codewordsRow > 1)
{
otherCodewords[8] = codewords[codewordsRow - 2];
otherCodewords[10] = previousColumnCodewords[codewordsRow - 2];
otherCodewords[11] = nextColumnCodewords[codewordsRow - 2];
}
if (codewordsRow < codewords.Length - 1)
{
otherCodewords[1] = codewords[codewordsRow + 1];
otherCodewords[6] = previousColumnCodewords[codewordsRow + 1];
otherCodewords[7] = nextColumnCodewords[codewordsRow + 1];
}
if (codewordsRow < codewords.Length - 2)
{
otherCodewords[9] = codewords[codewordsRow + 2];
otherCodewords[12] = previousColumnCodewords[codewordsRow + 2];
otherCodewords[13] = nextColumnCodewords[codewordsRow + 2];
}
foreach (Codeword otherCodeword in otherCodewords)
{
if (adjustRowNumber(codeword, otherCodeword))
{
return;
}
}
}
/// <summary>
/// Adjusts the row number.
/// </summary>
/// <returns><c>true</c>, if row number was adjusted, <c>false</c> otherwise.</returns>
/// <param name="codeword">Codeword.</param>
/// <param name="otherCodeword">Other codeword.</param>
private static bool adjustRowNumber(Codeword codeword, Codeword otherCodeword)
{
if (otherCodeword == null)
{
return false;
}
if (otherCodeword.HasValidRowNumber && otherCodeword.Bucket == codeword.Bucket)
{
codeword.RowNumber = otherCodeword.RowNumber;
return true;
}
return false;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.DetectionResult"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.DetectionResult"/>.</returns>
public override string ToString()
{
StringBuilder formatter = new StringBuilder();
DetectionResultColumn rowIndicatorColumn = DetectionResultColumns[0];
if (rowIndicatorColumn == null)
{
rowIndicatorColumn = DetectionResultColumns[ColumnCount + 1];
}
for (int codewordsRow = 0; codewordsRow < rowIndicatorColumn.Codewords.Length; codewordsRow++)
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "CW {0,3}:", codewordsRow);
for (int barcodeColumn = 0; barcodeColumn < ColumnCount + 2; barcodeColumn++)
{
if (DetectionResultColumns[barcodeColumn] == null)
{
formatter.Append(" | ");
continue;
}
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword == null)
{
formatter.Append(" | ");
continue;
}
formatter.AppendFormat(CultureInfo.InvariantCulture, " {0,3}|{1,3}", codeword.RowNumber, codeword.Value);
}
formatter.Append("\n");
}
return formatter.ToString();
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Utilities.IO;
namespace Org.BouncyCastle.Asn1
{
/**
* a general purpose ASN.1 decoder - note: this class differs from the
* others in that it returns null after it has read the last object in
* the stream. If an ASN.1 Null is encountered a Der/BER Null object is
* returned.
*/
public class Asn1InputStream
: FilterStream
{
private readonly int limit;
public Asn1InputStream(
Stream inputStream)
: this(inputStream, int.MaxValue)
{
}
/**
* Create an ASN1InputStream where no DER object will be longer than limit.
*
* @param input stream containing ASN.1 encoded data.
* @param limit maximum size of a DER encoded object.
*/
public Asn1InputStream(
Stream inputStream,
int limit)
: base(inputStream)
{
this.limit = limit;
}
/**
* Create an ASN1InputStream based on the input byte array. The length of DER objects in
* the stream is automatically limited to the length of the input array.
*
* @param input array containing ASN.1 encoded data.
*/
public Asn1InputStream(
byte[] input)
: this(new MemoryStream(input, false), input.Length)
{
}
internal Asn1EncodableVector BuildEncodableVector()
{
Asn1EncodableVector v = new Asn1EncodableVector();
Asn1Object o;
while ((o = ReadObject()) != null)
{
v.Add(o);
}
return v;
}
internal virtual Asn1EncodableVector BuildDerEncodableVector(
DefiniteLengthInputStream dIn)
{
return new Asn1InputStream(dIn).BuildEncodableVector();
}
internal virtual DerSequence CreateDerSequence(
DefiniteLengthInputStream dIn)
{
return DerSequence.FromVector(BuildDerEncodableVector(dIn));
}
internal virtual DerSet CreateDerSet(
DefiniteLengthInputStream dIn)
{
return DerSet.FromVector(BuildDerEncodableVector(dIn), false);
}
public Asn1Object ReadObject()
{
int tag = ReadByte();
if (tag <= 0)
{
if (tag == 0)
throw new IOException("unexpected end-of-contents marker");
return null;
}
//
// calculate tag number
//
int tagNo = ReadTagNumber(this, tag);
bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
//
// calculate length
//
int length = ReadLength(this, limit);
if (length < 0) // indefinite length method
{
if (!isConstructed)
throw new IOException("indefinite length primitive encoding encountered");
IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this);
if ((tag & Asn1Tags.Application) != 0)
{
Asn1StreamParser sp2 = new Asn1StreamParser(indIn);
return new BerApplicationSpecificParser(tagNo, sp2).ToAsn1Object();
}
if ((tag & Asn1Tags.Tagged) != 0)
{
// TODO Investigate passing an Asn1StreamParser into this constructor
return new BerTaggedObjectParser(tag, tagNo, indIn).ToAsn1Object();
}
Asn1StreamParser sp = new Asn1StreamParser(indIn);
// TODO There are other tags that may be constructed (e.g. BitString)
switch (tagNo)
{
case Asn1Tags.OctetString:
return new BerOctetStringParser(sp).ToAsn1Object();
case Asn1Tags.Sequence:
return new BerSequenceParser(sp).ToAsn1Object();
case Asn1Tags.Set:
return new BerSetParser(sp).ToAsn1Object();
default:
throw new IOException("unknown BER object encountered");
}
}
else
{
DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length);
if ((tag & Asn1Tags.Application) != 0)
{
return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new BerTaggedObjectParser(tag, tagNo, defIn).ToAsn1Object();
}
if (isConstructed)
{
// TODO There are other tags that may be constructed (e.g. BitString)
switch (tagNo)
{
case Asn1Tags.OctetString:
//
// yes, people actually do this...
//
return new BerOctetString(BuildDerEncodableVector(defIn));
case Asn1Tags.Sequence:
return CreateDerSequence(defIn);
case Asn1Tags.Set:
return CreateDerSet(defIn);
default:
return new DerUnknownTag(true, tagNo, defIn.ToArray());
}
}
return CreatePrimitiveDerObject(tagNo, defIn.ToArray());
}
}
internal static int ReadTagNumber(
Stream s,
int tag)
{
int tagNo = tag & 0x1f;
//
// with tagged object tag number is bottom 5 bits, or stored at the start of the content
//
if (tagNo == 0x1f)
{
tagNo = 0;
int b = s.ReadByte();
// X.690-0207 8.1.2.4.2
// "c) bits 7 to 1 of the first subsequent octet shall not all be zero."
if ((b & 0x7f) == 0) // Note: -1 will pass
{
throw new IOException("corrupted stream - invalid high tag number found");
}
while ((b >= 0) && ((b & 0x80) != 0))
{
tagNo |= (b & 0x7f);
tagNo <<= 7;
b = s.ReadByte();
}
if (b < 0)
throw new EndOfStreamException("EOF found inside tag value.");
tagNo |= (b & 0x7f);
}
return tagNo;
}
internal static int ReadLength(
Stream s,
int limit)
{
int length = s.ReadByte();
if (length < 0)
throw new EndOfStreamException("EOF found when length expected");
if (length == 0x80)
return -1; // indefinite-length encoding
if (length > 127)
{
int size = length & 0x7f;
if (size > 4)
throw new IOException("DER length more than 4 bytes");
length = 0;
for (int i = 0; i < size; i++)
{
int next = s.ReadByte();
if (next < 0)
throw new EndOfStreamException("EOF found reading length");
length = (length << 8) + next;
}
if (length < 0)
throw new IOException("Corrupted stream - negative length found");
if (length >= limit) // after all we must have read at least 1 byte
throw new IOException("Corrupted stream - out of bounds length found");
}
return length;
}
internal static Asn1Object CreatePrimitiveDerObject(
int tagNo,
byte[] bytes)
{
switch (tagNo)
{
case Asn1Tags.BitString:
{
int padBits = bytes[0];
byte[] data = new byte[bytes.Length - 1];
Array.Copy(bytes, 1, data, 0, bytes.Length - 1);
return new DerBitString(data, padBits);
}
case Asn1Tags.BmpString:
return new DerBmpString(bytes);
case Asn1Tags.Boolean:
return new DerBoolean(bytes);
case Asn1Tags.Enumerated:
return new DerEnumerated(bytes);
case Asn1Tags.GeneralizedTime:
return new DerGeneralizedTime(bytes);
case Asn1Tags.GeneralString:
return new DerGeneralString(bytes);
case Asn1Tags.IA5String:
return new DerIA5String(bytes);
case Asn1Tags.Integer:
return new DerInteger(bytes);
case Asn1Tags.Null:
return DerNull.Instance; // actual content is ignored (enforce 0 length?)
case Asn1Tags.NumericString:
return new DerNumericString(bytes);
case Asn1Tags.ObjectIdentifier:
return new DerObjectIdentifier(bytes);
case Asn1Tags.OctetString:
return new DerOctetString(bytes);
case Asn1Tags.PrintableString:
return new DerPrintableString(bytes);
case Asn1Tags.T61String:
return new DerT61String(bytes);
case Asn1Tags.UniversalString:
return new DerUniversalString(bytes);
case Asn1Tags.UtcTime:
return new DerUtcTime(bytes);
case Asn1Tags.Utf8String:
return new DerUtf8String(bytes);
case Asn1Tags.VisibleString:
return new DerVisibleString(bytes);
default:
return new DerUnknownTag(false, tagNo, bytes);
}
}
}
}
| |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HeadRaceTimingSite.Models;
using System.Collections.Generic;
namespace HeadRaceTimingSite.Tests.Models
{
[TestClass]
public class CrewTests
{
[TestMethod]
public void RunTime_WithNoResults_ShouldReturnNull()
{
Crew crew = new Crew();
TimingPoint startPoint = new TimingPoint();
TimingPoint finishPoint = new TimingPoint();
Assert.IsNull(crew.RunTime(startPoint, finishPoint));
}
[TestMethod]
public void RunTime_WithTwoResults_ShouldReturnDifference()
{
Crew crew = new Crew();
TimingPoint startPoint = new TimingPoint(1);
TimingPoint finishPoint = new TimingPoint(2);
crew.Results.Add(new Result(startPoint, crew, new TimeSpan(2, 0, 0)));
crew.Results.Add(new Result(finishPoint, crew, new TimeSpan(2, 20, 0)));
Assert.AreEqual(new TimeSpan(0, 20, 0), crew.RunTime(startPoint, finishPoint));
}
[TestMethod]
public void RunTime_ShouldRoundToNearestTenth()
{
Crew crew = new Crew();
TimingPoint startPoint = new TimingPoint(1);
TimingPoint finishPoint = new TimingPoint(2);
crew.Results.Add(new Result(startPoint, crew, new TimeSpan(2, 0, 0)));
crew.Results.Add(new Result(finishPoint, crew, new TimeSpan(0, 2, 20, 0, 210)));
Assert.AreEqual(new TimeSpan(0, 0, 20, 0, 200), crew.RunTime(startPoint, finishPoint));
}
[TestMethod]
public void RunTime_WithPenalty_ShouldNotIncludePenalty()
{
Crew crew = new Crew();
TimingPoint startPoint = new TimingPoint(1);
TimingPoint finishPoint = new TimingPoint(2);
crew.Results.Add(new Result(startPoint, crew, new TimeSpan(2, 0, 0)));
crew.Results.Add(new Result(finishPoint, crew, new TimeSpan(0, 2, 20, 0, 210)));
crew.Penalties.Add(new Penalty { Value = new TimeSpan(0, 0, 5) });
Assert.AreEqual(new TimeSpan(0, 0, 20, 0, 200), crew.RunTime(startPoint, finishPoint));
}
[TestMethod]
public void OverallTime_WithPenalty_ShouldIncludePenalty()
{
Crew crew = new Crew();
TimingPoint startPoint = new TimingPoint(1);
TimingPoint finishPoint = new TimingPoint(2);
Competition competition = new Competition();
competition.TimingPoints.Add(startPoint);
competition.TimingPoints.Add(finishPoint);
crew.Competition = competition;
crew.Results.Add(new Result(startPoint, crew, new TimeSpan(2, 0, 0)));
crew.Results.Add(new Result(finishPoint, crew, new TimeSpan(0, 2, 20, 0, 210)));
crew.Penalties.Add(new Penalty { Value = new TimeSpan(0, 0, 5) });
Assert.AreEqual(new TimeSpan(0, 0, 20, 5, 200), crew.OverallTime);
}
[TestMethod]
public void Rank_WithSingleResult_ShouldReturnOne()
{
Crew crew = new Crew();
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
crew.Results.Add(startResult);
TimingPoint finishTimingPoint = new TimingPoint(2);
Result finishResult = new Result(finishTimingPoint, TimeSpan.Zero);
crew.Results.Add(finishResult);
List<Crew> crewList = new List<Crew>();
crewList.Add(crew);
Assert.AreEqual("1", crew.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void Rank_WithMultipleDistinct_ShouldReturnPlacing()
{
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
TimingPoint finishTimingPoint = new TimingPoint(2);
Crew crewOne = new Crew();
Result resultOne = new Result(finishTimingPoint, TimeSpan.Zero);
crewOne.Results.Add(startResult);
crewOne.Results.Add(resultOne);
Crew crewTwo = new Crew();
Result resultTwo = new Result(finishTimingPoint, TimeSpan.Zero.Add(new TimeSpan(0, 0, 2)));
crewTwo.Results.Add(startResult);
crewTwo.Results.Add(resultTwo);
List<Crew> crewList = new List<Crew>();
crewList.Add(crewOne);
crewList.Add(crewTwo);
Assert.AreEqual("1", crewOne.Rank(crewList, startTimingPoint, finishTimingPoint));
Assert.AreEqual("2", crewTwo.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void Rank_WithTwoIdenticalTimes_ShouldReturnEqualPlacings()
{
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
TimingPoint finishTimingPoint = new TimingPoint(2);
Crew crewOne = new Crew();
Result resultOne = new Result(finishTimingPoint, TimeSpan.Zero);
crewOne.Results.Add(startResult);
crewOne.Results.Add(resultOne);
Crew crewTwo = new Crew();
Result resultTwo = new Result(finishTimingPoint, TimeSpan.Zero);
crewTwo.Results.Add(startResult);
crewTwo.Results.Add(resultTwo);
List<Crew> crewList = new List<Crew>();
crewList.Add(crewOne);
crewList.Add(crewTwo);
Assert.AreEqual("1=", crewOne.Rank(crewList, startTimingPoint, finishTimingPoint));
Assert.AreEqual("1=", crewTwo.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void Rank_WithThreeIdenticalTimes_ShouldReturnEqualPlacings()
{
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
TimingPoint finishTimingPoint = new TimingPoint(2);
Crew crewOne = new Crew();
Result resultOne = new Result(finishTimingPoint, TimeSpan.Zero);
crewOne.Results.Add(startResult);
crewOne.Results.Add(resultOne);
Crew crewTwo = new Crew();
Result resultTwo = new Result(finishTimingPoint, TimeSpan.Zero);
crewTwo.Results.Add(startResult);
crewTwo.Results.Add(resultTwo);
Crew crewThree = new Crew();
Result resultThree = new Result(finishTimingPoint, TimeSpan.Zero);
crewThree.Results.Add(startResult);
crewThree.Results.Add(resultThree);
List<Crew> crewList = new List<Crew>();
crewList.Add(crewOne);
crewList.Add(crewTwo);
crewList.Add(crewThree);
Assert.AreEqual("1=", crewOne.Rank(crewList, startTimingPoint, finishTimingPoint));
Assert.AreEqual("1=", crewTwo.Rank(crewList, startTimingPoint, finishTimingPoint));
Assert.AreEqual("1=", crewThree.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void Rank_WithTimesWithinOneTenthRoundingEqual_ShouldReturnEqual()
{
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
TimingPoint finishTimingPoint = new TimingPoint(2);
Crew crewOne = new Crew();
Result resultOne = new Result(finishTimingPoint, TimeSpan.Zero);
crewOne.Results.Add(startResult);
crewOne.Results.Add(resultOne);
Crew crewTwo = new Crew();
Result resultTwo = new Result(finishTimingPoint, TimeSpan.Zero.Add(new TimeSpan(0, 0, 0, 0, 5)));
crewTwo.Results.Add(startResult);
crewTwo.Results.Add(resultTwo);
List<Crew> crewList = new List<Crew>();
crewList.Add(crewOne);
crewList.Add(crewTwo);
Assert.AreEqual("1=", crewOne.Rank(crewList, startTimingPoint, finishTimingPoint));
Assert.AreEqual("1=", crewTwo.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void Rank_WithTimesWithinOneTenthRoundingNotEqual_ShouldReturnNotEqual()
{
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
TimingPoint finishTimingPoint = new TimingPoint(2);
Crew crewOne = new Crew();
Result resultOne = new Result(finishTimingPoint, new TimeSpan(0, 0, 0, 0, 410));
crewOne.Results.Add(startResult);
crewOne.Results.Add(resultOne);
Crew crewTwo = new Crew();
Result resultTwo = new Result(finishTimingPoint, new TimeSpan(0, 0, 0, 0, 490));
crewTwo.Results.Add(startResult);
crewTwo.Results.Add(resultTwo);
List<Crew> crewList = new List<Crew>();
crewList.Add(crewOne);
crewList.Add(crewTwo);
Assert.AreEqual("1", crewOne.Rank(crewList, startTimingPoint, finishTimingPoint));
Assert.AreEqual("2", crewTwo.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void Rank_WithTimeOnlyCrew_ShouldReturnEmptyString()
{
TimingPoint startTimingPoint = new TimingPoint(1);
Result startResult = new Result(startTimingPoint, TimeSpan.Zero);
TimingPoint finishTimingPoint = new TimingPoint(2);
Crew crewOne = new Crew();
crewOne.IsTimeOnly = true;
Result resultOne = new Result(finishTimingPoint, new TimeSpan(0, 0, 0, 0, 410));
crewOne.Results.Add(startResult);
crewOne.Results.Add(resultOne);
List<Crew> crewList = new List<Crew>();
crewList.Add(crewOne);
Assert.AreEqual(String.Empty, crewOne.Rank(crewList, startTimingPoint, finishTimingPoint));
}
[TestMethod]
public void AverageAge_WithCrewWithAges_ShouldReturnAverage()
{
Crew crew = new Crew();
Athlete athleteOne = new Athlete();
Athlete athleteTwo = new Athlete();
Athlete athleteThree = new Athlete();
crew.Athletes.Add(new CrewAthlete { Athlete = athleteOne, Age = 30 });
crew.Athletes.Add(new CrewAthlete { Athlete = athleteTwo, Age = 31 });
crew.Athletes.Add(new CrewAthlete { Athlete = athleteThree, Age = 32 });
Assert.AreEqual(31, crew.AverageAge);
}
[DataTestMethod]
[DataRow(MastersCategory.None, 26)]
[DataRow(MastersCategory.A, 27)]
[DataRow(MastersCategory.B, 36)]
[DataRow(MastersCategory.C, 43)]
[DataRow(MastersCategory.D, 50)]
[DataRow(MastersCategory.E, 55)]
[DataRow(MastersCategory.F, 60)]
[DataRow(MastersCategory.G, 65)]
[DataRow(MastersCategory.H, 70)]
[DataRow(MastersCategory.I, 75)]
[DataRow(MastersCategory.J, 80)]
[DataRow(MastersCategory.K, 85)]
public void MastersCategory_WithCrewWithAges_ShouldReturnCorrectCategory(MastersCategory mastersCategory, int athleteAge)
{
Crew crew = new Crew();
crew.Athletes.Add(new CrewAthlete { Athlete = new Athlete(), Age = athleteAge });
Assert.AreEqual(mastersCategory, crew.MastersCategory, "Category: {0}; Age One: {1}", mastersCategory, athleteAge);
}
[TestMethod]
public void MastersHandicap_WithNonMastersCrew_ShouldThrowInvalidOperationException()
{
Crew crew = new Crew();
crew.Athletes.Add(new CrewAthlete { Athlete = new Athlete(), Age = 26 });
Award award = new Award { IsMasters = true, AwardId = 1 };
crew.Awards.Add(new CrewAward() { Award = award });
Assert.ThrowsException<InvalidOperationException>(() => crew.CalculateMastersHandicap(new Dictionary<MastersCategory, int>(), new Dictionary<MastersCategory, int>()));
}
[TestMethod]
public void MastersHandicap_WithCrewNotInMastersCompetition_ShouldThrowInvalidOperationException()
{
Crew crew = new Crew();
crew.Athletes.Add(new CrewAthlete { Athlete = new Athlete(), Age = 27 });
Assert.ThrowsException<InvalidOperationException>(() => crew.CalculateMastersHandicap(new Dictionary<MastersCategory, int>(), new Dictionary<MastersCategory, int>()));
}
[TestMethod]
public void MastersHandicap_WithMastersACrew_ShouldReturnZero()
{
Crew crew = new Crew();
crew.Athletes.Add(new CrewAthlete { Athlete = new Athlete(), Age = 27 });
Award award = new Award { IsMasters = true, AwardId = 1 };
crew.Awards.Add(new CrewAward() { Award = award });
Assert.AreEqual(0, crew.CalculateMastersHandicap(new Dictionary<MastersCategory, int>(), new Dictionary<MastersCategory, int>()));
}
[DataTestMethod]
[DataRow(36, 10, 0, 5)]
public void MastersHandicap_WithMastersCrew_ShouldReturnCorrectHandicap(int age, int minutes, int seconds, int handicap)
{
Competition competition = new Competition();
competition.TimingPoints.Add(new TimingPoint { TimingPointId = 1 });
competition.TimingPoints.Add(new TimingPoint { TimingPointId = 2 });
Award award = new Award { IsMasters = true, AwardId = 1 };
competition.Awards.Add(award);
Crew crewOne = new Crew();
crewOne.Results.Add(new Result { TimingPointId = 1, TimeOfDay = new TimeSpan(10, 0, 0) });
crewOne.Results.Add(new Result { TimingPointId = 2, TimeOfDay = new TimeSpan(10, minutes, seconds) });
crewOne.Awards.Add(new CrewAward { Award = award });
crewOne.Athletes.Add(new CrewAthlete { Athlete = new Athlete(), Age = 27 });
award.Crews.Add(new CrewAward { Crew = crewOne });
crewOne.Competition = competition;
competition.Crews.Add(crewOne);
Crew crewTwo = new Crew();
crewTwo.Results.Add(new Result { TimingPointId = 1, TimeOfDay = new TimeSpan(10, 0, 0) });
crewTwo.Results.Add(new Result { TimingPointId = 2, TimeOfDay = new TimeSpan(10, minutes, seconds + 20) });
crewTwo.Awards.Add(new CrewAward { Award = award });
crewTwo.Athletes.Add(new CrewAthlete { Athlete = new Athlete(), Age = age });
crewTwo.Competition = competition;
award.Crews.Add(new CrewAward { Crew = crewTwo });
competition.Crews.Add(crewTwo);
Dictionary<MastersCategory, int> lowerBounds = new Dictionary<MastersCategory, int>();
lowerBounds.Add(MastersCategory.B, handicap);
Dictionary<MastersCategory, int> upperBounds = new Dictionary<MastersCategory, int>();
upperBounds.Add(MastersCategory.B, handicap);
Assert.AreEqual(handicap, crewTwo.CalculateMastersHandicap(lowerBounds, upperBounds));
}
[TestMethod]
public void Cri_ShouldReturnSumOfPri()
{
Crew crew = new Crew();
crew.BoatClass = BoatClass.CoxlessPair;
Athlete athlete1 = new Athlete();
Athlete athlete2 = new Athlete();
crew.Athletes.Add(new CrewAthlete { Athlete = athlete1, Position = 1, Pri = 1, Crew = crew });
crew.Athletes.Add(new CrewAthlete { Athlete = athlete2, Position = 2, Pri = 1, Crew = crew });
Assert.AreEqual(2, crew.Cri);
}
[TestMethod]
public void CriMax_ShouldReturnSumOfPriMax()
{
Crew crew = new Crew();
crew.BoatClass = BoatClass.CoxlessPair;
Athlete athlete1 = new Athlete();
Athlete athlete2 = new Athlete();
crew.Athletes.Add(new CrewAthlete { Athlete = athlete1, Position = 1, PriMax = 1, Crew = crew });
crew.Athletes.Add(new CrewAthlete { Athlete = athlete2, Position = 2, PriMax = 1, Crew = crew });
Assert.AreEqual(2, crew.CriMax);
}
[TestMethod]
public void Cri_ShouldIgnoreCox()
{
Crew crew = new Crew();
crew.BoatClass = BoatClass.CoxedPair;
Athlete athlete1 = new Athlete();
Athlete athlete2 = new Athlete();
Athlete cox = new Athlete();
crew.Athletes.Add(new CrewAthlete { Athlete = athlete1, Position = 1, Pri = 1, Crew = crew });
crew.Athletes.Add(new CrewAthlete { Athlete = athlete2, Position = 2, Pri = 1, Crew = crew });
crew.Athletes.Add(new CrewAthlete { Athlete = cox, Position = 3, Pri = 1, Crew = crew });
Assert.AreEqual(2, crew.Cri);
}
[TestMethod]
public void CriMax_ShouldIgnoreCox()
{
Crew crew = new Crew();
crew.BoatClass = BoatClass.CoxedPair;
Athlete athlete1 = new Athlete();
Athlete athlete2 = new Athlete();
Athlete cox = new Athlete();
crew.Athletes.Add(new CrewAthlete { Athlete = athlete1, Position = 1, PriMax = 1, Crew = crew });
crew.Athletes.Add(new CrewAthlete { Athlete = athlete2, Position = 2, PriMax = 1, Crew = crew });
crew.Athletes.Add(new CrewAthlete { Athlete = cox, Position = 3, PriMax = 1, Crew = crew });
Assert.AreEqual(2, crew.CriMax);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace SimpleAssetBundler
{
public class SimpleAssetBundler : EditorWindow
{
private const string defaultAssetBundleDirectory = "Assets\\Bundles\\";
private const string defaultOutputDirectory = "AssetBundles";
[MenuItem("Assets/AssetBundles/Simple Asset Bundler")]
private static void OpenAssetBundlesWindow()
{
var newWindow = GetWindow<SimpleAssetBundler>();
newWindow.Show();
}
private static List<AssetBundleBuild> BuildAllAssetBundles(BuildAssetBundleOptions assetBundleOptions)
{
List<AssetBundleBuild> builds = new List<AssetBundleBuild>();
string assetBundleDirectory = EditorPrefs.GetString("SimpleBundlerBundleDir", defaultAssetBundleDirectory);
string outputDirectory = EditorPrefs.GetString("SimpleBundlerOutputDir", defaultOutputDirectory);
if (!Directory.Exists(assetBundleDirectory))
{
Directory.CreateDirectory(assetBundleDirectory);
}
if (!Directory.Exists(outputDirectory))
{
Directory.CreateDirectory(outputDirectory);
}
if (EditorPrefs.GetBool("SimpleBundlerClearOnBuild", false))
{
ClearDirectory(defaultOutputDirectory);
}
string[] directories = Directory.GetDirectories(assetBundleDirectory);
foreach (var directory in directories)
{
var build = new AssetBundleBuild();
List<string> filesInBuild = new List<string>();
List<string> bundleAccessPaths = new List<string>();
string bundleName = directory.Replace(assetBundleDirectory, "").Remove(0, 1);
int variantStart = bundleName.IndexOf(".");
string variant = null;
if ((variantStart != -1) && ((variantStart + 1) < bundleName.Length))
{
variant = bundleName.Substring(variantStart + 1);
bundleName = bundleName.Remove(variantStart);
}
build.assetBundleVariant = variant;
build.assetBundleName = bundleName;
AssignAssetBundles(build, filesInBuild, bundleAccessPaths, directory);
build.assetNames = filesInBuild.ToArray();
build.addressableNames = bundleAccessPaths.ToArray();
builds.Add(build);
}
BuildPipeline.BuildAssetBundles(outputDirectory, builds.ToArray(), (BuildAssetBundleOptions)((int)assetBundleOptions / 2), EditorUserBuildSettings.activeBuildTarget);
return builds;
}
private static void ClearDirectory(string directory)
{
var subdirectories = Directory.GetDirectories(directory);
foreach (var sub in subdirectories)
{
ClearDirectory(sub);
Directory.Delete(sub);
}
foreach (var file in Directory.GetFiles(directory))
{
File.Delete(file);
}
}
private static void AssignAssetBundles(AssetBundleBuild build, List<string> filesInBuild, List<string> fileAccessPaths, string path)
{
path = path.Replace('/', '\\');
var directories = Directory.GetDirectories(path);
var files = Directory.GetFiles(path);
foreach (var file in files)
{
string bundlePath = file;
bundlePath = bundlePath.Remove(0, file.IndexOf(build.assetBundleName));
if (!string.IsNullOrEmpty(build.assetBundleVariant))
{
bundlePath = bundlePath.Remove(bundlePath.IndexOf(build.assetBundleVariant) - 1, build.assetBundleVariant.Length + 1);
}
AssetImporter importer = AssetImporter.GetAtPath(file);
if (importer == null)
continue;
importer.assetBundleName = bundlePath;
importer.assetBundleVariant = build.assetBundleVariant;
fileAccessPaths.Add(importer.assetBundleName);
filesInBuild.Add(file);
}
foreach (var directory in directories)
{
AssignAssetBundles(build, filesInBuild, fileAccessPaths, directory);
}
}
private List<CachedBuildInfo> cachedInfo;
private Vector2 buildResultsScroll;
private BuildAssetBundleOptions buildOptions = BuildAssetBundleOptions.UncompressedAssetBundle;
private BuildTarget targetPlatform;
private void OnGUI()
{
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Bundle Folder: ", GUILayout.MaxWidth(100));
EditorPrefs.SetString("SimpleBundlerBundleDir", EditorGUILayout.TextField(EditorPrefs.GetString("SimpleBundlerBundleDir", defaultAssetBundleDirectory)));
if (GUILayout.Button("...", GUILayout.Width(30)))
EditorPrefs.SetString("SimpleBundlerBundleDir", (EditorUtility.OpenFolderPanel("Select an Asset Bundle Directory", EditorPrefs.GetString("SimpleBundlerBundleDir", defaultAssetBundleDirectory), "").Remove(0, Directory.GetCurrentDirectory().Length + 1)));
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Output Folder: ", GUILayout.MaxWidth(100));
EditorPrefs.SetString("SimpleBundlerOutputDir", EditorGUILayout.TextField(EditorPrefs.GetString("SimpleBundlerOutputDir", defaultOutputDirectory)));
if (GUILayout.Button("...", GUILayout.Width(30)))
{
EditorPrefs.SetString("SimpleBundlerOutputDir", (EditorUtility.OpenFolderPanel("Select an Output Directory", EditorPrefs.GetString("SimpleBundlerOutputDir", defaultAssetBundleDirectory), "").Remove(0, Directory.GetCurrentDirectory().Length + 1)));
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Clear Output Folder on Build:", GUILayout.MaxWidth(200));
EditorPrefs.SetBool("SimpleBundlerClearOnBuild", EditorGUILayout.Toggle(EditorPrefs.GetBool("SimpleBundlerClearOnBuild", true)));
}
EditorGUILayout.EndHorizontal();
buildOptions = (BuildAssetBundleOptions)EditorGUILayout.EnumMaskPopup("Build Options: ", buildOptions);
if (GUILayout.Button("Build AssetBundles"))
{
var buildInfo = BuildAllAssetBundles(buildOptions);
cachedInfo = new List<CachedBuildInfo>();
for (var i = 0; i < buildInfo.Count; i++)
{
var info = new CachedBuildInfo();
info.BundlePaths = new List<string>();
info.LocalPaths = new List<string>();
info.BuildName = buildInfo[i].assetBundleName;
info.Variant = buildInfo[i].assetBundleVariant;
for (var j = 0; j < buildInfo[i].addressableNames.Length; j++)
{
info.BundlePaths.Add(buildInfo[i].addressableNames[j]);
info.LocalPaths.Add(buildInfo[i].assetNames[j]);
}
cachedInfo.Add(info);
}
}
DisplayResults();
}
private void DisplayResults()
{
if (cachedInfo != null)
{
buildResultsScroll = EditorGUILayout.BeginScrollView(buildResultsScroll);
GUIStyle buildNameLabel = new GUIStyle();
buildNameLabel.fontSize = 16;
buildNameLabel.fontStyle = FontStyle.Bold;
foreach (var buildInfo in cachedInfo)
{
buildInfo.IsFoldedOut = (string.IsNullOrEmpty(buildInfo.Variant)) ?
EditorGUILayout.Foldout(buildInfo.IsFoldedOut, buildInfo.BuildName) :
EditorGUILayout.Foldout(buildInfo.IsFoldedOut, buildInfo.BuildName + " [" + buildInfo.Variant + "]");
if (buildInfo.IsFoldedOut)
{
buildInfo.Scroll = EditorGUILayout.BeginScrollView(buildInfo.Scroll, true, true);
{
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Local Path", EditorStyles.boldLabel);
EditorGUILayout.LabelField("Bundle Path", EditorStyles.boldLabel);
}
EditorGUILayout.EndHorizontal();
for (var i = 0; i < buildInfo.LocalPaths.Count; i++)
{
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField(new GUIContent(buildInfo.LocalPaths[i], buildInfo.LocalPaths[i]));
EditorGUILayout.LabelField(new GUIContent(buildInfo.BundlePaths[i], buildInfo.BundlePaths[i]));
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.EndScrollView();
}
}
EditorGUILayout.EndScrollView();
}
}
[Serializable]
public class CachedBuildInfo
{
public string BuildName { get; set; }
public string Variant { get; set; }
public List<string> LocalPaths { get; set; }
public List<string> BundlePaths { get; set; }
public Vector2 Scroll { get; set; }
public bool IsFoldedOut { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
public struct Span<T>
{
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
_length = array.Length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and covering the remainder of the array.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
int arrayLength = array.Length;
if ((uint)start > (uint)arrayLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = arrayLength - start;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = null;
_byteOffset = new IntPtr(pointer);
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
{
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
IntPtr byteOffset = Unsafe.ByteOffset<T>(ref pinnable.Data, ref objectData);
return new Span<T>(pinnable, byteOffset, length);
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
{
Debug.Assert(length >= 0);
_length = length;
_pinnable = pinnable;
_byteOffset = byteOffset;
}
/// <summary>
/// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return ref Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return ref Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
public unsafe void Clear()
{
int length = _length;
if (length == 0)
return;
var byteLength = (UIntPtr)((uint)length * Unsafe.SizeOf<T>());
if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
{
if (_pinnable == null)
{
var ptr = (byte*)_byteOffset.ToPointer();
SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
SpanHelpers.ClearLessThanPointerSized(ref b, byteLength);
}
}
else
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
{
UIntPtr pointerSizedLength = (UIntPtr)((length * Unsafe.SizeOf<T>()) / sizeof(IntPtr));
ref IntPtr ip = ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithReferences(ref ip, pointerSizedLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithoutReferences(ref b, byteLength);
}
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public unsafe void Fill(T value)
{
int length = _length;
if (length == 0)
return;
if (Unsafe.SizeOf<T>() == 1)
{
byte fill = Unsafe.As<T, byte>(ref value);
if (_pinnable == null)
{
Unsafe.InitBlockUnaligned(_byteOffset.ToPointer(), fill, (uint)length);
}
else
{
ref byte r = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
Unsafe.InitBlockUnaligned(ref r, fill, (uint)length);
}
}
else
{
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
// Simple loop unrolling
int i = 0;
for (; i < (length & ~7); i += 8)
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
Unsafe.Add<T>(ref r, i + 4) = value;
Unsafe.Add<T>(ref r, i + 5) = value;
Unsafe.Add<T>(ref r, i + 6) = value;
Unsafe.Add<T>(ref r, i + 7) = value;
}
if (i < (length & ~3))
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.Add<T>(ref r, i) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
int length = _length;
int destLength = destination._length;
if ((uint)length == 0)
return true;
if ((uint)length > (uint)destLength)
return false;
ref T src = ref DangerousGetPinnableReference();
ref T dst = ref destination.DangerousGetPinnableReference();
SpanHelpers.CopyTo<T>(ref dst, destLength, ref src, length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(Span<T> left, Span<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(T[] array) => new Span<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
int length = _length - start;
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return SpanHelpers.PerTypeValues<T>.EmptyArray;
T[] result = new T[_length];
CopyTo(result);
return result;
}
/// <summary>
/// Returns a 0-length span whose base is the null pointer.
/// </summary>
public static Span<T> Empty => default(Span<T>);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
unsafe { return ref Unsafe.AsRef<T>(_byteOffset.ToPointer()); }
else
return ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
}
// These expose the internal representation for Span-related apis use only.
internal Pinnable<T> Pinnable => _pinnable;
internal IntPtr ByteOffset => _byteOffset;
//
// If the Span was constructed from an object,
//
// _pinnable = that object (unsafe-casted to a Pinnable<T>)
// _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref span[0]"
//
// If the Span was constructed from a native pointer,
//
// _pinnable = null
// _byteOffset = the pointer
//
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
public static class Span
{
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<byte> AsBytes<T>(this Span<T> source)
where T : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
int newLength = checked(source.Length * Unsafe.SizeOf<T>());
return new Span<byte>(Unsafe.As<Pinnable<byte>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source)
where T : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
int newLength = checked(source.Length * Unsafe.SizeOf<T>());
return new ReadOnlySpan<byte>(Unsafe.As<Pinnable<byte>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access.
/// </remarks>
/// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source)
where TFrom : struct
where TTo : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom));
if (SpanHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo));
int newLength = checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()));
return new Span<TTo>(Unsafe.As<Pinnable<TTo>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access.
/// </remarks>
/// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source)
where TFrom : struct
where TTo : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom));
if (SpanHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo));
int newLength = checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()));
return new ReadOnlySpan<TTo>(Unsafe.As<Pinnable<TTo>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> Slice(this string text)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string, beginning at 'start'.
/// </summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> Slice(this string text, int start)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
int textLength = text.Length;
if ((uint)start > (uint)textLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
unsafe
{
byte* byteOffset = ((byte*)StringAdjustment) + (uint)(start * sizeof(char));
return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), (IntPtr)byteOffset, textLength - start);
}
}
/// <summary>
/// Creates a new readonly span over the portion of the target string, beginning at <paramref name="start"/>, of given <paramref name="length"/>.
/// </summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> Slice(this string text, int start, int length)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
int textLength = text.Length;
if ((uint)start > (uint)textLength || (uint)length > (uint)(textLength - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
unsafe
{
byte* byteOffset = ((byte*)StringAdjustment) + (uint)(start * sizeof(char));
return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), (IntPtr)byteOffset, length);
}
}
private static readonly IntPtr StringAdjustment = MeasureStringAdjustment();
private static IntPtr MeasureStringAdjustment()
{
string sampleString = "a";
unsafe
{
fixed (char* pSampleString = sampleString)
{
return Unsafe.ByteOffset<char>(ref Unsafe.As<Pinnable<char>>(sampleString).Data, ref Unsafe.AsRef<char>(pSampleString));
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SkinnedEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace StockEffects
{
/// <summary>
/// Built-in effect for rendering skinned character models.
/// </summary>
public class SkinnedEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog
{
public const int MaxBones = 72;
#region Effect Parameters
EffectParameter textureParam;
EffectParameter diffuseColorParam;
EffectParameter emissiveColorParam;
EffectParameter specularColorParam;
EffectParameter specularPowerParam;
EffectParameter eyePositionParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldParam;
EffectParameter worldInverseTransposeParam;
EffectParameter worldViewProjParam;
EffectParameter bonesParam;
EffectParameter shaderIndexParam;
#endregion
#region Fields
bool preferPerPixelLighting;
bool oneLight;
bool fogEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector3 diffuseColor = Vector3.One;
Vector3 emissiveColor = Vector3.Zero;
Vector3 ambientLightColor = Vector3.Zero;
float alpha = 1;
DirectionalLight light0;
DirectionalLight light1;
DirectionalLight light2;
float fogStart = 0;
float fogEnd = 1;
int weightsPerVertex = 4;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector3 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material emissive color (range 0 to 1).
/// </summary>
public Vector3 EmissiveColor
{
get { return emissiveColor; }
set
{
emissiveColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material specular color (range 0 to 1).
/// </summary>
public Vector3 SpecularColor
{
get { return specularColorParam.GetValueVector3(); }
set { specularColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the material specular power.
/// </summary>
public float SpecularPower
{
get { return specularPowerParam.GetValueSingle(); }
set { specularPowerParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the per-pixel lighting prefer flag.
/// </summary>
public bool PreferPerPixelLighting
{
get { return preferPerPixelLighting; }
set
{
if (preferPerPixelLighting != value)
{
preferPerPixelLighting = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// Gets or sets the ambient light color (range 0 to 1).
/// </summary>
public Vector3 AmbientLightColor
{
get { return ambientLightColor; }
set
{
ambientLightColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets the first directional light.
/// </summary>
public DirectionalLight DirectionalLight0 { get { return light0; } }
/// <summary>
/// Gets the second directional light.
/// </summary>
public DirectionalLight DirectionalLight1 { get { return light1; } }
/// <summary>
/// Gets the third directional light.
/// </summary>
public DirectionalLight DirectionalLight2 { get { return light2; } }
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValueVector3(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetValueTexture2D(); }
set { textureParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the number of skinning weights to evaluate for each vertex (1, 2, or 4).
/// </summary>
public int WeightsPerVertex
{
get { return weightsPerVertex; }
set
{
if ((value != 1) &&
(value != 2) &&
(value != 4))
{
throw new ArgumentOutOfRangeException("value");
}
weightsPerVertex = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
/// <summary>
/// Sets an array of skinning bone transform matrices.
/// </summary>
public void SetBoneTransforms(Matrix[] boneTransforms)
{
if ((boneTransforms == null) || (boneTransforms.Length == 0))
throw new ArgumentNullException("boneTransforms");
if (boneTransforms.Length > MaxBones)
throw new ArgumentException();
bonesParam.SetValue(boneTransforms);
}
/// <summary>
/// Gets a copy of the current skinning bone transform matrices.
/// </summary>
public Matrix[] GetBoneTransforms(int count)
{
if (count <= 0 || count > MaxBones)
throw new ArgumentOutOfRangeException("count");
Matrix[] bones = bonesParam.GetValueMatrixArray(count);
// Convert matrices from 43 to 44 format.
for (int i = 0; i < bones.Length; i++)
{
bones[i].M44 = 1;
}
return bones;
}
/// <summary>
/// This effect requires lighting, so we explicitly implement
/// IEffectLights.LightingEnabled, and do not allow turning it off.
/// </summary>
bool IEffectLights.LightingEnabled
{
get { return true; }
set { if (!value) throw new NotSupportedException("SkinnedEffect does not support setting LightingEnabled to false."); }
}
#endregion
#region Methods
/// <summary>
/// Creates a new SkinnedEffect with default parameter settings.
/// </summary>
public SkinnedEffect(GraphicsDevice device)
: base(device, Resources.SkinnedEffect)
{
CacheEffectParameters(null);
DirectionalLight0.Enabled = true;
SpecularColor = Vector3.One;
SpecularPower = 16;
Matrix[] identityBones = new Matrix[MaxBones];
for (int i = 0; i < MaxBones; i++)
{
identityBones[i] = Matrix.Identity;
}
SetBoneTransforms(identityBones);
}
/// <summary>
/// Creates a new SkinnedEffect by cloning parameter settings from an existing instance.
/// </summary>
protected SkinnedEffect(SkinnedEffect cloneSource)
: base(cloneSource)
{
CacheEffectParameters(cloneSource);
preferPerPixelLighting = cloneSource.preferPerPixelLighting;
fogEnabled = cloneSource.fogEnabled;
world = cloneSource.world;
view = cloneSource.view;
projection = cloneSource.projection;
diffuseColor = cloneSource.diffuseColor;
emissiveColor = cloneSource.emissiveColor;
ambientLightColor = cloneSource.ambientLightColor;
alpha = cloneSource.alpha;
fogStart = cloneSource.fogStart;
fogEnd = cloneSource.fogEnd;
weightsPerVertex = cloneSource.weightsPerVertex;
}
/// <summary>
/// Creates a clone of the current SkinnedEffect instance.
/// </summary>
public override Effect Clone()
{
return new SkinnedEffect(this);
}
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
public void EnableDefaultLighting()
{
AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2);
}
/// <summary>
/// Looks up shortcut references to our effect parameters.
/// </summary>
void CacheEffectParameters(SkinnedEffect cloneSource)
{
textureParam = Parameters["Texture"];
diffuseColorParam = Parameters["DiffuseColor"];
emissiveColorParam = Parameters["EmissiveColor"];
specularColorParam = Parameters["SpecularColor"];
specularPowerParam = Parameters["SpecularPower"];
eyePositionParam = Parameters["EyePosition"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldParam = Parameters["World"];
worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
worldViewProjParam = Parameters["WorldViewProj"];
bonesParam = Parameters["Bones"];
shaderIndexParam = Parameters["ShaderIndex"];
light0 = new DirectionalLight(Parameters["DirLight0Direction"],
Parameters["DirLight0DiffuseColor"],
Parameters["DirLight0SpecularColor"],
(cloneSource != null) ? cloneSource.light0 : null);
light1 = new DirectionalLight(Parameters["DirLight1Direction"],
Parameters["DirLight1DiffuseColor"],
Parameters["DirLight1SpecularColor"],
(cloneSource != null) ? cloneSource.light1 : null);
light2 = new DirectionalLight(Parameters["DirLight2Direction"],
Parameters["DirLight2DiffuseColor"],
Parameters["DirLight2SpecularColor"],
(cloneSource != null) ? cloneSource.light2 : null);
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected override void OnApply()
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the world inverse transpose and eye position?
dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam);
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Check if we can use the only-bother-with-the-first-light shader optimization.
bool newOneLight = !light1.Enabled && !light2.Enabled;
if (oneLight != newOneLight)
{
oneLight = newOneLight;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (weightsPerVertex == 2)
shaderIndex += 2;
else if (weightsPerVertex == 4)
shaderIndex += 4;
if (preferPerPixelLighting)
shaderIndex += 12;
else if (oneLight)
shaderIndex += 6;
shaderIndexParam.SetValue(shaderIndex);
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
}
}
#endregion
}
}
| |
/* ====================================================================
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.Generic;
using NPOI.POIFS.Common;
using NPOI.Util;
using NPOI.HWPF.Model.IO;
using System.IO;
using NPOI.HWPF.SPRM;
using System;
namespace NPOI.HWPF.Model
{
/**
* This class holds all of the character formatting properties.
*
* @author Ryan Ackley
*/
public class CHPBinTable
{
/** List of character properties.*/
internal List<CHPX> _textRuns = new List<CHPX>();
public CHPBinTable()
{
}
/**
* Constructor used to read a binTable in from a Word document.
*
* @param documentStream
* @param tableStream
* @param offset
* @param size
* @param fcMin
*/
[Obsolete]
public CHPBinTable(byte[] documentStream, byte[] tableStream, int offset,
int size, int fcMin, TextPieceTable tpt):this( documentStream, tableStream, offset, size, tpt )
{
}
/**
* Constructor used to read a binTable in from a Word document.
*/
public CHPBinTable(byte[] documentStream, byte[] tableStream, int offset,
int size, CharIndexTranslator translator)
{
PlexOfCps binTable = new PlexOfCps(tableStream, offset, size, 4);
int length = binTable.Length;
for (int x = 0; x < length; x++)
{
GenericPropertyNode node = binTable.GetProperty(x);
int pageNum = LittleEndian.GetInt(node.Bytes);
int pageOffset = POIFSConstants.SMALLER_BIG_BLOCK_SIZE * pageNum;
CHPFormattedDiskPage cfkp = new CHPFormattedDiskPage(documentStream,
pageOffset, translator);
int fkpSize = cfkp.Size();
for (int y = 0; y < fkpSize; y++)
{
CHPX chpx = cfkp.GetCHPX(y);
if (chpx != null)
_textRuns.Add(chpx);
}
}
}
internal class CHPXToFileComparer : IComparer<CHPX>
{
Dictionary<CHPX, int> list;
public CHPXToFileComparer(Dictionary<CHPX, int> list)
{
this.list = list;
}
#region IComparer<CHPX> Members
public int Compare(CHPX o1, CHPX o2)
{
int i1 = list[o1];
int i2 = list[o2];
return i1.CompareTo(i2);
}
#endregion
}
private static POILogger logger = POILogFactory
.GetLogger(typeof(CHPBinTable));
public void Rebuild(ComplexFileTable complexFileTable)
{
long start = DateTime.Now.Ticks;
if (complexFileTable != null)
{
SprmBuffer[] sprmBuffers = complexFileTable.GetGrpprls();
// adding CHPX from fast-saved SPRMs
foreach (TextPiece textPiece in complexFileTable.GetTextPieceTable()
.TextPieces)
{
PropertyModifier prm = textPiece.PieceDescriptor.Prm;
if (!prm.IsComplex())
continue;
int igrpprl = prm.GetIgrpprl();
if (igrpprl < 0 || igrpprl >= sprmBuffers.Length)
{
logger.Log(POILogger.WARN, textPiece
+ "'s PRM references to unknown grpprl");
continue;
}
bool hasChp = false;
SprmBuffer sprmBuffer = sprmBuffers[igrpprl];
for (SprmIterator iterator = sprmBuffer.Iterator(); ; iterator
.HasNext())
{
SprmOperation sprmOperation = iterator.Next();
if (sprmOperation.Type == SprmOperation.TYPE_CHP)
{
hasChp = true;
break;
}
}
if (hasChp)
{
SprmBuffer newSprmBuffer;
newSprmBuffer = (SprmBuffer)sprmBuffer.Clone();
CHPX chpx = new CHPX(textPiece.Start,
textPiece.End, newSprmBuffer);
_textRuns.Add(chpx);
}
}
logger.Log(POILogger.DEBUG,
"Merged with CHPX from complex file table in ",
DateTime.Now.Ticks - start,
" ms (", _textRuns.Count,
" elements in total)");
start = DateTime.Now.Ticks;
}
List<CHPX> oldChpxSortedByStartPos = new List<CHPX>(_textRuns);
oldChpxSortedByStartPos.Sort(
(IComparer<CHPX>)PropertyNode.CHPXComparator.instance);
logger.Log(POILogger.DEBUG, "CHPX sorted by start position in ",
DateTime.Now.Ticks - start, " ms");
start = DateTime.Now.Ticks;
Dictionary<CHPX, int> chpxToFileOrder = new Dictionary<CHPX, int>();
int counter = 0;
foreach (CHPX chpx in _textRuns)
{
chpxToFileOrder.Add(chpx, counter++);
}
logger.Log(POILogger.DEBUG, "CHPX's order map created in ",
DateTime.Now.Ticks - start, " ms");
start = DateTime.Now.Ticks;
List<int> textRunsBoundariesList;
List<int> textRunsBoundariesSet = new List<int>();
foreach (CHPX chpx in _textRuns)
{
textRunsBoundariesSet.Add(chpx.Start);
textRunsBoundariesSet.Add(chpx.End);
}
textRunsBoundariesSet.Remove(0);
textRunsBoundariesList = new List<int>(
textRunsBoundariesSet);
textRunsBoundariesList.Sort();
logger.Log(POILogger.DEBUG, "Texts CHPX boundaries collected in ",
DateTime.Now.Ticks - start, " ms");
start = DateTime.Now.Ticks;
List<CHPX> newChpxs = new List<CHPX>();
int lastTextRunStart = 0;
foreach (int objBoundary in textRunsBoundariesList)
{
int boundary = objBoundary;
int startInclusive = lastTextRunStart;
int endExclusive = boundary;
lastTextRunStart = endExclusive;
int startPosition = BinarySearch(oldChpxSortedByStartPos, boundary);
startPosition = Math.Abs(startPosition);
while (startPosition >= oldChpxSortedByStartPos.Count)
startPosition--;
while (startPosition > 0
&& oldChpxSortedByStartPos[startPosition].Start >= boundary)
startPosition--;
List<CHPX> chpxs = new List<CHPX>();
for (int c = startPosition; c < oldChpxSortedByStartPos.Count; c++)
{
CHPX chpx = oldChpxSortedByStartPos[c];
if (boundary < chpx.Start)
break;
int left = Math.Max(startInclusive, chpx.Start);
int right = Math.Min(endExclusive, chpx.End);
if (left < right)
{
chpxs.Add(chpx);
}
}
if (chpxs.Count == 0)
{
logger.Log(POILogger.WARN, "Text piece [",
startInclusive, "; ",
endExclusive,
") has no CHPX. Creating new one.");
// create it manually
CHPX chpx = new CHPX(startInclusive, endExclusive,
new SprmBuffer(0));
newChpxs.Add(chpx);
continue;
}
if (chpxs.Count == 1)
{
// can we reuse existing?
CHPX existing = chpxs[0];
if (existing.Start == startInclusive
&& existing.End == endExclusive)
{
newChpxs.Add(existing);
continue;
}
}
CHPXToFileComparer chpxFileOrderComparator = new CHPXToFileComparer(chpxToFileOrder);
chpxs.Sort(chpxFileOrderComparator);
SprmBuffer sprmBuffer = new SprmBuffer(0);
foreach (CHPX chpx in chpxs)
{
sprmBuffer.Append(chpx.GetGrpprl(), 0);
}
CHPX newChpx = new CHPX(startInclusive, endExclusive, sprmBuffer);
newChpxs.Add(newChpx);
continue;
}
this._textRuns = new List<CHPX>(newChpxs);
logger.Log(POILogger.DEBUG, "CHPX rebuilded in ",
DateTime.Now.Ticks - start, " ms (",
_textRuns.Count, " elements)");
start = DateTime.Now.Ticks;
CHPX previous = null;
for (int iterator = _textRuns.Count; iterator != 0; )
{
CHPX current = previous;
previous = _textRuns[--iterator];
if (current == null)
{
continue;
}
if (previous.End == current.Start
&& Arrays
.Equals(previous.GetGrpprl(), current.GetGrpprl()))
{
previous.End = current.End;
_textRuns.Remove(current);
continue;
}
previous = current;
}
logger.Log(POILogger.DEBUG, "CHPX compacted in ",
DateTime.Now.Ticks - start, " ms (",
_textRuns.Count, " elements)");
}
private static int BinarySearch(List<CHPX> chpxs, int startPosition)
{
int low = 0;
int high = chpxs.Count - 1;
while (low <= high)
{
int mid = (low + high) >> 1;
CHPX midVal = chpxs[mid];
int midValue = midVal.Start;
if (midValue < startPosition)
low = mid + 1;
else if (midValue > startPosition)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public void AdjustForDelete(int listIndex, int offset, int Length)
{
int size = _textRuns.Count;
int endMark = offset + Length;
int endIndex = listIndex;
CHPX chpx = _textRuns[endIndex];
while (chpx.End < endMark)
{
chpx = _textRuns[++endIndex];
}
if (listIndex == endIndex)
{
chpx = _textRuns[endIndex];
chpx.End = ((chpx.End - endMark) + offset);
}
else
{
chpx = _textRuns[listIndex];
chpx.End = (offset);
for (int x = listIndex + 1; x < endIndex; x++)
{
chpx = _textRuns[x];
chpx.Start = (offset);
chpx.End = (offset);
}
chpx = _textRuns[endIndex];
chpx.End = ((chpx.End - endMark) + offset);
}
for (int x = endIndex + 1; x < size; x++)
{
chpx = _textRuns[x];
chpx.Start = (chpx.Start - Length);
chpx.End = (chpx.End - Length);
}
}
public void Insert(int listIndex, int cpStart, SprmBuffer buf)
{
CHPX insertChpx = new CHPX(0, 0, buf);
// Ensure character OffSets are really characters
insertChpx.Start = (cpStart);
insertChpx.End = (cpStart);
if (listIndex == _textRuns.Count)
{
_textRuns.Add(insertChpx);
}
else
{
CHPX chpx = _textRuns[listIndex];
if (chpx.Start < cpStart)
{
// Copy the properties of the one before to afterwards
// Will go:
// Original, until insert at point
// New one
// Clone of original, on to the old end
CHPX clone = new CHPX(0, 0, chpx.GetSprmBuf());
// Again ensure Contains character based OffSets no matter what
clone.Start = (cpStart);
clone.End = (chpx.End);
chpx.End = (cpStart);
_textRuns.Insert(listIndex + 1, insertChpx);
_textRuns.Insert(listIndex + 2, clone);
}
else
{
_textRuns.Insert(listIndex, insertChpx);
}
}
}
public void AdjustForInsert(int listIndex, int Length)
{
int size = _textRuns.Count;
CHPX chpx = _textRuns[listIndex];
chpx.End = (chpx.End + Length);
for (int x = listIndex + 1; x < size; x++)
{
chpx = _textRuns[x];
chpx.Start = (chpx.Start + Length);
chpx.End = (chpx.End + Length);
}
}
public List<CHPX> GetTextRuns()
{
return _textRuns;
}
public void WriteTo(HWPFFileSystem sys, int fcMin)
{
HWPFStream docStream = sys.GetStream("WordDocument");
Stream tableStream = sys.GetStream("1Table");
PlexOfCps binTable = new PlexOfCps(4);
// each FKP must start on a 512 byte page.
int docOffset = docStream.Offset;
int mod = docOffset % POIFSConstants.SMALLER_BIG_BLOCK_SIZE;
if (mod != 0)
{
byte[] pAdding = new byte[POIFSConstants.SMALLER_BIG_BLOCK_SIZE - mod];
docStream.Write(pAdding);
}
// get the page number for the first fkp
docOffset = docStream.Offset;
int pageNum = docOffset / POIFSConstants.SMALLER_BIG_BLOCK_SIZE;
// get the ending fc
int endingFc = ((PropertyNode)_textRuns[_textRuns.Count - 1]).End;
endingFc += fcMin;
List<CHPX> overflow = _textRuns;
do
{
PropertyNode startingProp = (PropertyNode)overflow[0];
int start = startingProp.Start + fcMin;
CHPFormattedDiskPage cfkp = new CHPFormattedDiskPage();
cfkp.Fill(overflow);
byte[] bufFkp = cfkp.ToArray(fcMin);
docStream.Write(bufFkp);
overflow = cfkp.GetOverflow();
int end = endingFc;
if (overflow != null)
{
end = ((PropertyNode)overflow[0]).Start + fcMin;
}
byte[] intHolder = new byte[4];
LittleEndian.PutInt(intHolder, pageNum++);
binTable.AddProperty(new GenericPropertyNode(start, end, intHolder));
}
while (overflow != null);
byte[] bytes = binTable.ToByteArray();
tableStream.Write(bytes, 0, bytes.Length);
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// FixedMaxHeap.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// Very simple heap data structure, of fixed size.
/// </summary>
/// <typeparam name="TElement"></typeparam>
internal class FixedMaxHeap<TElement>
{
private readonly TElement[] _elements; // Element array.
private int _count; // Current count.
private readonly IComparer<TElement> _comparer; // Element comparison routine.
//-----------------------------------------------------------------------------------
// Create a new heap with the specified maximum size.
//
internal FixedMaxHeap(int maximumSize)
: this(maximumSize, Util.GetDefaultComparer<TElement>())
{
}
internal FixedMaxHeap(int maximumSize, IComparer<TElement> comparer)
{
Debug.Assert(comparer != null);
_elements = new TElement[maximumSize];
_comparer = comparer;
}
//-----------------------------------------------------------------------------------
// Retrieve the count (i.e. how many elements are in the heap).
//
internal int Count
{
get { return _count; }
}
//-----------------------------------------------------------------------------------
// Retrieve the size (i.e. the maximum size of the heap).
//
internal int Size
{
get { return _elements.Length; }
}
//-----------------------------------------------------------------------------------
// Get the current maximum value in the max-heap.
//
// Note: The heap stores the maximumSize smallest elements that were inserted.
// So, if the heap is full, the value returned is the maximumSize-th smallest
// element that was inserted into the heap.
//
internal TElement MaxValue
{
get
{
if (_count == 0)
{
throw new InvalidOperationException(SR.NoElements);
}
// The maximum element is in the 0th position.
return _elements[0];
}
}
//-----------------------------------------------------------------------------------
// Removes all elements from the heap.
//
internal void Clear()
{
_count = 0;
}
//-----------------------------------------------------------------------------------
// Inserts the new element, maintaining the heap property.
//
// Return Value:
// If the element is greater than the current max element, this function returns
// false without modifying the heap. Otherwise, it returns true.
//
internal bool Insert(TElement e)
{
if (_count < _elements.Length)
{
// There is room. We can add it and then max-heapify.
_elements[_count] = e;
_count++;
HeapifyLastLeaf();
return true;
}
else
{
// No more room. The element might not even fit in the heap. The check
// is simple: if it's greater than the maximum element, then it can't be
// inserted. Otherwise, we replace the head with it and reheapify.
if (_comparer.Compare(e, _elements[0]) < 0)
{
_elements[0] = e;
HeapifyRoot();
return true;
}
return false;
}
}
//-----------------------------------------------------------------------------------
// Replaces the maximum value in the heap with the user-provided value, and restores
// the heap property.
//
internal void ReplaceMax(TElement newValue)
{
Debug.Assert(_count > 0);
_elements[0] = newValue;
HeapifyRoot();
}
//-----------------------------------------------------------------------------------
// Removes the maximum value from the heap, and restores the heap property.
//
internal void RemoveMax()
{
Debug.Assert(_count > 0);
_count--;
if (_count > 0)
{
_elements[0] = _elements[_count];
HeapifyRoot();
}
}
//-----------------------------------------------------------------------------------
// Private helpers to swap elements, and to reheapify starting from the root or
// from a leaf element, depending on what is needed.
//
private void Swap(int i, int j)
{
TElement tmpElement = _elements[i];
_elements[i] = _elements[j];
_elements[j] = tmpElement;
}
private void HeapifyRoot()
{
// We are heapifying from the head of the list.
int i = 0;
int n = _count;
while (i < n)
{
// Calculate the current child node indexes.
int n0 = ((i + 1) * 2) - 1;
int n1 = n0 + 1;
if (n0 < n && _comparer.Compare(_elements[i], _elements[n0]) < 0)
{
// We have to select the bigger of the two subtrees, and float
// the current element down. This maintains the max-heap property.
if (n1 < n && _comparer.Compare(_elements[n0], _elements[n1]) < 0)
{
Swap(i, n1);
i = n1;
}
else
{
Swap(i, n0);
i = n0;
}
}
else if (n1 < n && _comparer.Compare(_elements[i], _elements[n1]) < 0)
{
// Float down the "right" subtree. We needn't compare this subtree
// to the "left", because if the element was smaller than that, the
// first if statement's predicate would have evaluated to true.
Swap(i, n1);
i = n1;
}
else
{
// Else, the current key is in its final position. Break out
// of the current loop and return.
break;
}
}
}
private void HeapifyLastLeaf()
{
int i = _count - 1;
while (i > 0)
{
int j = ((i + 1) / 2) - 1;
if (_comparer.Compare(_elements[i], _elements[j]) > 0)
{
Swap(i, j);
i = j;
}
else
{
break;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Esthar.Core;
namespace Esthar.UI
{
/// <summary>
/// Interaction logic for FontChooser.xaml
/// </summary>
public partial class FontChooser
{
#region Private fields and types
private ICollection<FontFamily> _familyCollection; // see FamilyCollection property
private string _defaultSampleText;
private string _previewSampleText;
private string _pointsText;
private bool _updatePending; // indicates a call to OnUpdate is scheduled
private bool _familyListValid; // indicates the list of font families is valid
private bool _typefaceListValid; // indicates the list of typefaces is valid
private bool _typefaceListSelectionValid; // indicates the current selection in the typeface list is valid
private bool _previewValid; // indicates the preview control is valid
private Dictionary<TabItem, TabState> _tabDictionary; // state and logic for each tab
private DependencyProperty _currentFeature;
private TypographyFeaturePage _currentFeaturePage;
private static readonly double[] CommonlyUsedFontSizes = new double[]
{
3.0, 4.0, 5.0, 6.0, 6.5,
7.0, 7.5, 8.0, 8.5, 9.0,
9.5, 10.0, 10.5, 11.0, 11.5,
12.0, 12.5, 13.0, 13.5, 14.0,
15.0, 16.0, 17.0, 18.0, 19.0,
20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 38.0,
40.0, 44.0, 48.0, 52.0, 56.0, 60.0, 64.0, 68.0, 72.0, 76.0,
80.0, 88.0, 96.0, 104.0, 112.0, 120.0, 128.0, 136.0, 144.0
};
// Specialized metadata object for font chooser dependency properties
private class FontPropertyMetadata : FrameworkPropertyMetadata
{
public readonly DependencyProperty TargetProperty;
public FontPropertyMetadata(
object defaultValue,
PropertyChangedCallback changeCallback,
DependencyProperty targetProperty
)
: base(defaultValue, changeCallback)
{
TargetProperty = targetProperty;
}
}
// Specialized metadata object for typographic font chooser properties
private class TypographicPropertyMetadata : FontPropertyMetadata
{
public TypographicPropertyMetadata(object defaultValue, DependencyProperty targetProperty, TypographyFeaturePage featurePage, string sampleTextTag)
: base(defaultValue, _callback, targetProperty)
{
FeaturePage = featurePage;
SampleTextTag = sampleTextTag;
}
public readonly TypographyFeaturePage FeaturePage;
public readonly string SampleTextTag;
private static PropertyChangedCallback _callback = new PropertyChangedCallback(
FontChooser.TypographicPropertyChangedCallback
);
}
// Object used to initialize the right-hand side of the typographic properties tab
private class TypographyFeaturePage
{
public TypographyFeaturePage(Item[] items)
{
Items = items;
}
public TypographyFeaturePage(Type enumType)
{
string[] names = Enum.GetNames(enumType);
Array values = Enum.GetValues(enumType);
Items = new Item[names.Length];
for (int i = 0; i < names.Length; ++i)
{
Items[i] = new Item(names[i], values.GetValue(i));
}
}
public static readonly TypographyFeaturePage BooleanFeaturePage = new TypographyFeaturePage(
new Item[] {
new Item("Disabled", false),
new Item("Enabled", true)
}
);
public static readonly TypographyFeaturePage IntegerFeaturePage = new TypographyFeaturePage(
new Item[] {
new Item("_0", 0),
new Item("_1", 1),
new Item("_2", 2),
new Item("_3", 3),
new Item("_4", 4),
new Item("_5", 5),
new Item("_6", 6),
new Item("_7", 7),
new Item("_8", 8),
new Item("_9", 9)
}
);
public struct Item
{
public Item(string tag, object value)
{
Tag = tag;
Value = value;
}
public readonly string Tag;
public readonly object Value;
}
public readonly Item[] Items;
}
private delegate void UpdateCallback();
// Encapsulates the state and initialization logic of a tab control item.
private class TabState
{
public TabState(UpdateCallback initMethod)
{
InitializeTab = initMethod;
}
public bool IsValid = false;
public readonly UpdateCallback InitializeTab;
}
#endregion
#region Construction and initialization
public FontChooser()
{
InitializeComponent();
Loaded += OnLoaded;
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
_previewSampleText = _defaultSampleText = previewTextBox.Text;
_pointsText = typefaceNameRun.Text;
// Hook up events for the font family list and associated text box.
fontFamilyTextBox.SelectionChanged += new RoutedEventHandler(fontFamilyTextBox_SelectionChanged);
fontFamilyTextBox.TextChanged += new TextChangedEventHandler(fontFamilyTextBox_TextChanged);
fontFamilyTextBox.PreviewKeyDown += new KeyEventHandler(fontFamilyTextBox_PreviewKeyDown);
fontFamilyList.SelectionChanged += new SelectionChangedEventHandler(fontFamilyList_SelectionChanged);
// Hook up events for the typeface list.
typefaceList.SelectionChanged += new SelectionChangedEventHandler(typefaceList_SelectionChanged);
// Hook up events for the font size list and associated text box.
sizeTextBox.TextChanged += new TextChangedEventHandler(sizeTextBox_TextChanged);
sizeTextBox.PreviewKeyDown += new KeyEventHandler(sizeTextBox_PreviewKeyDown);
sizeList.SelectionChanged += new SelectionChangedEventHandler(sizeList_SelectionChanged);
// Hook up events for text decoration check boxes.
RoutedEventHandler textDecorationEventHandler = new RoutedEventHandler(textDecorationCheckStateChanged);
underlineCheckBox.Checked += textDecorationEventHandler;
underlineCheckBox.Unchecked += textDecorationEventHandler;
baselineCheckBox.Checked += textDecorationEventHandler;
baselineCheckBox.Unchecked += textDecorationEventHandler;
strikethroughCheckBox.Checked += textDecorationEventHandler;
strikethroughCheckBox.Unchecked += textDecorationEventHandler;
overlineCheckBox.Checked += textDecorationEventHandler;
overlineCheckBox.Unchecked += textDecorationEventHandler;
// Initialize the dictionary that maps tab control items to handler objects.
_tabDictionary = new Dictionary<TabItem, TabState>(tabControl.Items.Count);
_tabDictionary.Add(samplesTab, new TabState(new UpdateCallback(InitializeSamplesTab)));
_tabDictionary.Add(typographyTab, new TabState(new UpdateCallback(InitializeTypographyTab)));
_tabDictionary.Add(descriptiveTextTab, new TabState(new UpdateCallback(InitializeDescriptiveTextTab)));
// Hook up events for the tab control.
tabControl.SelectionChanged += new SelectionChangedEventHandler(tabControl_SelectionChanged);
// Initialize the list of font sizes and select the nearest size.
foreach (double value in CommonlyUsedFontSizes)
{
sizeList.Items.Add(new FontSizeListItem(value));
}
OnSelectedFontSizeChanged(SelectedFontSize);
// Initialize the font family list and the current family.
if (!_familyListValid)
{
InitializeFontFamilyList();
_familyListValid = true;
OnSelectedFontFamilyChanged(SelectedFontFamily);
}
// Schedule background updates.
ScheduleUpdate();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (FontDescriptor.TextDecorations.CanFreeze)
FontDescriptor.TextDecorations.Freeze();
if (FontDescriptor != null)
{
SelectedFontFamily = FontDescriptor.FontFamily;
SelectedFontWeight = FontDescriptor.FontWeight;
SelectedFontStyle = FontDescriptor.FontStyle;
SelectedFontStretch = FontDescriptor.FontStretch;
SelectedTextDecorations = FontDescriptor.TextDecorations;
SelectedFontSize = FontDescriptor.FontSize;
}
}
#endregion
#region Event handlers
private void OnOKButtonClicked(object sender, RoutedEventArgs e)
{
FontDescriptor = new FontDescriptor
{
FontFamily = SelectedFontFamily,
FontWeight = SelectedFontWeight,
FontStyle = SelectedFontStyle,
FontStretch = SelectedFontStretch,
TextDecorations = SelectedTextDecorations,
FontSize = SelectedFontSize
};
this.DialogResult = true;
this.Close();
}
private void OnCancelButtonClicked(object sender, RoutedEventArgs e)
{
this.Close();
}
private int _fontFamilyTextBoxSelectionStart;
private void fontFamilyTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
_fontFamilyTextBoxSelectionStart = fontFamilyTextBox.SelectionStart;
}
private void fontFamilyTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string text = fontFamilyTextBox.Text;
// Update the current list item.
if (SelectFontFamilyListItem(text) == null)
{
// The text does not exactly match a family name so consider applying auto-complete behavior.
// However, only do so if the following conditions are met:
// (1) The user is typing more text rather than deleting (i.e., the new text length is
// greater than the most recent selection start index), and
// (2) The caret is at the end of the text box.
if (text.Length > _fontFamilyTextBoxSelectionStart
&& fontFamilyTextBox.SelectionStart == text.Length)
{
// Get the current list item, which should be the nearest match for the text.
FontFamilyListItem item = fontFamilyList.Items.CurrentItem as FontFamilyListItem;
if (item != null)
{
// Does the text box text match the beginning of the family name?
string familyDisplayName = item.ToString();
if (string.Compare(text, 0, familyDisplayName, 0, text.Length, true, CultureInfo.CurrentCulture) == 0)
{
// Set the text box text to the complete family name and select the part not typed in.
fontFamilyTextBox.Text = familyDisplayName;
fontFamilyTextBox.SelectionStart = text.Length;
fontFamilyTextBox.SelectionLength = familyDisplayName.Length - text.Length;
}
}
}
}
}
private void sizeTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
double sizeInPoints;
if (double.TryParse(sizeTextBox.Text, out sizeInPoints))
{
double sizeInPixels = FontSizeListItem.PointsToPixels(sizeInPoints);
if (!FontSizeListItem.FuzzyEqual(sizeInPixels, SelectedFontSize))
{
SelectedFontSize = sizeInPixels;
}
}
}
private void fontFamilyTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
OnComboBoxPreviewKeyDown(fontFamilyTextBox, fontFamilyList, e);
}
private void sizeTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
OnComboBoxPreviewKeyDown(sizeTextBox, sizeList, e);
}
private void fontFamilyList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FontFamilyListItem item = fontFamilyList.SelectedItem as FontFamilyListItem;
if (item != null)
{
SelectedFontFamily = item.FontFamily;
}
}
private void sizeList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FontSizeListItem item = sizeList.SelectedItem as FontSizeListItem;
if (item != null)
{
SelectedFontSize = item.SizeInPixels;
}
}
private void typefaceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TypefaceListItem item = typefaceList.SelectedItem as TypefaceListItem;
if (item != null)
{
SelectedFontWeight = item.FontWeight;
SelectedFontStyle = item.FontStyle;
SelectedFontStretch = item.FontStretch;
}
}
private void textDecorationCheckStateChanged(object sender, RoutedEventArgs e)
{
TextDecorationCollection textDecorations = new TextDecorationCollection();
if (underlineCheckBox.IsChecked.Value)
{
textDecorations.Add(TextDecorations.Underline[0]);
}
if (baselineCheckBox.IsChecked.Value)
{
textDecorations.Add(TextDecorations.Baseline[0]);
}
if (strikethroughCheckBox.IsChecked.Value)
{
textDecorations.Add(TextDecorations.Strikethrough[0]);
}
if (overlineCheckBox.IsChecked.Value)
{
textDecorations.Add(TextDecorations.OverLine[0]);
}
textDecorations.Freeze();
SelectedTextDecorations = textDecorations;
}
private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabState tab = CurrentTabState;
if (tab != null && !tab.IsValid)
{
tab.InitializeTab();
tab.IsValid = true;
}
}
private void featureList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
InitializeTypographyTab();
}
#endregion
#region Public properties and methods
/// <summary>
/// Collection of font families to display in the font family list. By default this is Fonts.SystemFontFamilies,
/// but a client could set this to another collection returned by Fonts.GetFontFamilies, e.g., a collection of
/// application-defined fonts.
/// </summary>
public ICollection<FontFamily> FontFamilyCollection
{
get
{
return (_familyCollection == null) ? Fonts.SystemFontFamilies : _familyCollection;
}
set
{
if (value != _familyCollection)
{
_familyCollection = value;
InvalidateFontFamilyList();
}
}
}
/// <summary>
/// Sets the font chooser selection properties to match the properites of the specified object.
/// </summary>
public void SetPropertiesFromObject(DependencyObject obj)
{
foreach (DependencyProperty property in _chooserProperties)
{
FontPropertyMetadata metadata = property.GetMetadata(typeof(FontChooser)) as FontPropertyMetadata;
if (metadata != null)
{
this.SetValue(property, obj.GetValue(metadata.TargetProperty));
}
}
}
/// <summary>
/// Sets the properites of the specified object to match the font chooser selection properties.
/// </summary>
public void ApplyPropertiesToObject(DependencyObject obj)
{
foreach (DependencyProperty property in _chooserProperties)
{
FontPropertyMetadata metadata = property.GetMetadata(typeof(FontChooser)) as FontPropertyMetadata;
if (metadata != null)
{
obj.SetValue(metadata.TargetProperty, this.GetValue(property));
}
}
}
private void ApplyPropertiesToObjectExcept(DependencyObject obj, DependencyProperty except)
{
foreach (DependencyProperty property in _chooserProperties)
{
if (property != except)
{
FontPropertyMetadata metadata = property.GetMetadata(typeof(FontChooser)) as FontPropertyMetadata;
if (metadata != null)
{
obj.SetValue(metadata.TargetProperty, this.GetValue(property));
}
}
}
}
/// <summary>
/// Sample text used in the preview box and family and typeface samples tab.
/// </summary>
public string PreviewSampleText
{
get
{
return _previewSampleText;
}
set
{
string newValue = string.IsNullOrEmpty(value) ? _defaultSampleText : value;
if (newValue != _previewSampleText)
{
_previewSampleText = newValue;
// Update the preview text box.
previewTextBox.Text = newValue;
// The preview sample text is also used in the family and typeface samples tab.
InvalidateTab(samplesTab);
}
}
}
public FontDescriptor FontDescriptor { get; set; }
#endregion
#region Dependency properties for typographic features
public static readonly DependencyProperty StandardLigaturesProperty = RegisterTypographicProperty(Typography.StandardLigaturesProperty);
public bool StandardLigatures
{
get { return (bool)GetValue(StandardLigaturesProperty); }
set { SetValue(StandardLigaturesProperty, value); }
}
public static readonly DependencyProperty ContextualLigaturesProperty = RegisterTypographicProperty(Typography.ContextualLigaturesProperty);
public bool ContextualLigatures
{
get { return (bool)GetValue(ContextualLigaturesProperty); }
set { SetValue(ContextualLigaturesProperty, value); }
}
public static readonly DependencyProperty DiscretionaryLigaturesProperty = RegisterTypographicProperty(Typography.DiscretionaryLigaturesProperty);
public bool DiscretionaryLigatures
{
get { return (bool)GetValue(DiscretionaryLigaturesProperty); }
set { SetValue(DiscretionaryLigaturesProperty, value); }
}
public static readonly DependencyProperty HistoricalLigaturesProperty = RegisterTypographicProperty(Typography.HistoricalLigaturesProperty);
public bool HistoricalLigatures
{
get { return (bool)GetValue(HistoricalLigaturesProperty); }
set { SetValue(HistoricalLigaturesProperty, value); }
}
public static readonly DependencyProperty ContextualAlternatesProperty = RegisterTypographicProperty(Typography.ContextualAlternatesProperty);
public bool ContextualAlternates
{
get { return (bool)GetValue(ContextualAlternatesProperty); }
set { SetValue(ContextualAlternatesProperty, value); }
}
public static readonly DependencyProperty HistoricalFormsProperty = RegisterTypographicProperty(Typography.HistoricalFormsProperty);
public bool HistoricalForms
{
get { return (bool)GetValue(HistoricalFormsProperty); }
set { SetValue(HistoricalFormsProperty, value); }
}
public static readonly DependencyProperty KerningProperty = RegisterTypographicProperty(Typography.KerningProperty);
public bool Kerning
{
get { return (bool)GetValue(KerningProperty); }
set { SetValue(KerningProperty, value); }
}
public static readonly DependencyProperty CapitalSpacingProperty = RegisterTypographicProperty(Typography.CapitalSpacingProperty);
public bool CapitalSpacing
{
get { return (bool)GetValue(CapitalSpacingProperty); }
set { SetValue(CapitalSpacingProperty, value); }
}
public static readonly DependencyProperty CaseSensitiveFormsProperty = RegisterTypographicProperty(Typography.CaseSensitiveFormsProperty);
public bool CaseSensitiveForms
{
get { return (bool)GetValue(CaseSensitiveFormsProperty); }
set { SetValue(CaseSensitiveFormsProperty, value); }
}
public static readonly DependencyProperty StylisticSet1Property = RegisterTypographicProperty(Typography.StylisticSet1Property);
public bool StylisticSet1
{
get { return (bool)GetValue(StylisticSet1Property); }
set { SetValue(StylisticSet1Property, value); }
}
public static readonly DependencyProperty StylisticSet2Property = RegisterTypographicProperty(Typography.StylisticSet2Property);
public bool StylisticSet2
{
get { return (bool)GetValue(StylisticSet2Property); }
set { SetValue(StylisticSet2Property, value); }
}
public static readonly DependencyProperty StylisticSet3Property = RegisterTypographicProperty(Typography.StylisticSet3Property);
public bool StylisticSet3
{
get { return (bool)GetValue(StylisticSet3Property); }
set { SetValue(StylisticSet3Property, value); }
}
public static readonly DependencyProperty StylisticSet4Property = RegisterTypographicProperty(Typography.StylisticSet4Property);
public bool StylisticSet4
{
get { return (bool)GetValue(StylisticSet4Property); }
set { SetValue(StylisticSet4Property, value); }
}
public static readonly DependencyProperty StylisticSet5Property = RegisterTypographicProperty(Typography.StylisticSet5Property);
public bool StylisticSet5
{
get { return (bool)GetValue(StylisticSet5Property); }
set { SetValue(StylisticSet5Property, value); }
}
public static readonly DependencyProperty StylisticSet6Property = RegisterTypographicProperty(Typography.StylisticSet6Property);
public bool StylisticSet6
{
get { return (bool)GetValue(StylisticSet6Property); }
set { SetValue(StylisticSet6Property, value); }
}
public static readonly DependencyProperty StylisticSet7Property = RegisterTypographicProperty(Typography.StylisticSet7Property);
public bool StylisticSet7
{
get { return (bool)GetValue(StylisticSet7Property); }
set { SetValue(StylisticSet7Property, value); }
}
public static readonly DependencyProperty StylisticSet8Property = RegisterTypographicProperty(Typography.StylisticSet8Property);
public bool StylisticSet8
{
get { return (bool)GetValue(StylisticSet8Property); }
set { SetValue(StylisticSet8Property, value); }
}
public static readonly DependencyProperty StylisticSet9Property = RegisterTypographicProperty(Typography.StylisticSet9Property);
public bool StylisticSet9
{
get { return (bool)GetValue(StylisticSet9Property); }
set { SetValue(StylisticSet9Property, value); }
}
public static readonly DependencyProperty StylisticSet10Property = RegisterTypographicProperty(Typography.StylisticSet10Property);
public bool StylisticSet10
{
get { return (bool)GetValue(StylisticSet10Property); }
set { SetValue(StylisticSet10Property, value); }
}
public static readonly DependencyProperty StylisticSet11Property = RegisterTypographicProperty(Typography.StylisticSet11Property);
public bool StylisticSet11
{
get { return (bool)GetValue(StylisticSet11Property); }
set { SetValue(StylisticSet11Property, value); }
}
public static readonly DependencyProperty StylisticSet12Property = RegisterTypographicProperty(Typography.StylisticSet12Property);
public bool StylisticSet12
{
get { return (bool)GetValue(StylisticSet12Property); }
set { SetValue(StylisticSet12Property, value); }
}
public static readonly DependencyProperty StylisticSet13Property = RegisterTypographicProperty(Typography.StylisticSet13Property);
public bool StylisticSet13
{
get { return (bool)GetValue(StylisticSet13Property); }
set { SetValue(StylisticSet13Property, value); }
}
public static readonly DependencyProperty StylisticSet14Property = RegisterTypographicProperty(Typography.StylisticSet14Property);
public bool StylisticSet14
{
get { return (bool)GetValue(StylisticSet14Property); }
set { SetValue(StylisticSet14Property, value); }
}
public static readonly DependencyProperty StylisticSet15Property = RegisterTypographicProperty(Typography.StylisticSet15Property);
public bool StylisticSet15
{
get { return (bool)GetValue(StylisticSet15Property); }
set { SetValue(StylisticSet15Property, value); }
}
public static readonly DependencyProperty StylisticSet16Property = RegisterTypographicProperty(Typography.StylisticSet16Property);
public bool StylisticSet16
{
get { return (bool)GetValue(StylisticSet16Property); }
set { SetValue(StylisticSet16Property, value); }
}
public static readonly DependencyProperty StylisticSet17Property = RegisterTypographicProperty(Typography.StylisticSet17Property);
public bool StylisticSet17
{
get { return (bool)GetValue(StylisticSet17Property); }
set { SetValue(StylisticSet17Property, value); }
}
public static readonly DependencyProperty StylisticSet18Property = RegisterTypographicProperty(Typography.StylisticSet18Property);
public bool StylisticSet18
{
get { return (bool)GetValue(StylisticSet18Property); }
set { SetValue(StylisticSet18Property, value); }
}
public static readonly DependencyProperty StylisticSet19Property = RegisterTypographicProperty(Typography.StylisticSet19Property);
public bool StylisticSet19
{
get { return (bool)GetValue(StylisticSet19Property); }
set { SetValue(StylisticSet19Property, value); }
}
public static readonly DependencyProperty StylisticSet20Property = RegisterTypographicProperty(Typography.StylisticSet20Property);
public bool StylisticSet20
{
get { return (bool)GetValue(StylisticSet20Property); }
set { SetValue(StylisticSet20Property, value); }
}
public static readonly DependencyProperty SlashedZeroProperty = RegisterTypographicProperty(Typography.SlashedZeroProperty, "Digits");
public bool SlashedZero
{
get { return (bool)GetValue(SlashedZeroProperty); }
set { SetValue(SlashedZeroProperty, value); }
}
public static readonly DependencyProperty MathematicalGreekProperty = RegisterTypographicProperty(Typography.MathematicalGreekProperty);
public bool MathematicalGreek
{
get { return (bool)GetValue(MathematicalGreekProperty); }
set { SetValue(MathematicalGreekProperty, value); }
}
public static readonly DependencyProperty EastAsianExpertFormsProperty = RegisterTypographicProperty(Typography.EastAsianExpertFormsProperty);
public bool EastAsianExpertForms
{
get { return (bool)GetValue(EastAsianExpertFormsProperty); }
set { SetValue(EastAsianExpertFormsProperty, value); }
}
public static readonly DependencyProperty FractionProperty = RegisterTypographicProperty(Typography.FractionProperty, "OneHalf");
public FontFraction Fraction
{
get { return (FontFraction)GetValue(FractionProperty); }
set { SetValue(FractionProperty, value); }
}
public static readonly DependencyProperty VariantsProperty = RegisterTypographicProperty(Typography.VariantsProperty);
public FontVariants Variants
{
get { return (FontVariants)GetValue(VariantsProperty); }
set { SetValue(VariantsProperty, value); }
}
public static readonly DependencyProperty CapitalsProperty = RegisterTypographicProperty(Typography.CapitalsProperty);
public FontCapitals Capitals
{
get { return (FontCapitals)GetValue(CapitalsProperty); }
set { SetValue(CapitalsProperty, value); }
}
public static readonly DependencyProperty NumeralStyleProperty = RegisterTypographicProperty(Typography.NumeralStyleProperty, "Digits");
public FontNumeralStyle NumeralStyle
{
get { return (FontNumeralStyle)GetValue(NumeralStyleProperty); }
set { SetValue(NumeralStyleProperty, value); }
}
public static readonly DependencyProperty NumeralAlignmentProperty = RegisterTypographicProperty(Typography.NumeralAlignmentProperty, "Digits");
public FontNumeralAlignment NumeralAlignment
{
get { return (FontNumeralAlignment)GetValue(NumeralAlignmentProperty); }
set { SetValue(NumeralAlignmentProperty, value); }
}
public static readonly DependencyProperty EastAsianWidthsProperty = RegisterTypographicProperty(Typography.EastAsianWidthsProperty);
public FontEastAsianWidths EastAsianWidths
{
get { return (FontEastAsianWidths)GetValue(EastAsianWidthsProperty); }
set { SetValue(EastAsianWidthsProperty, value); }
}
public static readonly DependencyProperty EastAsianLanguageProperty = RegisterTypographicProperty(Typography.EastAsianLanguageProperty);
public FontEastAsianLanguage EastAsianLanguage
{
get { return (FontEastAsianLanguage)GetValue(EastAsianLanguageProperty); }
set { SetValue(EastAsianLanguageProperty, value); }
}
public static readonly DependencyProperty AnnotationAlternatesProperty = RegisterTypographicProperty(Typography.AnnotationAlternatesProperty);
public int AnnotationAlternates
{
get { return (int)GetValue(AnnotationAlternatesProperty); }
set { SetValue(AnnotationAlternatesProperty, value); }
}
public static readonly DependencyProperty StandardSwashesProperty = RegisterTypographicProperty(Typography.StandardSwashesProperty);
public int StandardSwashes
{
get { return (int)GetValue(StandardSwashesProperty); }
set { SetValue(StandardSwashesProperty, value); }
}
public static readonly DependencyProperty ContextualSwashesProperty = RegisterTypographicProperty(Typography.ContextualSwashesProperty);
public int ContextualSwashes
{
get { return (int)GetValue(ContextualSwashesProperty); }
set { SetValue(ContextualSwashesProperty, value); }
}
public static readonly DependencyProperty StylisticAlternatesProperty = RegisterTypographicProperty(Typography.StylisticAlternatesProperty);
public int StylisticAlternates
{
get { return (int)GetValue(StylisticAlternatesProperty); }
set { SetValue(StylisticAlternatesProperty, value); }
}
private static void TypographicPropertyChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
FontChooser chooser = obj as FontChooser;
if (chooser != null)
{
chooser.InvalidatePreview();
}
}
#endregion
#region Other dependency properties
public static readonly DependencyProperty SelectedFontFamilyProperty = RegisterFontProperty(
"SelectedFontFamily",
TextBlock.FontFamilyProperty,
new PropertyChangedCallback(SelectedFontFamilyChangedCallback)
);
public FontFamily SelectedFontFamily
{
get { return GetValue(SelectedFontFamilyProperty) as FontFamily; }
set { SetValue(SelectedFontFamilyProperty, value); }
}
static void SelectedFontFamilyChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((FontChooser)obj).OnSelectedFontFamilyChanged(e.NewValue as FontFamily);
}
public static readonly DependencyProperty SelectedFontWeightProperty = RegisterFontProperty(
"SelectedFontWeight",
TextBlock.FontWeightProperty,
new PropertyChangedCallback(SelectedTypefaceChangedCallback)
);
public FontWeight SelectedFontWeight
{
get { return (FontWeight)GetValue(SelectedFontWeightProperty); }
set { SetValue(SelectedFontWeightProperty, value); }
}
public static readonly DependencyProperty SelectedFontStyleProperty = RegisterFontProperty(
"SelectedFontStyle",
TextBlock.FontStyleProperty,
new PropertyChangedCallback(SelectedTypefaceChangedCallback)
);
public FontStyle SelectedFontStyle
{
get { return (FontStyle)GetValue(SelectedFontStyleProperty); }
set { SetValue(SelectedFontStyleProperty, value); }
}
public static readonly DependencyProperty SelectedFontStretchProperty = RegisterFontProperty(
"SelectedFontStretch",
TextBlock.FontStretchProperty,
new PropertyChangedCallback(SelectedTypefaceChangedCallback)
);
public FontStretch SelectedFontStretch
{
get { return (FontStretch)GetValue(SelectedFontStretchProperty); }
set { SetValue(SelectedFontStretchProperty, value); }
}
static void SelectedTypefaceChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((FontChooser)obj).InvalidateTypefaceListSelection();
}
public static readonly DependencyProperty SelectedFontSizeProperty = RegisterFontProperty(
"SelectedFontSize",
TextBlock.FontSizeProperty,
new PropertyChangedCallback(SelectedFontSizeChangedCallback)
);
public double SelectedFontSize
{
get { return (double)GetValue(SelectedFontSizeProperty); }
set { SetValue(SelectedFontSizeProperty, value); }
}
private static void SelectedFontSizeChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((FontChooser)obj).OnSelectedFontSizeChanged((double)(e.NewValue));
}
public static readonly DependencyProperty SelectedTextDecorationsProperty = RegisterFontProperty(
"SelectedTextDecorations",
TextBlock.TextDecorationsProperty,
new PropertyChangedCallback(SelectedTextDecorationsChangedCallback)
);
public TextDecorationCollection SelectedTextDecorations
{
get { return GetValue(SelectedTextDecorationsProperty) as TextDecorationCollection; }
set { SetValue(SelectedTextDecorationsProperty, value); }
}
private static void SelectedTextDecorationsChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
FontChooser chooser = (FontChooser)obj;
chooser.OnTextDecorationsChanged();
}
#endregion
#region Dependency property helper functions
// Helper function for registering typographic dependency properties with property-specific sample text.
private static DependencyProperty RegisterTypographicProperty(DependencyProperty targetProperty, string sampleTextTag)
{
Type t = targetProperty.PropertyType;
TypographyFeaturePage featurePage = (t == typeof(bool)) ? TypographyFeaturePage.BooleanFeaturePage :
(t == typeof(int)) ? TypographyFeaturePage.IntegerFeaturePage :
new TypographyFeaturePage(t);
return DependencyProperty.Register(
targetProperty.Name,
t,
typeof(FontChooser),
new TypographicPropertyMetadata(
targetProperty.DefaultMetadata.DefaultValue,
targetProperty,
featurePage,
sampleTextTag
)
);
}
// Helper function for registering typographic dependency properties with default sample text for the type.
private static DependencyProperty RegisterTypographicProperty(DependencyProperty targetProperty)
{
return RegisterTypographicProperty(targetProperty, null);
}
// Helper function for registering font chooser dependency properties other than typographic properties.
private static DependencyProperty RegisterFontProperty(
string propertyName,
DependencyProperty targetProperty,
PropertyChangedCallback changeCallback
)
{
return DependencyProperty.Register(
propertyName,
targetProperty.PropertyType,
typeof(FontChooser),
new FontPropertyMetadata(
targetProperty.DefaultMetadata.DefaultValue,
changeCallback,
targetProperty
)
);
}
#endregion
#region Dependency property tables
// Array of all font chooser dependency properties
private static readonly DependencyProperty[] _chooserProperties = new DependencyProperty[]
{
// typography properties
StandardLigaturesProperty,
ContextualLigaturesProperty,
DiscretionaryLigaturesProperty,
HistoricalLigaturesProperty,
ContextualAlternatesProperty,
HistoricalFormsProperty,
KerningProperty,
CapitalSpacingProperty,
CaseSensitiveFormsProperty,
StylisticSet1Property,
StylisticSet2Property,
StylisticSet3Property,
StylisticSet4Property,
StylisticSet5Property,
StylisticSet6Property,
StylisticSet7Property,
StylisticSet8Property,
StylisticSet9Property,
StylisticSet10Property,
StylisticSet11Property,
StylisticSet12Property,
StylisticSet13Property,
StylisticSet14Property,
StylisticSet15Property,
StylisticSet16Property,
StylisticSet17Property,
StylisticSet18Property,
StylisticSet19Property,
StylisticSet20Property,
SlashedZeroProperty,
MathematicalGreekProperty,
EastAsianExpertFormsProperty,
FractionProperty,
VariantsProperty,
CapitalsProperty,
NumeralStyleProperty,
NumeralAlignmentProperty,
EastAsianWidthsProperty,
EastAsianLanguageProperty,
AnnotationAlternatesProperty,
StandardSwashesProperty,
ContextualSwashesProperty,
StylisticAlternatesProperty,
// other properties
SelectedFontFamilyProperty,
SelectedFontWeightProperty,
SelectedFontStyleProperty,
SelectedFontStretchProperty,
SelectedFontSizeProperty,
SelectedTextDecorationsProperty
};
#endregion
#region Property change handlers
// Handle changes to the SelectedFontFamily property
private void OnSelectedFontFamilyChanged(FontFamily family)
{
// If the family list is not valid do nothing for now.
// We'll be called again after the list is initialized.
if (_familyListValid)
{
// Select the family in the list; this will return null if the family is not in the list.
FontFamilyListItem item = SelectFontFamilyListItem(family);
// Set the text box to the family name, if it isn't already.
string displayName = (item != null) ? item.ToString() : FontFamilyListItem.GetDisplayName(family);
if (string.Compare(fontFamilyTextBox.Text, displayName, true, CultureInfo.CurrentCulture) != 0)
{
fontFamilyTextBox.Text = displayName;
}
// The typeface list is no longer valid; update it in the background to improve responsiveness.
InvalidateTypefaceList();
}
}
// Handle changes to the SelectedFontSize property
private void OnSelectedFontSizeChanged(double sizeInPixels)
{
// Select the list item, if the size is in the list.
double sizeInPoints = FontSizeListItem.PixelsToPoints(sizeInPixels);
if (!SelectListItem(sizeList, sizeInPoints))
{
sizeList.SelectedIndex = -1;
}
// Set the text box contents if it doesn't already match the current size.
double textBoxValue;
if (!double.TryParse(sizeTextBox.Text, out textBoxValue) || !FontSizeListItem.FuzzyEqual(textBoxValue, sizeInPoints))
{
sizeTextBox.Text = sizeInPoints.ToString();
}
// Schedule background updates.
InvalidateTab(typographyTab);
InvalidatePreview();
}
// Handle changes to any of the text decoration properties.
private void OnTextDecorationsChanged()
{
bool underline = false;
bool baseline = false;
bool strikethrough = false;
bool overline = false;
TextDecorationCollection textDecorations = SelectedTextDecorations;
if (textDecorations != null)
{
foreach (TextDecoration td in textDecorations)
{
switch (td.Location)
{
case TextDecorationLocation.Underline:
underline = true;
break;
case TextDecorationLocation.Baseline:
baseline = true;
break;
case TextDecorationLocation.Strikethrough:
strikethrough = true;
break;
case TextDecorationLocation.OverLine:
overline = true;
break;
}
}
}
underlineCheckBox.IsChecked = underline;
baselineCheckBox.IsChecked = baseline;
strikethroughCheckBox.IsChecked = strikethrough;
overlineCheckBox.IsChecked = overline;
// Schedule background updates.
InvalidateTab(typographyTab);
InvalidatePreview();
}
#endregion
#region Background update logic
// Schedule background initialization of the font famiy list.
private void InvalidateFontFamilyList()
{
if (_familyListValid)
{
InvalidateTypefaceList();
fontFamilyList.Items.Clear();
fontFamilyTextBox.Clear();
_familyListValid = false;
ScheduleUpdate();
}
}
// Schedule background initialization of the typeface list.
private void InvalidateTypefaceList()
{
if (_typefaceListValid)
{
typefaceList.Items.Clear();
_typefaceListValid = false;
ScheduleUpdate();
}
}
// Schedule background selection of the current typeface list item.
private void InvalidateTypefaceListSelection()
{
if (_typefaceListSelectionValid)
{
_typefaceListSelectionValid = false;
ScheduleUpdate();
}
}
// Mark a specific tab as invalid and schedule background initialization if necessary.
private void InvalidateTab(TabItem tab)
{
TabState tabState;
if (_tabDictionary.TryGetValue(tab, out tabState))
{
if (tabState.IsValid)
{
tabState.IsValid = false;
if (tabControl.SelectedItem == tab)
{
ScheduleUpdate();
}
}
}
}
// Mark all the tabs as invalid and schedule background initialization of the current tab.
private void InvalidateTabs()
{
foreach (KeyValuePair<TabItem, TabState> item in _tabDictionary)
{
item.Value.IsValid = false;
}
ScheduleUpdate();
}
// Schedule background initialization of the preview control.
private void InvalidatePreview()
{
if (_previewValid)
{
_previewValid = false;
ScheduleUpdate();
}
}
// Schedule background initialization.
private void ScheduleUpdate()
{
if (!_updatePending)
{
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new UpdateCallback(OnUpdate));
_updatePending = true;
}
}
// Dispatcher callback that performs background initialization.
private void OnUpdate()
{
_updatePending = false;
if (!_familyListValid)
{
// Initialize the font family list.
InitializeFontFamilyList();
_familyListValid = true;
OnSelectedFontFamilyChanged(SelectedFontFamily);
// Defer any other initialization until later.
ScheduleUpdate();
}
else if (!_typefaceListValid)
{
// Initialize the typeface list.
InitializeTypefaceList();
_typefaceListValid = true;
// Select the current typeface in the list.
InitializeTypefaceListSelection();
_typefaceListSelectionValid = true;
// Defer any other initialization until later.
ScheduleUpdate();
}
else if (!_typefaceListSelectionValid)
{
// Select the current typeface in the list.
InitializeTypefaceListSelection();
_typefaceListSelectionValid = true;
// Defer any other initialization until later.
ScheduleUpdate();
}
else
{
// Perform any remaining initialization.
TabState tab = CurrentTabState;
if (tab != null && !tab.IsValid)
{
// Initialize the current tab.
tab.InitializeTab();
tab.IsValid = true;
}
if (!_previewValid)
{
// Initialize the preview control.
InitializePreview();
_previewValid = true;
}
}
}
#endregion
#region Content initialization
private void InitializeFontFamilyList()
{
ICollection<FontFamily> familyCollection = FontFamilyCollection;
if (familyCollection != null)
{
FontFamilyListItem[] items = new FontFamilyListItem[familyCollection.Count];
int i = 0;
foreach (FontFamily family in familyCollection)
{
items[i++] = new FontFamilyListItem(family);
}
Array.Sort<FontFamilyListItem>(items);
foreach (FontFamilyListItem item in items)
{
fontFamilyList.Items.Add(item);
}
}
}
private void InitializeTypefaceList()
{
FontFamily family = SelectedFontFamily;
if (family != null)
{
ICollection<Typeface> faceCollection = family.GetTypefaces();
TypefaceListItem[] items = new TypefaceListItem[faceCollection.Count];
int i = 0;
foreach (Typeface face in faceCollection)
{
items[i++] = new TypefaceListItem(face);
}
Array.Sort<TypefaceListItem>(items);
foreach (TypefaceListItem item in items)
{
typefaceList.Items.Add(item);
}
}
}
private void InitializeTypefaceListSelection()
{
// If the typeface list is not valid, do nothing for now.
// We'll be called again after the list is initialized.
if (_typefaceListValid)
{
Typeface typeface = new Typeface(SelectedFontFamily, SelectedFontStyle, SelectedFontWeight, SelectedFontStretch);
// Select the typeface in the list.
SelectTypefaceListItem(typeface);
// Schedule background updates.
InvalidateTabs();
InvalidatePreview();
}
}
private void InitializeFeatureList()
{
TypographicFeatureListItem[] items = new TypographicFeatureListItem[_chooserProperties.Length];
int count = 0;
foreach (DependencyProperty property in _chooserProperties)
{
if (property.GetMetadata(typeof(FontChooser)) is TypographicPropertyMetadata)
{
items[count++] = new TypographicFeatureListItem(property.Name, property);
}
}
Array.Sort(items, 0, count);
for (int i = 0; i < count; ++i)
{
featureList.Items.Add(items[i]);
}
}
private TabState CurrentTabState
{
get
{
TabState tab;
return _tabDictionary.TryGetValue(tabControl.SelectedItem as TabItem, out tab) ? tab : null;
}
}
private void InitializeSamplesTab()
{
FontFamily selectedFamily = SelectedFontFamily;
Typeface selectedFace = new Typeface(
selectedFamily,
SelectedFontStyle,
SelectedFontWeight,
SelectedFontStretch
);
fontFamilyNameRun.Text = FontFamilyListItem.GetDisplayName(selectedFamily);
typefaceNameRun.Text = TypefaceListItem.GetDisplayName(selectedFace);
// Create FontFamily samples document.
FlowDocument doc = new FlowDocument();
foreach (Typeface face in selectedFamily.GetTypefaces())
{
Paragraph labelPara = new Paragraph(new Run(TypefaceListItem.GetDisplayName(face)));
labelPara.Margin = new Thickness(0);
doc.Blocks.Add(labelPara);
Paragraph samplePara = new Paragraph(new Run(_previewSampleText));
samplePara.FontFamily = selectedFamily;
samplePara.FontWeight = face.Weight;
samplePara.FontStyle = face.Style;
samplePara.FontStretch = face.Stretch;
samplePara.FontSize = 16.0;
samplePara.Margin = new Thickness(0, 0, 0, 8);
doc.Blocks.Add(samplePara);
}
fontFamilySamples.Document = doc;
// Create typeface samples document.
doc = new FlowDocument();
foreach (double sizeInPoints in new double[] { 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0 })
{
string labelText = string.Format("{0} {1}", sizeInPoints, _pointsText);
Paragraph labelPara = new Paragraph(new Run(labelText));
labelPara.Margin = new Thickness(0);
doc.Blocks.Add(labelPara);
Paragraph samplePara = new Paragraph(new Run(_previewSampleText));
samplePara.FontFamily = selectedFamily;
samplePara.FontWeight = selectedFace.Weight;
samplePara.FontStyle = selectedFace.Style;
samplePara.FontStretch = selectedFace.Stretch;
samplePara.FontSize = FontSizeListItem.PointsToPixels(sizeInPoints);
samplePara.Margin = new Thickness(0, 0, 0, 8);
doc.Blocks.Add(samplePara);
}
typefaceSamples.Document = doc;
}
private void InitializeTypographyTab()
{
if (featureList.Items.IsEmpty)
{
InitializeFeatureList();
featureList.SelectedIndex = 0;
featureList.SelectionChanged += new SelectionChangedEventHandler(featureList_SelectionChanged);
}
DependencyProperty chooserProperty = null;
TypographyFeaturePage featurePage = null;
TypographicFeatureListItem listItem = featureList.SelectedItem as TypographicFeatureListItem;
if (listItem != null)
{
TypographicPropertyMetadata metadata = listItem.ChooserProperty.GetMetadata(typeof(FontChooser)) as TypographicPropertyMetadata;
if (metadata != null)
{
chooserProperty = listItem.ChooserProperty;
featurePage = metadata.FeaturePage;
}
}
InitializeFeaturePage(typographyFeaturePage, chooserProperty, featurePage);
}
private void InitializeFeaturePage(Grid grid, DependencyProperty chooserProperty, TypographyFeaturePage page)
{
if (page == null)
{
grid.Children.Clear();
grid.RowDefinitions.Clear();
}
else
{
// Get the property value and metadata.
object value = this.GetValue(chooserProperty);
TypographicPropertyMetadata metadata = (TypographicPropertyMetadata)chooserProperty.GetMetadata(typeof(FontChooser));
// Look up the sample text.
string sampleText = metadata.SampleTextTag ?? _defaultSampleText;
if (page == _currentFeaturePage)
{
// Update the state of the controls.
for (int i = 0; i < page.Items.Length; ++i)
{
// Check the radio button if it matches the current property value.
if (page.Items[i].Value.Equals(value))
{
RadioButton radioButton = (RadioButton)grid.Children[i * 2];
radioButton.IsChecked = true;
}
// Apply properties to the sample text block.
TextBlock sample = (TextBlock)grid.Children[i * 2 + 1];
sample.Text = sampleText;
ApplyPropertiesToObjectExcept(sample, chooserProperty);
sample.SetValue(metadata.TargetProperty, page.Items[i].Value);
}
}
else
{
grid.Children.Clear();
grid.RowDefinitions.Clear();
// Add row definitions.
for (int i = 0; i < page.Items.Length; ++i)
{
RowDefinition row = new RowDefinition();
row.Height = GridLength.Auto;
grid.RowDefinitions.Add(row);
}
// Add the controls.
for (int i = 0; i < page.Items.Length; ++i)
{
string tag = page.Items[i].Tag;
TextBlock radioContent = new TextBlock(new Run(tag));
radioContent.TextWrapping = TextWrapping.Wrap;
// Add the radio button.
RadioButton radioButton = new RadioButton();
radioButton.Name = tag;
radioButton.Content = radioContent;
radioButton.Margin = new Thickness(5.0, 0.0, 0.0, 0.0);
radioButton.VerticalAlignment = VerticalAlignment.Center;
Grid.SetRow(radioButton, i);
grid.Children.Add(radioButton);
// Check the radio button if it matches the current property value.
if (page.Items[i].Value.Equals(value))
{
radioButton.IsChecked = true;
}
// Hook up the event.
radioButton.Checked += new RoutedEventHandler(featureRadioButton_Checked);
// Add the block with sample text.
TextBlock sample = new TextBlock(new Run(sampleText));
sample.Margin = new Thickness(5.0, 5.0, 5.0, 0.0);
sample.TextWrapping = TextWrapping.WrapWithOverflow;
ApplyPropertiesToObjectExcept(sample, chooserProperty);
sample.SetValue(metadata.TargetProperty, page.Items[i].Value);
Grid.SetRow(sample, i);
Grid.SetColumn(sample, 1);
grid.Children.Add(sample);
}
// Add borders between rows.
for (int i = 0; i < page.Items.Length; ++i)
{
Border border = new Border();
border.BorderThickness = new Thickness(0.0, 0.0, 0.0, 1.0);
border.BorderBrush = SystemColors.ControlLightBrush;
Grid.SetRow(border, i);
Grid.SetColumnSpan(border, 2);
grid.Children.Add(border);
}
}
}
_currentFeature = chooserProperty;
_currentFeaturePage = page;
}
private void featureRadioButton_Checked(object sender, RoutedEventArgs e)
{
if (_currentFeature != null && _currentFeaturePage != null)
{
string tag = ((RadioButton)sender).Name;
foreach (TypographyFeaturePage.Item item in _currentFeaturePage.Items)
{
if (item.Tag == tag)
{
this.SetValue(_currentFeature, item.Value);
}
}
}
}
private void AddTableRow(TableRowGroup rowGroup, string leftText, string rightText)
{
TableRow row = new TableRow();
row.Cells.Add(new TableCell(new Paragraph(new Run(leftText))));
row.Cells.Add(new TableCell(new Paragraph(new Run(rightText))));
rowGroup.Rows.Add(row);
}
private void AddTableRow(TableRowGroup rowGroup, string leftText, IDictionary<CultureInfo, string> rightStrings)
{
string rightText = NameDictionaryHelper.GetDisplayName(rightStrings);
AddTableRow(rowGroup, leftText, rightText);
}
private void InitializeDescriptiveTextTab()
{
Typeface selectedTypeface = new Typeface(
SelectedFontFamily,
SelectedFontStyle,
SelectedFontWeight,
SelectedFontStretch
);
GlyphTypeface glyphTypeface;
if (selectedTypeface.TryGetGlyphTypeface(out glyphTypeface))
{
// Create a table with two columns.
Table table = new Table();
table.CellSpacing = 5;
TableColumn leftColumn = new TableColumn();
leftColumn.Width = new GridLength(2.0, GridUnitType.Star);
table.Columns.Add(leftColumn);
TableColumn rightColumn = new TableColumn();
rightColumn.Width = new GridLength(3.0, GridUnitType.Star);
table.Columns.Add(rightColumn);
TableRowGroup rowGroup = new TableRowGroup();
AddTableRow(rowGroup, "Family:", glyphTypeface.FamilyNames);
AddTableRow(rowGroup, "Face:", glyphTypeface.FaceNames);
AddTableRow(rowGroup, "Description:", glyphTypeface.Descriptions);
AddTableRow(rowGroup, "Version:", glyphTypeface.VersionStrings);
AddTableRow(rowGroup, "Copyright:", glyphTypeface.Copyrights);
AddTableRow(rowGroup, "Trademark:", glyphTypeface.Trademarks);
AddTableRow(rowGroup, "Manufacturer:", glyphTypeface.ManufacturerNames);
AddTableRow(rowGroup, "Designer:", glyphTypeface.DesignerNames);
AddTableRow(rowGroup, "Designer URL:", glyphTypeface.DesignerUrls);
AddTableRow(rowGroup, "Vendor URL:", glyphTypeface.VendorUrls);
AddTableRow(rowGroup, "Win32 Family:", glyphTypeface.Win32FamilyNames);
AddTableRow(rowGroup, "Win32 Face:", glyphTypeface.Win32FaceNames);
try
{
AddTableRow(rowGroup, "Font File URI:", glyphTypeface.FontUri.ToString());
}
catch (System.Security.SecurityException)
{
// Font file URI is privileged information; just skip it if we don't have access.
}
table.RowGroups.Add(rowGroup);
fontDescriptionBox.Document = new FlowDocument(table);
fontLicenseBox.Text = NameDictionaryHelper.GetDisplayName(glyphTypeface.LicenseDescriptions);
}
else
{
fontDescriptionBox.Document = new FlowDocument();
fontLicenseBox.Text = String.Empty;
}
}
private void InitializePreview()
{
ApplyPropertiesToObject(previewTextBox);
}
#endregion
#region List box helpers
// Update font family list based on selection.
// Return list item if there's an exact match, or null if not.
private FontFamilyListItem SelectFontFamilyListItem(string displayName)
{
FontFamilyListItem listItem = fontFamilyList.SelectedItem as FontFamilyListItem;
if (listItem != null && string.Compare(listItem.ToString(), displayName, true, CultureInfo.CurrentCulture) == 0)
{
// Already selected
return listItem;
}
else if (SelectListItem(fontFamilyList, displayName))
{
// Exact match found
return fontFamilyList.SelectedItem as FontFamilyListItem;
}
else
{
// Not in the list
return null;
}
}
// Update font family list based on selection.
// Return list item if there's an exact match, or null if not.
private FontFamilyListItem SelectFontFamilyListItem(FontFamily family)
{
FontFamilyListItem listItem = fontFamilyList.SelectedItem as FontFamilyListItem;
if (listItem != null && listItem.FontFamily.Equals(family))
{
// Already selected
return listItem;
}
else if (SelectListItem(fontFamilyList, FontFamilyListItem.GetDisplayName(family)))
{
// Exact match found
return fontFamilyList.SelectedItem as FontFamilyListItem;
}
else
{
// Not in the list
return null;
}
}
// Update typeface list based on selection.
// Return list item if there's an exact match, or null if not.
private TypefaceListItem SelectTypefaceListItem(Typeface typeface)
{
TypefaceListItem listItem = typefaceList.SelectedItem as TypefaceListItem;
if (listItem != null && listItem.Typeface.Equals(typeface))
{
// Already selected
return listItem;
}
else if (SelectListItem(typefaceList, new TypefaceListItem(typeface)))
{
// Exact match found
return typefaceList.SelectedItem as TypefaceListItem;
}
else
{
// Not in list
return null;
}
}
// Update list based on selection.
// Return true if there's an exact match, or false if not.
private bool SelectListItem(ListBox list, object value)
{
ItemCollection itemList = list.Items;
// Perform a binary search for the item.
int first = 0;
int limit = itemList.Count;
while (first < limit)
{
int i = first + (limit - first) / 2;
IComparable item = (IComparable)(itemList[i]);
int comparison = item.CompareTo(value);
if (comparison < 0)
{
// Value must be after i
first = i + 1;
}
else if (comparison > 0)
{
// Value must be before i
limit = i;
}
else
{
// Exact match; select the item.
list.SelectedIndex = i;
itemList.MoveCurrentToPosition(i);
list.ScrollIntoView(itemList[i]);
return true;
}
}
// Not an exact match; move current position to the nearest item but don't select it.
if (itemList.Count > 0)
{
int i = Math.Min(first, itemList.Count - 1);
itemList.MoveCurrentToPosition(i);
list.ScrollIntoView(itemList[i]);
}
return false;
}
// Logic to handle UP and DOWN arrow keys in the text box associated with a list.
// Behavior is similar to a Win32 combo box.
private void OnComboBoxPreviewKeyDown(TextBox textBox, ListBox listBox, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Up:
// Move up from the current position.
MoveListPosition(listBox, -1);
e.Handled = true;
break;
case Key.Down:
// Move down from the current position, unless the item at the current position is
// not already selected in which case select it.
if (listBox.Items.CurrentPosition == listBox.SelectedIndex)
{
MoveListPosition(listBox, +1);
}
else
{
MoveListPosition(listBox, 0);
}
e.Handled = true;
break;
}
}
private void MoveListPosition(ListBox listBox, int distance)
{
int i = listBox.Items.CurrentPosition + distance;
if (i >= 0 && i < listBox.Items.Count)
{
listBox.Items.MoveCurrentToPosition(i);
listBox.SelectedIndex = i;
listBox.ScrollIntoView(listBox.Items[i]);
}
}
#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.Configuration.Internal;
using System.Diagnostics;
namespace System.Configuration
{
public sealed class SectionInformation
{
// Flags
private const int FlagAttached = 0x00000001;
private const int FlagDeclared = 0x00000002;
private const int FlagDeclarationRequired = 0x00000004;
private const int FlagAllowLocation = 0x00000008;
private const int FlagRestartOnExternalChanges = 0x00000010;
private const int FlagRequirePermission = 0x00000020;
private const int FlagLocationLocked = 0x00000040;
private const int FlagChildrenLocked = 0x00000080;
private const int FlagInheritInChildApps = 0x00000100;
private const int FlagIsParentSection = 0x00000200;
private const int FlagRemoved = 0x00000400;
private const int FlagProtectionProviderDetermined = 0x00000800;
private const int FlagForceSave = 0x00001000;
private const int FlagIsUndeclared = 0x00002000;
private const int FlagChildrenLockWithoutFileInput = 0x00004000;
private const int FlagAllowExeDefinitionModified = 0x00010000;
private const int FlagAllowDefinitionModified = 0x00020000;
private const int FlagConfigSourceModified = 0x00040000;
private const int FlagProtectionProviderModified = 0x00080000;
private const int FlagOverrideModeDefaultModified = 0x00100000;
private const int FlagOverrideModeModified = 0x00200000; // Used only for modified tracking
private readonly ConfigurationSection _configurationSection;
private ConfigurationAllowDefinition _allowDefinition;
private ConfigurationAllowExeDefinition _allowExeDefinition;
private MgmtConfigurationRecord _configRecord;
private string _configSource;
private SafeBitVector32 _flags;
private SimpleBitVector32 _modifiedFlags;
private OverrideModeSetting _overrideMode; // The override mode at the current config path
private OverrideModeSetting _overrideModeDefault; // The default mode for the section in _configurationSection
private ProtectedConfigurationProvider _protectionProvider;
private string _typeName;
internal SectionInformation(ConfigurationSection associatedConfigurationSection)
{
ConfigKey = string.Empty;
Name = string.Empty;
_configurationSection = associatedConfigurationSection;
_allowDefinition = ConfigurationAllowDefinition.Everywhere;
_allowExeDefinition = ConfigurationAllowExeDefinition.MachineToApplication;
_overrideModeDefault = OverrideModeSetting.s_sectionDefault;
_overrideMode = OverrideModeSetting.s_locationDefault;
_flags[FlagAllowLocation] = true;
_flags[FlagRestartOnExternalChanges] = true;
_flags[FlagRequirePermission] = true;
_flags[FlagInheritInChildApps] = true;
_flags[FlagForceSave] = false;
_modifiedFlags = new SimpleBitVector32();
}
private bool IsRuntime => _flags[FlagAttached] &&
(_configRecord == null);
internal bool Attached => _flags[FlagAttached];
internal string ConfigKey { get; private set; }
internal bool Removed
{
get { return _flags[FlagRemoved]; }
set { _flags[FlagRemoved] = value; }
}
public string SectionName => ConfigKey;
public string Name { get; private set; }
public ConfigurationAllowDefinition AllowDefinition
{
get { return _allowDefinition; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow AllowDefinition to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowDefinition != value))
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_allowDefinition = value;
_modifiedFlags[FlagAllowDefinitionModified] = true;
}
}
internal bool AllowDefinitionModified => _modifiedFlags[FlagAllowDefinitionModified];
public ConfigurationAllowExeDefinition AllowExeDefinition
{
get { return _allowExeDefinition; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow AllowDefinition to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowExeDefinition != value))
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_allowExeDefinition = value;
_modifiedFlags[FlagAllowExeDefinitionModified] = true;
}
}
internal bool AllowExeDefinitionModified => _modifiedFlags[FlagAllowExeDefinitionModified];
public OverrideMode OverrideModeDefault
{
get { return _overrideModeDefault.OverrideMode; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow OverrideModeDefault to be different from current value,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.OverrideModeDefault.OverrideMode != value))
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
// Threat "Inherit" as "Allow" as "Inherit" does not make sense as a default
if (value == OverrideMode.Inherit) value = OverrideMode.Allow;
_overrideModeDefault.OverrideMode = value;
_modifiedFlags[FlagOverrideModeDefaultModified] = true;
}
}
internal OverrideModeSetting OverrideModeDefaultSetting => _overrideModeDefault;
internal bool OverrideModeDefaultModified => _modifiedFlags[FlagOverrideModeDefaultModified];
public bool AllowLocation
{
get { return _flags[FlagAllowLocation]; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow AllowLocation to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowLocation != value))
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagAllowLocation] = value;
_modifiedFlags[FlagAllowLocation] = true;
}
}
internal bool AllowLocationModified => _modifiedFlags[FlagAllowLocation];
public bool AllowOverride
{
get { return _overrideMode.AllowOverride; }
set
{
VerifyIsEditable();
VerifySupportsLocation();
_overrideMode.AllowOverride = value;
_modifiedFlags[FlagOverrideModeModified] = true;
}
}
public OverrideMode OverrideMode
{
get { return _overrideMode.OverrideMode; }
set
{
VerifyIsEditable();
VerifySupportsLocation();
_overrideMode.OverrideMode = value;
_modifiedFlags[FlagOverrideModeModified] = true;
// Modify the state of OverrideModeEffective according to the changes to the current mode
switch (value)
{
case OverrideMode.Inherit:
// Wehen the state is changing to inherit - apply the value from parent which does not
// include the file input lock mode
_flags[FlagChildrenLocked] = _flags[FlagChildrenLockWithoutFileInput];
break;
case OverrideMode.Allow:
_flags[FlagChildrenLocked] = false;
break;
case OverrideMode.Deny:
_flags[FlagChildrenLocked] = true;
break;
default:
Debug.Fail("Unexpected value for OverrideMode");
break;
}
}
}
public OverrideMode OverrideModeEffective => _flags[FlagChildrenLocked] ? OverrideMode.Deny : OverrideMode.Allow
;
internal OverrideModeSetting OverrideModeSetting => _overrideMode;
// LocationAttributesAreDefault
//
// Are the location attributes for this section set to the
// default settings?
internal bool LocationAttributesAreDefault => _overrideMode.IsDefaultForLocationTag &&
_flags[FlagInheritInChildApps];
public string ConfigSource
{
get { return _configSource ?? string.Empty; }
set
{
VerifyIsEditable();
string configSource = !string.IsNullOrEmpty(value)
? BaseConfigurationRecord.NormalizeConfigSource(value, null)
: null;
// return early if there is no change
if (configSource == _configSource)
return;
_configRecord?.ChangeConfigSource(this, _configSource, ConfigSourceStreamName, configSource);
_configSource = configSource;
_modifiedFlags[FlagConfigSourceModified] = true;
}
}
internal bool ConfigSourceModified => _modifiedFlags[FlagConfigSourceModified];
internal string ConfigSourceStreamName { get; set; }
public bool InheritInChildApplications
{
get { return _flags[FlagInheritInChildApps]; }
set
{
VerifyIsEditable();
VerifySupportsLocation();
_flags[FlagInheritInChildApps] = value;
}
}
// True if the section is declared at the current level
public bool IsDeclared
{
get
{
VerifyNotParentSection();
return _flags[FlagDeclared];
}
}
// Is the Declaration Required. It is required if it is not set
// in a parent, or the parent entry does not have the type
public bool IsDeclarationRequired
{
get
{
VerifyNotParentSection();
return _flags[FlagDeclarationRequired];
}
}
// Is the Definition Allowed at this point. This is all depending
// on the Definition that is allowed, and what context we are
// writing the file
private bool IsDefinitionAllowed
=> (_configRecord == null) || _configRecord.IsDefinitionAllowed(_allowDefinition, _allowExeDefinition);
public bool IsLocked => _flags[FlagLocationLocked] || !IsDefinitionAllowed ||
_configurationSection.ElementInformation.IsLocked;
public bool IsProtected => ProtectionProvider != null;
public ProtectedConfigurationProvider ProtectionProvider
{
get
{
if (!_flags[FlagProtectionProviderDetermined] && (_configRecord != null))
{
_protectionProvider = _configRecord.GetProtectionProviderFromName(ProtectionProviderName, false);
_flags[FlagProtectionProviderDetermined] = true;
}
return _protectionProvider;
}
}
internal string ProtectionProviderName { get; private set; }
public bool RestartOnExternalChanges
{
get { return _flags[FlagRestartOnExternalChanges]; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow RestartOnExternalChanges to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.RestartOnExternalChanges != value))
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagRestartOnExternalChanges] = value;
_modifiedFlags[FlagRestartOnExternalChanges] = true;
}
}
internal bool RestartOnExternalChangesModified => _modifiedFlags[FlagRestartOnExternalChanges];
public bool RequirePermission
{
get { return _flags[FlagRequirePermission]; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow RequirePermission to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.RequirePermission != value))
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagRequirePermission] = value;
_modifiedFlags[FlagRequirePermission] = true;
}
}
internal bool RequirePermissionModified => _modifiedFlags[FlagRequirePermission];
public string Type
{
get { return _typeName; }
set
{
if (string.IsNullOrEmpty(value)) throw ExceptionUtil.PropertyNullOrEmpty(nameof(Type));
VerifyIsEditable();
VerifyIsEditableFactory();
// allow type to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if (factoryRecord != null)
{
IInternalConfigHost host = null;
if (_configRecord != null) host = _configRecord.Host;
if (!factoryRecord.IsEquivalentType(host, value))
{
throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined,
ConfigKey));
}
}
_typeName = value;
}
}
internal string RawXml { get; set; }
// True if the section will be serialized to the current hierarchy level, regardless of
// ConfigurationSaveMode.
public bool ForceSave
{
get { return _flags[FlagForceSave]; }
set
{
VerifyIsEditable();
_flags[FlagForceSave] = value;
}
}
internal void ResetModifiedFlags()
{
_modifiedFlags = new SimpleBitVector32();
}
internal bool IsModifiedFlags()
{
return _modifiedFlags.Data != 0;
}
// for instantiation of a ConfigurationSection from GetConfig
internal void AttachToConfigurationRecord(MgmtConfigurationRecord configRecord, FactoryRecord factoryRecord,
SectionRecord sectionRecord)
{
SetRuntimeConfigurationInformation(configRecord, factoryRecord, sectionRecord);
_configRecord = configRecord;
}
internal void SetRuntimeConfigurationInformation(BaseConfigurationRecord configRecord,
FactoryRecord factoryRecord, SectionRecord sectionRecord)
{
_flags[FlagAttached] = true;
// factory info
ConfigKey = factoryRecord.ConfigKey;
Name = factoryRecord.Name;
_typeName = factoryRecord.FactoryTypeName;
_allowDefinition = factoryRecord.AllowDefinition;
_allowExeDefinition = factoryRecord.AllowExeDefinition;
_flags[FlagAllowLocation] = factoryRecord.AllowLocation;
_flags[FlagRestartOnExternalChanges] = factoryRecord.RestartOnExternalChanges;
_flags[FlagRequirePermission] = factoryRecord.RequirePermission;
_overrideModeDefault = factoryRecord.OverrideModeDefault;
if (factoryRecord.IsUndeclared)
{
_flags[FlagIsUndeclared] = true;
_flags[FlagDeclared] = false;
_flags[FlagDeclarationRequired] = false;
}
else
{
_flags[FlagIsUndeclared] = false;
_flags[FlagDeclared] = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, false) != null;
_flags[FlagDeclarationRequired] = configRecord.IsRootDeclaration(factoryRecord.ConfigKey, false);
}
// section info
_flags[FlagLocationLocked] = sectionRecord.Locked;
_flags[FlagChildrenLocked] = sectionRecord.LockChildren;
_flags[FlagChildrenLockWithoutFileInput] = sectionRecord.LockChildrenWithoutFileInput;
if (sectionRecord.HasFileInput)
{
SectionInput fileInput = sectionRecord.FileInput;
_flags[FlagProtectionProviderDetermined] = fileInput.IsProtectionProviderDetermined;
_protectionProvider = fileInput.ProtectionProvider;
SectionXmlInfo sectionXmlInfo = fileInput.SectionXmlInfo;
_configSource = sectionXmlInfo.ConfigSource;
ConfigSourceStreamName = sectionXmlInfo.ConfigSourceStreamName;
_overrideMode = sectionXmlInfo.OverrideModeSetting;
_flags[FlagInheritInChildApps] = !sectionXmlInfo.SkipInChildApps;
ProtectionProviderName = sectionXmlInfo.ProtectionProviderName;
}
else
{
_flags[FlagProtectionProviderDetermined] = false;
_protectionProvider = null;
}
// element context information
_configurationSection.AssociateContext(configRecord);
}
internal void DetachFromConfigurationRecord()
{
RevertToParent();
_flags[FlagAttached] = false;
_configRecord = null;
}
private void VerifyDesigntime()
{
if (IsRuntime) throw new InvalidOperationException(SR.Config_operation_not_runtime);
}
private void VerifyIsAttachedToConfigRecord()
{
if (_configRecord == null)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_not_attached);
}
// VerifyIsEditable
//
// Verify the section is Editable.
// It may not be editable for the following reasons:
// - We are in Runtime mode, not Design time
// - The section is not attached to a _configRecord.
// - We are locked (ie. allowOveride = false )
// - We are a parent section (ie. Retrieved from GetParentSection)
//
internal void VerifyIsEditable()
{
VerifyDesigntime();
if (IsLocked)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_locked);
if (_flags[FlagIsParentSection])
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_parentsection);
if (!_flags[FlagAllowLocation] &&
(_configRecord != null) &&
_configRecord.IsLocationConfig)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_location_locked);
}
private void VerifyNotParentSection()
{
if (_flags[FlagIsParentSection])
throw new InvalidOperationException(SR.Config_configsection_parentnotvalid);
}
// Verify that we support the location tag. This is true either
// in machine.config, or in any place for the web config system
private void VerifySupportsLocation()
{
if ((_configRecord != null) &&
!_configRecord.RecordSupportsLocation)
throw new InvalidOperationException(SR.Config_cannot_edit_locationattriubtes);
}
internal void VerifyIsEditableFactory()
{
if ((_configRecord != null) && _configRecord.IsLocationConfig)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_in_location_config);
// Can't edit factory if the section is built-in
if (BaseConfigurationRecord.IsImplicitSection(ConfigKey))
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_it_is_implicit);
// Can't edit undeclared section
if (_flags[FlagIsUndeclared])
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_it_is_undeclared);
}
private FactoryRecord FindParentFactoryRecord(bool permitErrors)
{
FactoryRecord factoryRecord = null;
if ((_configRecord != null) && !_configRecord.Parent.IsRootConfig)
factoryRecord = _configRecord.Parent.FindFactoryRecord(ConfigKey, permitErrors);
return factoryRecord;
}
// Force the section declaration to be written out during Save.
public void ForceDeclaration()
{
ForceDeclaration(true);
}
// If force==false, it actually means don't declare it at
// the current level.
public void ForceDeclaration(bool force)
{
VerifyIsEditable();
if ((force == false) &&
_flags[FlagDeclarationRequired])
{
// Since it is required, we can not remove it
}
else
{
// CONSIDER: There is no apriori way to determine if a section
// is implicit or undeclared. Would it be better to simply
// fail silently so that app code can easily loop through sections
// and declare all of them?
if (force && BaseConfigurationRecord.IsImplicitSection(SectionName))
throw new ConfigurationErrorsException(SR.Format(SR.Cannot_declare_or_remove_implicit_section, SectionName));
if (force && _flags[FlagIsUndeclared])
{
throw new ConfigurationErrorsException(
SR.Config_cannot_edit_configurationsection_when_it_is_undeclared);
}
_flags[FlagDeclared] = force;
}
}
// method to cause a section to be protected using the specified provider
public void ProtectSection(string protectionProvider)
{
ProtectedConfigurationProvider protectedConfigurationProvider;
VerifyIsEditable();
// Do not encrypt sections that will be read by a native reader.
// These sections are be marked with allowLocation=false.
// Also, the configProtectedData section cannot be encrypted!
if (!AllowLocation || (ConfigKey == BaseConfigurationRecord.ReservedSectionProtectedConfiguration))
throw new InvalidOperationException(SR.Config_not_allowed_to_encrypt_this_section);
if (_configRecord != null)
{
if (string.IsNullOrEmpty(protectionProvider)) protectionProvider = _configRecord.DefaultProviderName;
protectedConfigurationProvider = _configRecord.GetProtectionProviderFromName(protectionProvider, true);
}
else throw new InvalidOperationException(SR.Must_add_to_config_before_protecting_it);
ProtectionProviderName = protectionProvider;
_protectionProvider = protectedConfigurationProvider;
_flags[FlagProtectionProviderDetermined] = true;
_modifiedFlags[FlagProtectionProviderModified] = true;
}
public void UnprotectSection()
{
VerifyIsEditable();
_protectionProvider = null;
ProtectionProviderName = null;
_flags[FlagProtectionProviderDetermined] = true;
_modifiedFlags[FlagProtectionProviderModified] = true;
}
public ConfigurationSection GetParentSection()
{
VerifyDesigntime();
if (_flags[FlagIsParentSection])
throw new InvalidOperationException(SR.Config_getparentconfigurationsection_first_instance);
// if a users create a configsection with : sectionType sec = new sectionType();
// the config record will be null. Return null for the parent in this case.
ConfigurationSection ancestor = null;
if (_configRecord != null)
{
ancestor = _configRecord.FindAndCloneImmediateParentSection(_configurationSection);
if (ancestor != null)
{
ancestor.SectionInformation._flags[FlagIsParentSection] = true;
ancestor.SetReadOnly();
}
}
return ancestor;
}
public string GetRawXml()
{
VerifyDesigntime();
VerifyNotParentSection();
return RawXml ?? _configRecord?.GetRawXml(ConfigKey);
}
public void SetRawXml(string rawXml)
{
VerifyIsEditable();
if (_configRecord != null) _configRecord.SetRawXml(_configurationSection, rawXml);
else RawXml = string.IsNullOrEmpty(rawXml) ? null : rawXml;
}
public void RevertToParent()
{
VerifyIsEditable();
VerifyIsAttachedToConfigRecord();
_configRecord.RevertToParent(_configurationSection);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
namespace Test
{
/// <summary>
/// Tests the public methods in ObservableCollection<T> as well as verifies
/// that the CollectionChanged events and eventargs are fired and populated
/// properly.
/// </summary>
public static class PublicMethodsTest
{
/// <summary>
/// Tests that is is possible to Add an item to the collection.
/// </summary>
[Fact]
public static void AddTest()
{
string[] anArray = { "one", "two", "three" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.AddOrInsertItemTest(col, "four");
}
/// <summary>
/// Tests that it is possible to remove an item from the collection.
/// - Removing an item from the collection results in a false.
/// - Removing null from collection returns a false.
/// - Removing an item that has duplicates only takes out the first instance.
/// </summary>
[Fact]
public static void RemoveTest()
{
// trying to remove item in collection.
string[] anArray = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, 2, "three", true, hasDuplicates: false);
// trying to remove item not in collection.
anArray = new string[] { "one", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, -1, "three2", false, hasDuplicates: false);
// removing null
anArray = new string[] { "one", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, -1, null, false, hasDuplicates: false);
// trying to remove item in collection that has duplicates.
anArray = new string[] { "one", "three", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, 1, "three", true, hasDuplicates: true);
// want to ensure that there is one "three" left in collection and not both were removed.
int occurancesThree = 0;
foreach (var item in col)
{
if (item.Equals("three"))
occurancesThree++;
}
Assert.Equal(1, occurancesThree);
}
/// <summary>
/// Tests that a collection can be cleared.
/// </summary>
[Fact]
public static void ClearTest()
{
string[] anArray = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
col.Clear();
Assert.Equal(0, col.Count);
foreach (var item in col)
{
Assert.True(false, "Should not be able to iterate through an empty collection.");
}
Assert.Throws<ArgumentOutOfRangeException>(() => col[1]);
//tests that the collectionChanged events are fired.
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
col = new ObservableCollection<string>(anArray);
helper.ClearTest(col);
}
/// <summary>
/// Tests that we can remove items at a specific index, at the middle beginning and end.
/// </summary>
[Fact]
public static void RemoveAtTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col2 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
col0.RemoveAt(0);
string collectionString = "";
foreach (var item in col1)
collectionString += item + ", ";
Assert.False(col0.Contains(anArray[0]), "Collection0 should no longer contain the item: " + anArray[0] + " Collection: " + collectionString);
col1.RemoveAt(1);
collectionString = "";
foreach (var item in col1)
collectionString += item + ", ";
Assert.False(col1.Contains(anArray[1]), "Collection1 should no longer contain the item: " + anArray[1] + " Collection: " + collectionString);
col2.RemoveAt(2);
collectionString = "";
foreach (var item in col2)
collectionString += item + ", ";
Assert.False(col2.Contains(anArray[2]), "Collection2 should no longer contain the item: " + anArray[2] + " Collection: " + collectionString);
string[] anArrayString = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArrayString);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemAtTest(col, 1);
}
/// <summary>
/// Tests that exceptions are thrown:
/// ArgumentOutOfRangeException when index < 0 or index >= collection.Count.
/// And that the collection does not change.
/// </summary>
[Fact]
public static void RemoveAtTest_Negative()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
collection.CollectionChanged += (o, e) =>
{
Assert.True(false, "Should not have thrown collection changed event when removing items from invalid indices");
};
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
Assert.Equal(anArray.Length, collection.Count);
}
int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
Assert.Equal(anArray.Length, collection.Count);
}
}
/// <summary>
/// Tests that items can be moved throughout a collection whether from
/// beginning to end, etc.
/// </summary>
[Fact]
public static void MoveTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col01 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col10 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col12 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col21 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col20 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
col01.Move(0, 1);
Assert.Equal(anArray[0], col01[1]);
col10.Move(1, 0);
Assert.Equal(anArray[1], col10[0]);
col12.Move(1, 2);
Assert.Equal(anArray[1], col12[2]);
col21.Move(2, 1);
Assert.Equal(anArray[2], col21[1]);
col20.Move(2, 0);
Assert.Equal(anArray[2], col20[0]);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
string[] anArrayString = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArrayString);
helper.MoveItemTest(collection, 0, 2);
helper.MoveItemTest(collection, 3, 0);
helper.MoveItemTest(collection, 1, 2);
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the source or destination
/// Index is >= collection.Count or Index < 0.
/// </summary>
/// <remarks>
/// When the sourceIndex is valid, the item actually is removed from the list.
/// </remarks>
[Fact]
public static void MoveTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = null;
int validIndex = 2;
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
int[] iArrLargeValues = new Int32[] { anArray.Length, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrInvalidValues)
{
collection = new ObservableCollection<string>(anArray);
collection.CollectionChanged += (o, e) =>
{
Assert.True(false, "Should not have thrown collection changed event when removing items from invalid indices");
};
// invalid startIndex, valid destination index.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(index, validIndex));
Assert.Equal(anArray.Length, collection.Count);
// valid startIndex, invalid destIndex.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(validIndex, index));
//NOTE: It actually moves the item right out of the collection.So the count is one less.
//Assert.Equal(anArray.Length, collection.Count, "Collection should not have changed. index: " + index);
}
foreach (var index in iArrLargeValues)
{
collection = new ObservableCollection<string>(anArray);
collection.CollectionChanged += (o, e) =>
{
Assert.True(false, "Should not have thrown collection changed event when removing items from invalid indices");
};
// invalid startIndex, valid destination index.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(index, validIndex));
Assert.Equal(anArray.Length, collection.Count);
// valid startIndex, invalid destIndex.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(validIndex, index));
//NOTE: It actually moves the item right out of the collection. So the count is one less.
//Assert.Equal(anArray.Length, collection.Count, "Collection should not have changed.");
}
}
/// <summary>
/// Tests that an item can be inserted throughout the collection.
/// </summary>
[Fact]
public static void InsertTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col3 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
//inserting item at the beginning.
Guid g0 = Guid.NewGuid();
col0.Insert(0, g0);
Assert.Equal(g0, col0[0]);
// inserting item in the middle
Guid g1 = Guid.NewGuid();
col1.Insert(1, g1);
Assert.Equal(g1, col1[1]);
// inserting item at the end.
Guid g3 = Guid.NewGuid();
col3.Insert(col3.Count, g3);
Assert.Equal(g3, col3[col3.Count - 1]);
string[] anArrayString = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArrayString);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.AddOrInsertItemTest(collection, "seven", 2);
helper.AddOrInsertItemTest(collection, "zero", 0);
helper.AddOrInsertItemTest(collection, "eight", collection.Count);
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0. And ensures that the collection does not change.
/// </summary>
[Fact]
public static void InsertTest_Negative()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
collection.CollectionChanged += (o, e) =>
{
Assert.True(false, "Should not have thrown collection changed event when removing items from invalid indices");
};
Guid itemToInsert = Guid.NewGuid();
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(index, itemToInsert));
Assert.Equal(anArray.Length, collection.Count);
}
int[] iArrLargeValues = new Int32[] { collection.Count + 1, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(index, itemToInsert));
Assert.Equal(anArray.Length, collection.Count);
}
}
/// <summary>
/// Tests that the appropriate collectionchanged event is fired when
/// an item is replaced in the collection.
/// </summary>
[Fact]
public static void ReplaceItemTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.ReplaceItemTest(collection, 1, "seven");
helper.ReplaceItemTest(collection, 3, "zero");
}
/// <summary>
/// Tests that contains returns true when the item is in the collection
/// and false otherwise.
/// </summary>
[Fact]
public static void ContainsTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
string collectionString = "";
foreach (var item in collection)
collectionString += item + ", ";
for (int i = 0; i < collection.Count; ++i)
Assert.True(collection.Contains(anArray[i]), "ObservableCollection did not contain the item: " + anArray[i] + " Collection: " + collectionString);
string g = "six";
Assert.False(collection.Contains(g), "Collection contained an item that should not have been there. guid: " + g + " Collection: " + collectionString);
Assert.False(collection.Contains(null), "Collection should not have contained null. Collection: " + collectionString);
}
/// <summary>
/// Tests that the index of an item can be retrieved when the item is
/// in the collection and -1 otherwise.
/// </summary>
[Fact]
public static void IndexOfTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(i, collection.IndexOf(anArray[i]));
Assert.Equal(-1, collection.IndexOf("seven"));
Assert.Equal(-1, collection.IndexOf(null));
// testing that the first occurance is the index returned.
ObservableCollection<int> intCol = new ObservableCollection<int>();
for (int i = 0; i < 4; ++i)
intCol.Add(i % 2);
Assert.Equal(0, intCol.IndexOf(0));
Assert.Equal(1, intCol.IndexOf(1));
IList colAsIList = (IList)intCol;
var index = colAsIList.IndexOf("stringObj");
Assert.Equal(-1, index);
}
/// <summary>
/// Tests that the collection can be copied into a destination array.
/// </summary>
[Fact]
public static void CopyToTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
string[] aCopy = new string[collection.Count];
collection.CopyTo(aCopy, 0);
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(anArray[i], aCopy[i]);
// copy observable collection starting in middle, where array is larger than source.
aCopy = new string[collection.Count + 2];
int offsetIndex = 1;
collection.CopyTo(aCopy, offsetIndex);
for (int i = 0; i < aCopy.Length; i++)
{
string value = aCopy[i];
if (i == 0)
Assert.True(null == value, "Should not have a value since we did not start copying there.");
else if (i == (aCopy.Length - 1))
Assert.True(null == value, "Should not have a value since the collection is shorter than the copy array..");
else
{
int indexInCollection = i - offsetIndex;
Assert.Equal(collection[indexInCollection], aCopy[i]);
}
}
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0.
/// ArgumentException when the destination array does not have enough space to
/// contain the source Collection.
/// ArgumentNullException when the destination array is null.
/// </summary>
[Fact]
public static void CopyToTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArray);
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
string[] aCopy = new string[collection.Count];
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(aCopy, index));
}
int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
string[] aCopy = new string[collection.Count];
Assert.Throws<ArgumentException>(() => collection.CopyTo(aCopy, index));
}
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 1));
string[] copy = new string[collection.Count - 1];
Assert.Throws<ArgumentException>(() => collection.CopyTo(copy, 0));
copy = new string[0];
Assert.Throws<ArgumentException>(() => collection.CopyTo(copy, 0));
}
/// <summary>
/// Tests that it is possible to iterate through the collection with an
/// Enumerator.
/// </summary>
[Fact]
public static void GetEnumeratorTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
int i = 0;
IEnumerator<Guid> e;
for (e = col.GetEnumerator(); e.MoveNext(); ++i)
{
Assert.Equal(anArray[i], e.Current);
}
Assert.Equal(col.Count, i);
e.Dispose();
}
}
/// <summary>
/// Helper class to test the CollectionChanged and PropertyChanged Events.
/// </summary>
public class CollectionAndPropertyChangedTester
{
#region Properties
private const string COUNT = "Count";
private const string ITEMARRAY = "Item[]";
// Number of collection changed events that were ACTUALLY fired.
public int NumCollectionChangedFired { get; private set; }
// Number of collection changed events that are EXPECTED to be fired.
public int ExpectedCollectionChangedFired { get; private set; }
public int ExpectedNewStartingIndex { get; private set; }
public NotifyCollectionChangedAction ExpectedAction { get; private set; }
public IList ExpectedNewItems { get; private set; }
public IList ExpectedOldItems { get; private set; }
public int ExpectedOldStartingIndex { get; private set; }
private PropertyNameExpected[] _expectedPropertyChanged;
#endregion
#region Helper Methods
/// <summary>
/// Will perform an Add or Insert on the given Collection depending on whether the
/// insertIndex is null or not. If it is null, will Add, otherwise, will Insert.
/// </summary>
public void AddOrInsertItemTest(ObservableCollection<string> collection, string itemToAdd, int? insertIndex = null)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Add;
ExpectedNewItems = new string[] { itemToAdd };
if (insertIndex.HasValue)
ExpectedNewStartingIndex = insertIndex.Value;
else
ExpectedNewStartingIndex = collection.Count;
ExpectedOldItems = null;
ExpectedOldStartingIndex = -1;
int expectedCount = collection.Count + 1;
if (insertIndex.HasValue)
{
collection.Insert(insertIndex.Value, itemToAdd);
Assert.Equal(itemToAdd, collection[insertIndex.Value]);
}
else
{
collection.Add(itemToAdd);
Assert.Equal(itemToAdd, collection[collection.Count - 1]);
}
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just added an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Clears the given Collection.
/// </summary>
public void ClearTest(ObservableCollection<string> collection)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Reset;
ExpectedNewItems = null;
ExpectedNewStartingIndex = -1;
ExpectedOldItems = null;
ExpectedOldStartingIndex = -1;
collection.Clear();
Assert.Equal(0, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just cleared the collection");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Given a collection, will move an item from the oldIndex to the newIndex.
/// </summary>
public void MoveItemTest(ObservableCollection<string> collection, int oldIndex, int newIndex)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) };
collection.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[oldIndex];
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Move;
ExpectedNewItems = new string[] { itemAtOldIndex };
ExpectedNewStartingIndex = newIndex;
ExpectedOldItems = new string[] { itemAtOldIndex };
ExpectedOldStartingIndex = oldIndex;
int expectedCount = collection.Count;
collection.Move(oldIndex, newIndex);
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(itemAtOldIndex, collection[newIndex]);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just moved an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Will set that new item at the specified index in the given collection.
/// </summary>
public void ReplaceItemTest(ObservableCollection<string> collection, int index, string newItem)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) };
collection.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[index];
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Replace;
ExpectedNewItems = new string[] { newItem };
ExpectedNewStartingIndex = index;
ExpectedOldItems = new string[] { itemAtOldIndex };
ExpectedOldStartingIndex = index;
int expectedCount = collection.Count;
collection[index] = newItem;
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(newItem, collection[index]);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just replaced an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Given a collection, index and item to remove, will try to remove that item
/// from the index. If the item has duplicates, will verify that only the first
/// instance was removed.
/// </summary>
public void RemoveItemTest(ObservableCollection<string> collection, int itemIndex, string itemToRemove, bool isSuccessfulRemove, bool hasDuplicates)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
if (isSuccessfulRemove)
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Remove;
ExpectedNewItems = null;
ExpectedNewStartingIndex = -1;
ExpectedOldItems = new string[] { itemToRemove };
ExpectedOldStartingIndex = itemIndex;
int expectedCount = isSuccessfulRemove ? collection.Count - 1 : collection.Count;
bool removedItem = collection.Remove(itemToRemove);
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
if (isSuccessfulRemove)
{
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since there were items removed.");
Assert.True(removedItem, "Should have been successful in removing the item.");
}
else
{
foreach (var item in _expectedPropertyChanged)
Assert.False(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since there were no items removed.");
Assert.False(removedItem, "Should not have been successful in removing the item.");
}
if (hasDuplicates)
return;
// ensuring that the item is not in the collection.
for (int i = 0; i < collection.Count; i++)
{
if (itemToRemove == collection[i])
{
string itemsInCollection = "";
foreach (var item in collection)
itemsInCollection += item + ", ";
Assert.True(false, "Found item (" + itemToRemove + ") that should not be in the collection because we tried to remove it. Collection: " + itemsInCollection);
}
}
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Verifies that the item is removed from a given index in the collection.
/// </summary>
public void RemoveItemAtTest(ObservableCollection<string> collection, int itemIndex)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[itemIndex];
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Remove;
ExpectedNewItems = null;
ExpectedNewStartingIndex = -1;
ExpectedOldItems = new string[] { itemAtOldIndex };
ExpectedOldStartingIndex = itemIndex;
int expectedCount = collection.Count - 1;
collection.RemoveAt(itemIndex);
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just removed an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Verifies that the eventargs fired matches the expected results.
/// </summary>
private void VerifyEventArgs(NotifyCollectionChangedEventArgs e)
{
Assert.Equal(ExpectedNewStartingIndex, e.NewStartingIndex);
Assert.Equal(ExpectedOldStartingIndex, e.OldStartingIndex);
if (ExpectedNewItems != null)
{
foreach (var newItem in e.NewItems)
Assert.True(ExpectedNewItems.Contains(newItem), "newItem was not in the ExpectedNewItems. newItem: " + newItem);
foreach (var expectedItem in ExpectedNewItems)
Assert.True(e.NewItems.Contains(expectedItem), "expectedItem was not in e.NewItems. expectedItem: " + expectedItem);
}
else
{
Assert.Null(e.NewItems);
}
if (ExpectedOldItems != null)
{
foreach (var oldItem in e.OldItems)
Assert.True(ExpectedOldItems.Contains(oldItem), "oldItem was not in the ExpectedOldItems. oldItem: " + oldItem);
foreach (var expectedItem in ExpectedOldItems)
Assert.True(e.OldItems.Contains(expectedItem), "expectedItem was not in e.OldItems. expectedItem: " + expectedItem);
}
else
{
Assert.Null(e.OldItems);
}
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
NumCollectionChangedFired++;
Assert.Equal(ExpectedAction, e.Action);
switch (ExpectedAction)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Move:
case NotifyCollectionChangedAction.Reset:
case NotifyCollectionChangedAction.Replace:
VerifyEventArgs(e);
break;
default:
throw new NotSupportedException("Does not support this action yet.");
}
}
private void Collection_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
foreach (var item in _expectedPropertyChanged)
{
if (item.Name == e.PropertyName)
item.IsFound = true;
}
}
/// <summary>
/// Helper class to keep track of what propertychanges we expect and whether they were found or not.
/// </summary>
private class PropertyNameExpected
{
internal PropertyNameExpected(string name)
{
Name = name;
}
internal string Name { get; private set; }
internal bool IsFound { get; set; }
}
#endregion
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_821 : MapLoop
{
public M_821() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new B2A() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 4 },
new TRN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 2 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_FA1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_ENT(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
//1000
public class L_LM : MapLoop
{
public L_LM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_LQ(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
});
}
}
//1100
public class L_LQ : MapLoop
{
public L_LQ(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
});
}
}
//2000
public class L_FA1 : MapLoop
{
public L_FA1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3000
public class L_ENT : MapLoop
{
public L_ENT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ENT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new L_ACT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_FA1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3100
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3200
public class L_ACT : MapLoop
{
public L_ACT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ACT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_RTE(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 13 },
new L_BLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_TSU(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_FIR(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3210
public class L_LM_1 : MapLoop
{
public L_LM_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_LQ_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
});
}
}
//3211
public class L_LQ_1 : MapLoop
{
public L_LQ_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
});
}
}
//3220
public class L_RTE : MapLoop
{
public L_RTE(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new RTE() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3230
public class L_BLN : MapLoop
{
public L_BLN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AVA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3240
public class L_TSU : MapLoop
{
public L_TSU(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new TSU() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AVA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3250
public class L_FIR : MapLoop
{
public L_FIR(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FIR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new AVA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new TRN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new RTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3251
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3300
public class L_FA1_1 : MapLoop
{
public L_FA1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Correspondence.Conditions;
using Correspondence.Mementos;
using Correspondence.Queries;
using Correspondence.Strategy;
using Correspondence.Tasks;
using Assisticant.Fields;
namespace Correspondence
{
class Model
{
public const short MaxDataLength = 1024;
private const long ClientDatabaseId = 0;
private Community _community;
private IStorageStrategy _storageStrategy;
private bool _clientApp = true;
private IDictionary<CorrespondenceFactType, ICorrespondenceFactFactory> _factoryByType =
new Dictionary<CorrespondenceFactType, ICorrespondenceFactFactory>();
private IDictionary<CorrespondenceFactType, List<QueryInvalidator>> _queryInvalidatorsByType =
new Dictionary<CorrespondenceFactType, List<QueryInvalidator>>();
private IDictionary<CorrespondenceFactType, List<Unpublisher>> _unpublishersByType =
new Dictionary<CorrespondenceFactType, List<Unpublisher>>();
private IDictionary<CorrespondenceFactType, FactMetadata> _metadataByFactType = new Dictionary<CorrespondenceFactType, FactMetadata>();
private IDictionary<FactID, CorrespondenceFact> _factByID = new Dictionary<FactID, CorrespondenceFact>();
private IDictionary<FactMemento, CorrespondenceFact> _factByMemento = new Dictionary<FactMemento, CorrespondenceFact>();
private IDictionary<FactMemento, Observable<CorrespondenceFact>> _findFactByMemento = new Dictionary<FactMemento, Observable<CorrespondenceFact>>();
private Observable<Exception> _lastException = new Observable<Exception>();
public event Action<CorrespondenceFact> FactAdded;
public event Action<FactID> FactReceived;
public Model(Community community, IStorageStrategy storageStrategy)
{
_community = community;
_storageStrategy = storageStrategy;
}
public bool ClientApp
{
get { return _clientApp; }
set { _clientApp = value; }
}
public void AddType(CorrespondenceFactType type, ICorrespondenceFactFactory factory, FactMetadata factMetadata)
{
_factoryByType[type] = factory;
_metadataByFactType.Add(type, factMetadata);
}
public void AddQuery(CorrespondenceFactType type, QueryDefinition query)
{
// Invert the query.
new QueryInverter(type, delegate(CorrespondenceFactType targetType, QueryDefinition inverse)
{
// Record the inverse as a query invalidator by the target type.
List<QueryInvalidator> invalidators;
if (!_queryInvalidatorsByType.TryGetValue(targetType, out invalidators))
{
invalidators = new List<QueryInvalidator>();
_queryInvalidatorsByType.Add(targetType, invalidators);
}
invalidators.Add(new QueryInvalidator(inverse, query));
})
.InvertQuery(query.Joins);
}
public void AddUnpublisher(RoleMemento role, Condition publishCondition)
{
// Invert the query.
var queryInverter = new QueryInverter(role.DeclaringType, delegate(CorrespondenceFactType targetType, QueryDefinition inverse)
{
// Record the inverse as an unpublisher by the target type.
List<Unpublisher> unpublishers;
if (!_unpublishersByType.TryGetValue(targetType, out unpublishers))
{
unpublishers = new List<Unpublisher>();
_unpublishersByType.Add(targetType, unpublishers);
}
unpublishers.Add(new Unpublisher(inverse, publishCondition, role));
});
publishCondition.Accept(queryInverter);
}
public IDisposable BeginDuration()
{
return _storageStrategy.BeginDuration();
}
public T AddFact<T>(T prototype) where T : CorrespondenceFact
{
return AddFact<T>(prototype, 0);
}
private T AddFact<T>(T prototype, int peerId) where T : CorrespondenceFact
{
// Save invalidate actions until after the lock
// because they reenter if a fact is removed.
Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries = new Dictionary<InvalidatedQuery, InvalidatedQuery>();
lock (this)
{
if (prototype.InternalCommunity != null)
throw new CorrespondenceException("A fact may only belong to one community");
foreach (RoleMemento role in prototype.PredecessorRoles)
{
PredecessorBase predecessor = prototype.GetPredecessor(role);
if (predecessor.Community != null && predecessor.Community != _community)
throw new CorrespondenceException("A fact cannot be added to a different community than its predecessors.");
}
FactMemento memento = CreateMementoFromFact(prototype);
// See if we already have the fact in memory.
CorrespondenceFact fact;
if (_factByMemento.TryGetValue(memento, out fact))
return (T)fact;
FactID id = AddFactMemento(peerId, memento, invalidatedQueries);
// Turn the prototype into the real fact.
prototype.ID = id;
prototype.SetCommunity(_community);
_factByID.Add(prototype.ID, prototype);
_factByMemento.Add(memento, prototype);
}
foreach (InvalidatedQuery invalidatedQuery in invalidatedQueries.Keys)
invalidatedQuery.Invalidate();
if (FactAdded != null)
FactAdded(prototype);
return prototype;
}
public T FindFact<T>(T prototype)
where T : CorrespondenceFact
{
lock (this)
{
ICorrespondenceFactFactory factory;
FactMemento memento = CreateMementoFromFact(prototype, out factory);
Observable<CorrespondenceFact> independent;
if (!_findFactByMemento.TryGetValue(memento, out independent))
{
var completion = new TaskCompletionSource<CorrespondenceFact>();
CorrespondenceFact fact = factory.GetUnloadedInstance();
fact.SetLoadedTask(completion.Task);
independent = new Observable<CorrespondenceFact>(fact);
_findFactByMemento.Add(memento, independent);
FindFactAndStore(memento, prototype, factory, independent, completion);
}
return (T)independent.Value;
}
}
public CorrespondenceFact LoadFact(string factName)
{
FactID id;
if (_storageStrategy.GetID(factName, out id))
return GetFactByID(id);
else
return null;
}
public void SetFact(string factName, CorrespondenceFact obj)
{
_storageStrategy.SetID(factName, obj.ID);
}
public FactTreeMemento GetMessageBodies(ref TimestampID timestamp, int peerId, List<UnpublishMemento> unpublishedMessages)
{
FactTreeMemento result = new FactTreeMemento(ClientDatabaseId);
IEnumerable<MessageMemento> recentMessages = _storageStrategy.LoadRecentMessagesForServer(peerId, timestamp);
foreach (MessageMemento message in recentMessages)
{
if (message.FactId.key > timestamp.Key)
timestamp = new TimestampID(ClientDatabaseId, message.FactId.key);
FactMemento newFact = AddToFactTree(result, message.FactId, peerId);
FactMetadata factMetadata;
if (newFact != null && _metadataByFactType.TryGetValue(newFact.FactType, out factMetadata))
{
IEnumerable<CorrespondenceFactType> convertableTypes = factMetadata.ConvertableTypes;
foreach (CorrespondenceFactType convertableType in convertableTypes)
{
List<Unpublisher> unpublishers;
if (_unpublishersByType.TryGetValue(convertableType, out unpublishers))
{
foreach (Unpublisher unpublisher in unpublishers)
{
IEnumerable<FactID> messageIds = _storageStrategy.QueryForIds(unpublisher.MessageFacts, message.FactId);
foreach (FactID messageId in messageIds)
{
ConditionEvaluator conditionEvaluator = new ConditionEvaluator(_storageStrategy);
bool published = conditionEvaluator.Evaluate(messageId, unpublisher.PublishCondition);
if (!published)
{
AddToFactTree(result, messageId, peerId);
UnpublishMemento unpublishMemento = new UnpublishMemento(messageId, unpublisher.Role);
if (!unpublishedMessages.Contains(unpublishMemento))
unpublishedMessages.Add(unpublishMemento);
}
}
}
}
}
}
}
return result;
}
public FactMemento AddToFactTree(FactTreeMemento messageBody, FactID factId, int peerId)
{
if (!messageBody.Contains(factId))
{
CorrespondenceFact fact = GetFactByID(factId);
if (fact != null)
{
FactID remoteId;
if (_storageStrategy.GetRemoteId(factId, peerId, out remoteId))
{
messageBody.Add(new IdentifiedFactRemote(factId, remoteId));
}
else
{
FactMemento factMemento = CreateMementoFromFact(fact);
foreach (PredecessorMemento predecessor in factMemento.Predecessors)
AddToFactTree(messageBody, predecessor.ID, peerId);
messageBody.Add(new IdentifiedFactMemento(factId, factMemento));
return factMemento;
}
}
return null;
}
else
{
IdentifiedFactBase identifiedFact = messageBody.Get(factId);
if (identifiedFact is IdentifiedFactMemento)
return ((IdentifiedFactMemento)identifiedFact).Memento;
else
return null;
}
}
public void ReceiveMessage(FactTreeMemento messageBody, int peerId)
{
Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries = new Dictionary<InvalidatedQuery, InvalidatedQuery>();
lock (this)
{
IDictionary<FactID, FactID> localIdByRemoteId = new Dictionary<FactID, FactID>();
foreach (IdentifiedFactBase identifiedFact in messageBody.Facts)
{
FactID localId = ReceiveFact(identifiedFact, peerId, invalidatedQueries, localIdByRemoteId);
FactID remoteId = identifiedFact.Id;
localIdByRemoteId.Add(remoteId, localId);
}
}
foreach (InvalidatedQuery invalidatedQuery in invalidatedQueries.Keys)
invalidatedQuery.Invalidate();
}
private FactID ReceiveFact(IdentifiedFactBase identifiedFact, int peerId, Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries, IDictionary<FactID, FactID> localIdByRemoteId)
{
if (identifiedFact is IdentifiedFactMemento)
{
IdentifiedFactMemento identifiedFactMemento = (IdentifiedFactMemento)identifiedFact;
FactMemento translatedMemento = new FactMemento(identifiedFactMemento.Memento.FactType);
translatedMemento.Data = identifiedFactMemento.Memento.Data;
translatedMemento.AddPredecessors(identifiedFactMemento.Memento.Predecessors
.Select(remote =>
{
FactID localFactId;
return !localIdByRemoteId.TryGetValue(remote.ID, out localFactId)
? null
: new PredecessorMemento(remote.Role, localFactId, remote.IsPivot);
})
.Where(pred => pred != null));
FactID localId = AddFactMemento(peerId, translatedMemento, invalidatedQueries);
_storageStrategy.SaveShare(peerId, identifiedFact.Id, localId);
return localId;
}
else
{
IdentifiedFactRemote identifiedFactRemote = (IdentifiedFactRemote)identifiedFact;
return _storageStrategy.GetFactIDFromShare(peerId, identifiedFactRemote.RemoteId);
}
}
public CorrespondenceFact GetFactByID(FactID id)
{
// Check for null.
if (id.key == 0)
return null;
lock (this)
{
// See if the object is already loaded.
CorrespondenceFact obj;
if (_factByID.TryGetValue(id, out obj))
return obj;
// If not, load it from storage.
FactMemento memento = _storageStrategy.Load(id);
return CreateFactFromMemento(id, memento);
}
}
public Guid ClientDatabaseGuid
{
get { return _storageStrategy.ClientGuid; }
}
public bool InvokeTransform(ITransform transform)
{
IdentifiedFactMemento factMemento = _storageStrategy.LoadNextFact(transform.LastFactId);
if (factMemento == null)
return false;
CorrespondenceFact nextFact = GetFactByIdAndMemento(factMemento.Id, factMemento.Memento);
transform.Transform(nextFact, factMemento.Id, f => f.ID);
return true;
}
internal Task<List<CorrespondenceFact>> ExecuteQueryAsync(QueryDefinition queryDefinition, FactID startingId, QueryOptions options)
{
Task<List<IdentifiedFactMemento>> task = _storageStrategy.QueryForFactsAsync(queryDefinition, startingId, options);
if (task.CompletedSynchronously)
{
List<IdentifiedFactMemento> facts = task.Result;
lock (this)
{
return Task<List<CorrespondenceFact>>.FromResult(facts
.Select(m => GetFactByIdAndMemento(m.Id, m.Memento))
.Where(m => m != null)
.ToList());
}
}
else
{
return task.ContinueWith(delegate(Task<List<IdentifiedFactMemento>> t)
{
List<IdentifiedFactMemento> facts = task.Result;
lock (this)
{
return facts
.Select(m => GetFactByIdAndMemento(m.Id, m.Memento))
.Where(m => m != null)
.ToList();
}
});
}
}
private CorrespondenceFact GetFactByIdAndMemento(FactID id, FactMemento memento)
{
// Check for null.
if (id.key == 0)
return null;
// See if the fact is already loaded.
CorrespondenceFact fact;
if (_factByID.TryGetValue(id, out fact))
return fact;
// If not, create it from the memento.
return CreateFactFromMemento(id, memento);
}
private CorrespondenceFact CreateFactFromMemento(FactID id, FactMemento memento)
{
try
{
System.Diagnostics.Debug.Assert(
!_factByMemento.ContainsKey(memento),
"A memento already in memory is being reloaded");
// Invoke the factory to create the object.
if (memento == null)
throw new CorrespondenceException("Failed to load fact");
CorrespondenceFact fact = HydrateFact(memento);
fact.ID = id;
fact.SetCommunity(_community);
_factByID.Add(fact.ID, fact);
_factByMemento.Add(memento, fact);
return fact;
}
catch (Exception ex)
{
HandleException(ex);
return null;
}
}
private CorrespondenceFact HydrateFact(FactMemento memento)
{
ICorrespondenceFactFactory factory;
if (!_factoryByType.TryGetValue(memento.FactType, out factory))
throw new CorrespondenceException(string.Format("Unknown type: {0}", memento.FactType));
CorrespondenceFact fact = factory.CreateFact(memento);
if (fact == null)
throw new CorrespondenceException("Failed to create fact");
return fact;
}
private FactMemento CreateMementoFromFact(CorrespondenceFact prototype)
{
ICorrespondenceFactFactory factory;
return CreateMementoFromFact(prototype, out factory);
}
private FactMemento CreateMementoFromFact(CorrespondenceFact prototype, out ICorrespondenceFactFactory factory)
{
// Get the type of the object.
CorrespondenceFactType type = prototype.GetCorrespondenceFactType();
// Find the factory for that type.
if (!_factoryByType.TryGetValue(type, out factory))
throw new CorrespondenceException(string.Format("Add the type {0} or the assembly that contains it to the community.", type));
// Create the memento.
FactMemento memento = new FactMemento(type);
foreach (RoleMemento role in prototype.PredecessorRoles)
{
PredecessorBase predecessor = prototype.GetPredecessor(role);
foreach (FactID id in predecessor.InternalFactIds)
memento.AddPredecessor(role, id, role.IsPivot);
}
using (MemoryStream data = new MemoryStream())
{
using (BinaryWriter output = new BinaryWriter(data))
{
factory.WriteFactData(prototype, output);
}
memento.Data = data.ToArray();
if (memento.Data.Length > MaxDataLength)
throw new CorrespondenceException(string.Format("Fact data length {0} exceeded the maximum bytes allowable ({1}).", memento.Data.Length, Model.MaxDataLength));
}
return memento;
}
private FactID AddFactMemento(int peerId, FactMemento memento, Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries)
{
// Set the ID and add the object to the community.
FactID id;
if (_storageStrategy.Save(memento, peerId, out id))
{
// Invalidate all of the queries affected by the new object.
List<QueryInvalidator> invalidators;
FactMetadata metadata;
if (_metadataByFactType.TryGetValue(memento.FactType, out metadata))
{
foreach (CorrespondenceFactType factType in metadata.ConvertableTypes)
if (_queryInvalidatorsByType.TryGetValue(factType, out invalidators))
{
foreach (QueryInvalidator invalidator in invalidators)
{
List<FactID> targetFactIds;
if (invalidator.TargetFacts.CanExecuteFromMemento)
// If the inverse query is simple, the results are already in the memento.
targetFactIds = invalidator.TargetFacts.ExecuteFromMemento(memento);
else
// The query is more complex, so go to the storage strategy.
targetFactIds = _storageStrategy.QueryForIds(invalidator.TargetFacts, id).ToList();
foreach (FactID targetObjectId in targetFactIds)
{
CorrespondenceFact targetObject;
if (_factByID.TryGetValue(targetObjectId, out targetObject))
{
QueryDefinition invalidQuery = invalidator.InvalidQuery;
InvalidatedQuery query = new InvalidatedQuery(targetObject, invalidQuery);
if (!invalidatedQueries.ContainsKey(query))
invalidatedQueries.Add(query, query);
}
}
}
}
}
if (FactReceived != null)
FactReceived(id);
}
return id;
}
private void FindFactAndStore(FactMemento memento, CorrespondenceFact prototype, ICorrespondenceFactFactory factory, Observable<CorrespondenceFact> independent, TaskCompletionSource<CorrespondenceFact> completion)
{
try
{
CorrespondenceFact fact;
lock (this)
{
// See if we already have the fact in memory.
if (!_factByMemento.TryGetValue(memento, out fact))
{
// If the object is already in storage, load it.
var task = _storageStrategy.FindExistingFactAsync(memento);
task.ContinueWith(t => StoreFact(t, memento, prototype, factory, independent, completion));
}
else
{
independent.Value = fact;
}
}
if (fact != null)
completion.SetResult(fact);
}
catch (Exception x)
{
HandleException(x);
}
}
private void StoreFact(Task<FactID?> t, FactMemento memento, CorrespondenceFact prototype, ICorrespondenceFactFactory factory, Observable<CorrespondenceFact> independent, TaskCompletionSource<CorrespondenceFact> completion)
{
CorrespondenceFact fact;
lock (this)
{
if (t.Result.HasValue)
{
prototype.ID = t.Result.Value;
prototype.SetCommunity(_community);
_factByID.Add(prototype.ID, prototype);
_factByMemento.Add(memento, prototype);
fact = prototype;
}
else
{
fact = factory.GetNullInstance();
}
independent.Value = fact;
}
completion.SetResult(fact);
}
private void HandleException(Exception exception)
{
_lastException.Value = exception;
}
public Exception LastException
{
get { return _lastException; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using TestLibrary;
public class StringConcat5
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
public static int Main()
{
StringConcat5 sc5 = new StringConcat5();
TestLibrary.TestFramework.BeginTestCase("StringConcat5");
if (sc5.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
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;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PostTest1:Concat two null ");
try
{
strA = null;
strB = null;
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("001", "Concat two null ExpectResult is" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PostTest2:Concat null and empty");
try
{
strA = null;
strB = "";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("003", "Concat null string and empty ExpectResult is" + MergeString(strA,strB) + " ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest3:Concat null and space");
try
{
strA = null;
strB = "\u0020";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("005", "Concat null and space ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest4: Concat empty and space");
try
{
strA = "";
strB = "\u0020";
ActualResult = string.Concat(strA,strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("007", "Concat empty and space ExpectResult is" + MergeString(strA,strB)+ " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest5:Concat \0 and space");
try
{
strA = "\0";
strB = "u0020";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("009", "Concat \0 and space ExpectResult is equel" + MergeString(strA,strB) + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest6: Concat null and not nullstring");
try
{
strA = null;
strB = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH);
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("011", "Concat null and not nullstring ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest7: Concat empty and not nullstring");
try
{
strA = "";
strB = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("013", "Concat empty and not nullstring ExpectResult is equel" + MergeString(strA, strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest8:Concat two empty");
try
{
strA = "";
strB = "";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("015", "Concat two empty ExpectResult is equel" + MergeString(strA,strB) + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest9: Concat two not nullstrings one");
try
{
string strBasic = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
strA = strBasic + "\n";
strB = strBasic;
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("017", "Concat two not nullstrings one ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest10:Concat some special symbols ");
try
{
strA = new string('\t', 2);
strB = "\uffff";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("019", "Concat some special symbols ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest11:Concat tab and space ");
try
{
strA = "\u0009";
strB = "\u0020";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("021", "Concat tab and space ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest12:Concat two not nullstrings two ");
try
{
strA = "Hello\t";
strB = "World";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("023", "Concat two not nullstrings two ExpectResult is equel" + MergeString(strA, strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest13:Concat two not nullstrings three");
try
{
strA = "Hello\0";
strB = "World";
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("025", "Concat two not nullstrings three ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest14:Concat two not nullstrings four");
try
{
strA = "Hello\nWorld";
strB = "I am here!";
ActualResult = string.Concat(strA, strB);
if (ActualResult !=MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("027", "Concat two not nullstrings four ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest15()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest15:Concat two not nullstrings five");
try
{
strA = "Hello\nWorld\tI am here\0....";
strB = "Welcome to you!";
ActualResult = string.Concat(strA, strB);
if (ActualResult !=MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("029", "Concat two not nullstrings five ExpectResult is equel" + MergeString(strA, strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest16()
{
bool retVal = true;
string ActualResult;
string strA;
string strB;
TestLibrary.TestFramework.BeginScenario("PosTest16:Concat string of two number of less than 0");
try
{
string stra = "hello World! ";
string strb = "Come here! ";
strA = stra.Trim();
strB = strb.Trim();
ActualResult = string.Concat(strA, strB);
if (ActualResult != MergeString(strA,strB))
{
TestLibrary.TestFramework.LogError("031", "Concat string of two number of less than 0 ExpectResult is equel" + MergeString(strA,strB) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
#region Help Method
private string MergeString(string strA, string strB)
{
if (strA == null || strA == string.Empty)
{
if (strB == null || strB == string.Empty)
{
return string.Empty;
}
else
return strB.ToString();
}
else
return strA.ToString() + strB.ToString();
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Articles.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//
// System.Web.UI.Control.cs
//
// Authors:
// Bob Smith <bob@thestuff.net>
// Gonzalo Paniagua Javier (gonzalo@ximian.com
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
// Sanjay Gupta (gsanjay@novell.com)
//
// (C) Bob Smith
// (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
// (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.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Web;
using System.Web.Util;
namespace System.Web.UI
{
[DefaultProperty ("ID"), DesignerCategory ("Code"), ToolboxItemFilter ("System.Web.UI", ToolboxItemFilterType.Require)]
[ToolboxItem ("System.Web.UI.Design.WebControlToolboxItem, " + Consts.AssemblySystem_Design)]
[Designer ("System.Web.UI.Design.ControlDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
[DesignerSerializer ("Microsoft.VSDesigner.WebForms.ControlCodeDomSerializer, " + Consts.AssemblyMicrosoft_VSDesigner,
"System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
public class Control : IComponent, IDisposable, IParserAccessor, IDataBindingsAccessor
#if NET_2_0
, IUrlResolutionService, IControlBuilderAccessor, IControlDesignerAccessor, IExpressionsAccessor
#endif
{
static readonly object DataBindingEvent = new object();
static readonly object DisposedEvent = new object();
static readonly object InitEvent = new object();
static readonly object LoadEvent = new object();
static readonly object PreRenderEvent = new object();
static readonly object UnloadEvent = new object();
static string[] defaultNameArray;
/* */
int event_mask;
const int databinding_mask = 1;
const int disposed_mask = 1 << 1;
const int init_mask = 1 << 2;
const int load_mask = 1 << 3;
const int prerender_mask = 1 << 4;
const int unload_mask = 1 << 5;
/* */
string uniqueID;
string _userId;
ControlCollection _controls;
IDictionary _childViewStates;
Control _namingContainer;
Page _page;
Control _parent;
ISite _site;
HttpContext _context;
StateBag _viewState;
EventHandlerList _events;
RenderMethod _renderMethodDelegate;
int defaultNumberID;
DataBindingCollection dataBindings;
Hashtable pendingVS; // may hold unused viewstate data from child controls
/*************/
int stateMask;
const int ENABLE_VIEWSTATE = 1;
const int VISIBLE = 1 << 1;
const int AUTOID = 1 << 2;
const int CREATING_CONTROLS = 1 << 3;
const int BINDING_CONTAINER = 1 << 4;
const int AUTO_EVENT_WIREUP = 1 << 5;
const int IS_NAMING_CONTAINER = 1 << 6;
const int VISIBLE_CHANGED = 1 << 7;
const int TRACK_VIEWSTATE = 1 << 8;
const int CHILD_CONTROLS_CREATED = 1 << 9;
const int ID_SET = 1 << 10;
const int INITED = 1 << 11;
const int INITING = 1 << 12;
const int VIEWSTATE_LOADED = 1 << 13;
const int LOADED = 1 << 14;
const int PRERENDERED = 1 << 15;
#if NET_2_0
const int ENABLE_THEMING = 1 << 16;
#endif
/*************/
static Control ()
{
defaultNameArray = new string [100];
for (int i = 0 ; i < 100 ; i++)
defaultNameArray [i] = "_ctrl" + i;
}
public Control()
{
stateMask = ENABLE_VIEWSTATE | VISIBLE | AUTOID | BINDING_CONTAINER | AUTO_EVENT_WIREUP;
if (this is INamingContainer)
stateMask |= IS_NAMING_CONTAINER;
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
public Control BindingContainer {
get {
Control container = NamingContainer;
if ((container.stateMask & BINDING_CONTAINER) == 0)
container = container.BindingContainer;
return container;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("An Identification of the control that is rendered.")]
public virtual string ClientID {
get {
string client = UniqueID;
if (client != null)
client = client.Replace (':', '_');
return client;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("The child controls of this control.")]
public virtual ControlCollection Controls //DIT
{
get
{
if (_controls == null) _controls = CreateControlCollection();
return _controls;
}
}
[DefaultValue (true), WebCategory ("Behavior")]
[WebSysDescription ("An Identification of the control that is rendered.")]
#if NET_2_0
[Themeable (true)]
#endif
public virtual bool EnableViewState {
get { return ((stateMask & ENABLE_VIEWSTATE) != 0); }
set { SetMask (ENABLE_VIEWSTATE, value); }
}
[MergableProperty (false), ParenthesizePropertyName (true)]
[WebSysDescription ("The name of the control that is rendered.")]
#if NET_2_0
[Filterable (true), Themeable (true)]
#endif
public virtual string ID {
get {
return (((stateMask & ID_SET) != 0) ? _userId : null);
}
set {
if (value == "")
value = null;
stateMask |= ID_SET;
_userId = value;
NullifyUniqueID ();
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("The container that this control is part of. The control's name has to be unique within the container.")]
public virtual Control NamingContainer {
get {
if (_namingContainer == null && _parent != null) {
if ((_parent.stateMask & IS_NAMING_CONTAINER) == 0)
_namingContainer = _parent.NamingContainer;
else
_namingContainer = _parent;
}
return _namingContainer;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("The webpage that this control resides on.")]
#if NET_2_0
[Bindable (true)]
#endif
public virtual Page Page //DIT
{
get
{
if (_page == null && _parent != null) _page = _parent.Page;
return _page;
}
set
{
_page = value;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("The parent control of this control.")]
public virtual Control Parent //DIT
{
get
{
return _parent;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[EditorBrowsable (EditorBrowsableState.Advanced), Browsable (false)]
[WebSysDescription ("The site this control is part of.")]
public ISite Site //DIT
{
get
{
return _site;
}
set
{
_site = value;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("A virtual directory containing the parent of the control.")]
public virtual string TemplateSourceDirectory {
get { return (_parent == null) ? String.Empty : _parent.TemplateSourceDirectory; }
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
[WebSysDescription ("The unique ID of the control.")]
public virtual string UniqueID {
get {
if (uniqueID != null)
return uniqueID;
if (_namingContainer == null) {
return _userId;
}
if (_userId == null)
_userId = _namingContainer.GetDefaultName ();
string prefix = _namingContainer.UniqueID;
if (_namingContainer == _page || prefix == null) {
uniqueID = _userId;
return uniqueID;
}
uniqueID = prefix + ":" + _userId;
return uniqueID;
}
}
void SetMask (int m, bool val)
{
if (val)
stateMask |= m;
else
stateMask &= ~m;
}
[DefaultValue (true), Bindable (true), WebCategory ("Behavior")]
[WebSysDescription ("Visiblity state of the control.")]
#if NET_2_0
[Localizable (true)]
#endif
public virtual bool Visible {
get {
if ((stateMask & VISIBLE) == 0)
return false;
if (_parent != null)
return _parent.Visible;
return true;
}
set {
if ((value && (stateMask & VISIBLE) == 0) ||
(!value && (stateMask & VISIBLE) != 0)) {
if (IsTrackingViewState)
stateMask |= VISIBLE_CHANGED;
}
SetMask (VISIBLE, value);
}
}
protected bool ChildControlsCreated {
get { return ((stateMask & CHILD_CONTROLS_CREATED) != 0); }
set {
if (value == false && (stateMask & CHILD_CONTROLS_CREATED) != 0)
Controls.Clear();
SetMask (CHILD_CONTROLS_CREATED, value);
}
}
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
protected virtual HttpContext Context //DIT
{
get
{
HttpContext context;
if (_context != null)
return _context;
if (_parent == null)
return HttpContext.Current;
context = _parent.Context;
if (context != null)
return context;
return HttpContext.Current;
}
}
protected EventHandlerList Events //DIT
{
get
{
if (_events == null)
{
_events = new EventHandlerList();
}
return _events;
}
}
protected bool HasChildViewState //DIT
{
get
{
if (_childViewStates == null) return false;
return true;
}
}
protected bool IsTrackingViewState {
get { return ((stateMask & TRACK_VIEWSTATE) != 0); }
}
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("ViewState")]
protected virtual StateBag ViewState
{
get
{
if(_viewState == null)
_viewState = new StateBag (ViewStateIgnoresCase);
if (IsTrackingViewState)
_viewState.TrackViewState ();
return _viewState;
}
}
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
protected virtual bool ViewStateIgnoresCase
{
get {
return false;
}
}
internal bool AutoEventWireup {
get { return (stateMask & AUTO_EVENT_WIREUP) != 0; }
set { SetMask (AUTO_EVENT_WIREUP, value); }
}
internal void SetBindingContainer (bool isBC)
{
SetMask (BINDING_CONTAINER, isBC);
}
internal void ResetChildNames ()
{
defaultNumberID = 0;
}
string GetDefaultName ()
{
string defaultName;
if (defaultNumberID > 99) {
defaultName = "_ctrl" + defaultNumberID++;
} else {
defaultName = defaultNameArray [defaultNumberID++];
}
return defaultName;
}
void NullifyUniqueID ()
{
uniqueID = null;
if (!HasControls ())
return;
foreach (Control c in Controls)
c.NullifyUniqueID ();
}
protected internal virtual void AddedControl (Control control, int index)
{
/* Ensure the control don't have more than 1 parent */
if (control._parent != null)
control._parent.Controls.Remove (control);
control._parent = this;
control._page = _page;
Control nc = ((stateMask & IS_NAMING_CONTAINER) != 0) ? this : NamingContainer;
if (nc != null) {
control._namingContainer = nc;
if (control.AutoID == true && control._userId == null)
control._userId = nc.GetDefaultName () + "a";
}
if ((stateMask & (INITING | INITED)) != 0)
control.InitRecursive (nc);
if ((stateMask & (VIEWSTATE_LOADED | LOADED)) != 0) {
if (pendingVS != null) {
object vs = pendingVS [index];
if (vs != null) {
pendingVS.Remove (index);
if (pendingVS.Count == 0)
pendingVS = null;
control.LoadViewStateRecursive (vs);
}
}
}
if ((stateMask & LOADED) != 0)
control.LoadRecursive ();
if ((stateMask & PRERENDERED) != 0)
control.PreRenderRecursiveInternal ();
}
protected virtual void AddParsedSubObject(object obj) //DIT
{
WebTrace.PushContext ("Control.AddParsedSubobject ()");
Control c = obj as Control;
WebTrace.WriteLine ("Start: {0} -> {1}", obj, (c != null) ? c.ID : String.Empty);
if (c != null) Controls.Add(c);
WebTrace.WriteLine ("End");
WebTrace.PopContext ();
}
protected void BuildProfileTree(string parentId, bool calcViewState)
{
//TODO
}
protected void ClearChildViewState ()
{
pendingVS = null;
}
protected virtual void CreateChildControls() {} //DIT
protected virtual ControlCollection CreateControlCollection() //DIT
{
return new ControlCollection(this);
}
protected virtual void EnsureChildControls ()
{
if (ChildControlsCreated == false && (stateMask & CREATING_CONTROLS) == 0) {
stateMask |= CREATING_CONTROLS;
CreateChildControls();
ChildControlsCreated = true;
stateMask &= ~CREATING_CONTROLS;
}
}
protected bool IsLiteralContent()
{
if (HasControls () && Controls.Count == 1 && (Controls [0] is LiteralControl))
return true;
return false;
}
public virtual Control FindControl (string id)
{
return FindControl (id, 0);
}
Control LookForControlByName (string id)
{
if (!HasControls ())
return null;
Control result = null;
foreach (Control c in Controls) {
if (String.Compare (id, c._userId, true) == 0) {
if (result != null && result != c) {
throw new HttpException ("1 Found more than one control with ID '" + id + "'");
}
result = c;
continue;
}
if ((c.stateMask & IS_NAMING_CONTAINER) == 0 && c.HasControls ()) {
Control child = c.LookForControlByName (id);
if (child != null) {
if (result != null && result != child)
throw new HttpException ("2 Found more than one control with ID '" + id + "'");
result = child;
}
}
}
return result;
}
protected virtual Control FindControl (string id, int pathOffset)
{
EnsureChildControls ();
Control namingContainer = null;
if ((stateMask & IS_NAMING_CONTAINER) == 0) {
namingContainer = NamingContainer;
if (namingContainer == null)
return null;
return namingContainer.FindControl (id, pathOffset);
}
if (!HasControls ())
return null;
int colon = id.IndexOf (':', pathOffset);
if (colon == -1)
return LookForControlByName (id.Substring (pathOffset));
string idfound = id.Substring (pathOffset, colon - pathOffset);
namingContainer = LookForControlByName (idfound);
if (namingContainer == null)
return null;
return namingContainer.FindControl (id, colon + 1);
}
protected virtual void LoadViewState(object savedState)
{
if (savedState != null) {
ViewState.LoadViewState (savedState);
object o = ViewState ["Visible"];
if (o != null) {
SetMask (VISIBLE, (bool) o);
stateMask |= VISIBLE_CHANGED;
}
}
}
[MonoTODO("Secure?")]
protected string MapPathSecure(string virtualPath)
{
string combined = UrlUtils.Combine (TemplateSourceDirectory, virtualPath);
return Context.Request.MapPath (combined);
}
protected virtual bool OnBubbleEvent(object source, EventArgs args) //DIT
{
return false;
}
protected virtual void OnDataBinding (EventArgs e)
{
if ((event_mask & databinding_mask) != 0) {
EventHandler eh = (EventHandler)(_events [DataBindingEvent]);
if (eh != null) eh (this, e);
}
}
protected virtual void OnInit (EventArgs e)
{
if ((event_mask & init_mask) != 0) {
EventHandler eh = (EventHandler)(_events [InitEvent]);
if (eh != null) eh (this, e);
}
}
protected virtual void OnLoad (EventArgs e)
{
if ((event_mask & load_mask) != 0) {
EventHandler eh = (EventHandler)(_events [LoadEvent]);
if (eh != null) eh (this, e);
}
}
protected virtual void OnPreRender (EventArgs e)
{
if ((event_mask & prerender_mask) != 0) {
EventHandler eh = (EventHandler)(_events [PreRenderEvent]);
if (eh != null) eh (this, e);
}
}
protected virtual void OnUnload(EventArgs e)
{
if ((event_mask & unload_mask) != 0) {
EventHandler eh = (EventHandler)(_events [UnloadEvent]);
if (eh != null) eh (this, e);
}
}
protected void RaiseBubbleEvent(object source, EventArgs args)
{
Control c = Parent;
while (c != null) {
if (c.OnBubbleEvent (source, args))
break;
c = c.Parent;
}
}
protected virtual void Render(HtmlTextWriter writer) //DIT
{
RenderChildren(writer);
}
protected virtual void RenderChildren (HtmlTextWriter writer) //DIT
{
if (_renderMethodDelegate != null) {
_renderMethodDelegate (writer, this);
} else if (HasControls ()) {
int len = Controls.Count;
for (int i = 0; i < len; i++) {
Control c = Controls [i];
c.RenderControl (writer);
}
}
}
protected virtual object SaveViewState ()
{
if ((stateMask & VISIBLE_CHANGED) != 0) {
ViewState ["Visible"] = (stateMask & VISIBLE) != 0;
} else if (_viewState == null) {
return null;
}
return _viewState.SaveViewState ();
}
protected virtual void TrackViewState()
{
if (_viewState != null)
_viewState.TrackViewState ();
stateMask |= TRACK_VIEWSTATE;
}
public virtual void Dispose ()
{
if ((event_mask & disposed_mask) != 0) {
EventHandler eh = (EventHandler)(_events [DisposedEvent]);
if (eh != null) eh (this, EventArgs.Empty);
}
}
[WebCategory ("FIXME")]
[WebSysDescription ("Raised when the contols databound properties are evaluated.")]
public event EventHandler DataBinding {
add {
event_mask |= databinding_mask;
Events.AddHandler (DataBindingEvent, value);
}
remove { Events.RemoveHandler (DataBindingEvent, value); }
}
[WebSysDescription ("Raised when the contol is disposed.")]
public event EventHandler Disposed {
add {
event_mask |= disposed_mask;
Events.AddHandler (DisposedEvent, value);
}
remove { Events.RemoveHandler (DisposedEvent, value); }
}
[WebSysDescription ("Raised when the page containing the control is initialized.")]
public event EventHandler Init {
add {
event_mask |= init_mask;
Events.AddHandler (InitEvent, value);
}
remove { Events.RemoveHandler (InitEvent, value); }
}
[WebSysDescription ("Raised after the page containing the control has been loaded.")]
public event EventHandler Load {
add {
event_mask |= load_mask;
Events.AddHandler (LoadEvent, value);
}
remove { Events.RemoveHandler (LoadEvent, value); }
}
[WebSysDescription ("Raised before the page containing the control is rendered.")]
public event EventHandler PreRender {
add {
event_mask |= prerender_mask;
Events.AddHandler (PreRenderEvent, value);
}
remove { Events.RemoveHandler (PreRenderEvent, value); }
}
[WebSysDescription ("Raised when the page containing the control is unloaded.")]
public event EventHandler Unload {
add {
event_mask |= unload_mask;
Events.AddHandler (UnloadEvent, value);
}
remove { Events.RemoveHandler (UnloadEvent, value); }
}
public virtual void DataBind() //DIT
{
#if NET_2_0
DataBind (true);
#else
OnDataBinding (EventArgs.Empty);
DataBindChildren();
#endif
}
#if NET_2_0
protected virtual
#endif
void DataBindChildren ()
{
if (!HasControls ())
return;
int len = Controls.Count;
for (int i = 0; i < len; i++) {
Control c = Controls [i];
c.DataBind ();
}
}
public virtual bool HasControls ()
{
return (_controls != null && _controls.Count > 0);
}
#if NET_2_0
public virtual
#else
public
#endif
void RenderControl (HtmlTextWriter writer)
{
if ((stateMask & VISIBLE) != 0)
Render(writer);
}
public string ResolveUrl (string relativeUrl)
{
if (relativeUrl == null)
throw new ArgumentNullException ("relativeUrl");
if (relativeUrl == "")
return "";
if (relativeUrl [0] == '#')
return relativeUrl;
string ts = TemplateSourceDirectory;
if (ts == "" || !UrlUtils.IsRelativeUrl (relativeUrl))
return relativeUrl;
HttpResponse resp = Context.Response;
return resp.ApplyAppPathModifier (UrlUtils.Combine (ts, relativeUrl));
}
internal bool HasRenderMethodDelegate () {
return _renderMethodDelegate != null;
}
[EditorBrowsable (EditorBrowsableState.Advanced)]
public void SetRenderMethodDelegate(RenderMethod renderMethod) //DIT
{
_renderMethodDelegate = renderMethod;
}
internal void LoadRecursive()
{
OnLoad (EventArgs.Empty);
if (HasControls ()) {
int len = Controls.Count;
for (int i=0;i<len;i++)
{
Control c = Controls[i];
c.LoadRecursive ();
}
}
stateMask |= LOADED;
}
internal void UnloadRecursive(Boolean dispose)
{
if (HasControls ()) {
int len = Controls.Count;
for (int i=0;i<len;i++)
{
Control c = Controls[i];
c.UnloadRecursive (dispose);
}
}
OnUnload (EventArgs.Empty);
if (dispose)
Dispose();
}
internal void PreRenderRecursiveInternal()
{
if ((stateMask & VISIBLE) != 0) {
EnsureChildControls ();
OnPreRender (EventArgs.Empty);
if (!HasControls ())
return;
int len = Controls.Count;
for (int i=0;i<len;i++)
{
Control c = Controls[i];
c.PreRenderRecursiveInternal ();
}
}
stateMask |= PRERENDERED;
}
internal void InitRecursive(Control namingContainer)
{
if (HasControls ()) {
if ((stateMask & IS_NAMING_CONTAINER) != 0)
namingContainer = this;
if (namingContainer != null &&
namingContainer._userId == null &&
namingContainer.AutoID)
namingContainer._userId = namingContainer.GetDefaultName () + "b";
int len = Controls.Count;
for (int i=0;i<len;i++)
{
Control c = Controls[i];
c._page = Page;
c._namingContainer = namingContainer;
if (namingContainer != null && c._userId == null && c.AutoID)
c._userId = namingContainer.GetDefaultName () + "c";
c.InitRecursive (namingContainer);
}
}
stateMask |= INITING;
OnInit (EventArgs.Empty);
TrackViewState ();
stateMask |= INITED;
stateMask &= ~INITING;
}
internal object SaveViewStateRecursive ()
{
if (!EnableViewState)
return null;
ArrayList controlList = null;
ArrayList controlStates = null;
int idx = -1;
if (HasControls ())
{
int len = Controls.Count;
for (int i=0;i<len;i++)
{
Control ctrl = Controls[i];
object ctrlState = ctrl.SaveViewStateRecursive ();
idx++;
if (ctrlState == null)
continue;
if (controlList == null)
{
controlList = new ArrayList ();
controlStates = new ArrayList ();
}
controlList.Add (idx);
controlStates.Add (ctrlState);
}
}
object thisState = SaveViewState ();
if (thisState == null && controlList == null && controlStates == null)
return null;
return new Triplet (thisState, controlList, controlStates);
}
internal void LoadViewStateRecursive (object savedState)
{
if (!EnableViewState || savedState == null)
return;
Triplet savedInfo = (Triplet) savedState;
LoadViewState (savedInfo.First);
ArrayList controlList = savedInfo.Second as ArrayList;
if (controlList == null)
return;
ArrayList controlStates = savedInfo.Third as ArrayList;
int nControls = controlList.Count;
for (int i = 0; i < nControls; i++) {
int k = (int) controlList [i];
if (k < Controls.Count && controlStates != null) {
Control c = Controls [k];
c.LoadViewStateRecursive (controlStates [i]);
} else {
if (pendingVS == null)
pendingVS = new Hashtable ();
pendingVS [k] = controlStates [i];
}
}
stateMask |= VIEWSTATE_LOADED;
}
void IParserAccessor.AddParsedSubObject(object obj)
{
AddParsedSubObject(obj);
}
DataBindingCollection IDataBindingsAccessor.DataBindings
{
get
{
if(dataBindings == null)
dataBindings = new DataBindingCollection();
return dataBindings;
}
}
bool IDataBindingsAccessor.HasDataBindings
{
get
{
return (dataBindings!=null && dataBindings.Count>0);
}
}
internal bool AutoID
{
get { return (stateMask & AUTOID) != 0; }
set {
if (value == false && (stateMask & IS_NAMING_CONTAINER) != 0)
return;
SetMask (AUTOID, value);
}
}
internal void PreventAutoID()
{
AutoID = false;
}
protected internal virtual void RemovedControl (Control control)
{
control.UnloadRecursive (false);
control._parent = null;
control._page = null;
control._namingContainer = null;
}
#if NET_2_0
string skinId = string.Empty;
public virtual bool EnableTheming
{
get { return (stateMask & ENABLE_THEMING) != 0; }
set { SetMask (ENABLE_THEMING, value); }
}
public virtual string SkinID
{
get { return skinId; }
set { skinId = value; }
}
protected string GetWebResourceUrl (string resourceName)
{
return Page.ClientScript.GetWebResourceUrl (GetType(), resourceName);
}
string IUrlResolutionService.ResolveClientUrl (string url)
{
throw new NotImplementedException ();
}
ControlBuilder IControlBuilderAccessor.ControlBuilder {
get {throw new NotImplementedException (); }
}
IDictionary IControlDesignerAccessor.GetDesignModeState ()
{
throw new NotImplementedException ();
}
void IControlDesignerAccessor.SetDesignModeState (IDictionary designData)
{
throw new NotImplementedException ();
}
void IControlDesignerAccessor.SetOwnerControl (Control control)
{
throw new NotImplementedException ();
}
IDictionary IControlDesignerAccessor.UserData {
get { throw new NotImplementedException (); }
}
ExpressionBindingCollection expressionBindings;
ExpressionBindingCollection IExpressionsAccessor.Expressions {
get {
if (expressionBindings == null)
expressionBindings = new ExpressionBindingCollection ();
return expressionBindings;
}
}
bool IExpressionsAccessor.HasExpressions {
get {
return (expressionBindings != null && expressionBindings.Count > 0);
}
}
[MonoTODO]
public virtual void Focus()
{
throw new NotImplementedException();
}
protected internal virtual void LoadControlState (object state)
{
}
protected internal virtual object SaveControlState ()
{
return null;
}
protected virtual void DataBind (bool raiseOnDataBinding)
{
bool foundDataItem = false;
if ((stateMask & IS_NAMING_CONTAINER) != 0 && Page != null) {
object o = DataBinder.GetDataItem (this, out foundDataItem);
if (foundDataItem)
Page.PushDataItemContext (o);
}
try {
if (raiseOnDataBinding)
OnDataBinding (EventArgs.Empty);
DataBindChildren();
} finally {
if (foundDataItem)
Page.PopDataItemContext ();
}
}
#endif
}
}
| |
namespace T5Suite2
{
partial class frmBoostAdaption
{
/// <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.groupControl1 = new DevExpress.XtraEditors.GroupControl();
this.labelControl6 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit5 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl5 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit3 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl3 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit4 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl4 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit2 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl2 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit1 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit();
this.groupControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spinEdit5.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).BeginInit();
this.SuspendLayout();
//
// groupControl1
//
this.groupControl1.Controls.Add(this.labelControl6);
this.groupControl1.Controls.Add(this.spinEdit5);
this.groupControl1.Controls.Add(this.labelControl5);
this.groupControl1.Controls.Add(this.spinEdit3);
this.groupControl1.Controls.Add(this.labelControl3);
this.groupControl1.Controls.Add(this.spinEdit4);
this.groupControl1.Controls.Add(this.labelControl4);
this.groupControl1.Controls.Add(this.spinEdit2);
this.groupControl1.Controls.Add(this.labelControl2);
this.groupControl1.Controls.Add(this.spinEdit1);
this.groupControl1.Controls.Add(this.labelControl1);
this.groupControl1.Location = new System.Drawing.Point(9, 9);
this.groupControl1.Name = "groupControl1";
this.groupControl1.Size = new System.Drawing.Size(442, 168);
this.groupControl1.TabIndex = 0;
this.groupControl1.Text = "Select boost adaption ranges";
//
// labelControl6
//
this.labelControl6.Location = new System.Drawing.Point(266, 115);
this.labelControl6.Name = "labelControl6";
this.labelControl6.Size = new System.Drawing.Size(16, 13);
this.labelControl6.TabIndex = 10;
this.labelControl6.Text = "bar";
//
// spinEdit5
//
this.spinEdit5.EditValue = new decimal(new int[] {
4,
0,
0,
131072});
this.spinEdit5.Enabled = false;
this.spinEdit5.Location = new System.Drawing.Point(171, 112);
this.spinEdit5.Name = "spinEdit5";
this.spinEdit5.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit5.Properties.Increment = new decimal(new int[] {
1,
0,
0,
131072});
this.spinEdit5.Properties.MaxValue = new decimal(new int[] {
2,
0,
0,
65536});
this.spinEdit5.Properties.MinValue = new decimal(new int[] {
1,
0,
0,
131072});
this.spinEdit5.Size = new System.Drawing.Size(70, 20);
this.spinEdit5.TabIndex = 9;
this.spinEdit5.EditValueChanged += new System.EventHandler(this.spinEdit5_EditValueChanged);
//
// labelControl5
//
this.labelControl5.Location = new System.Drawing.Point(34, 115);
this.labelControl5.Name = "labelControl5";
this.labelControl5.Size = new System.Drawing.Size(81, 13);
this.labelControl5.TabIndex = 8;
this.labelControl5.Text = "Max. boost error";
//
// spinEdit3
//
this.spinEdit3.EditValue = new decimal(new int[] {
4500,
0,
0,
0});
this.spinEdit3.Location = new System.Drawing.Point(332, 72);
this.spinEdit3.Name = "spinEdit3";
this.spinEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit3.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit3.Properties.IsFloatValue = false;
this.spinEdit3.Properties.Mask.EditMask = "N00";
this.spinEdit3.Properties.MaxValue = new decimal(new int[] {
9000,
0,
0,
0});
this.spinEdit3.Properties.MinValue = new decimal(new int[] {
1000,
0,
0,
0});
this.spinEdit3.Size = new System.Drawing.Size(70, 20);
this.spinEdit3.TabIndex = 7;
//
// labelControl3
//
this.labelControl3.Location = new System.Drawing.Point(266, 75);
this.labelControl3.Name = "labelControl3";
this.labelControl3.Size = new System.Drawing.Size(46, 13);
this.labelControl3.TabIndex = 6;
this.labelControl3.Text = "rpm upto ";
//
// spinEdit4
//
this.spinEdit4.EditValue = new decimal(new int[] {
2750,
0,
0,
0});
this.spinEdit4.Location = new System.Drawing.Point(171, 72);
this.spinEdit4.Name = "spinEdit4";
this.spinEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit4.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit4.Properties.IsFloatValue = false;
this.spinEdit4.Properties.Mask.EditMask = "N00";
this.spinEdit4.Properties.MaxValue = new decimal(new int[] {
9000,
0,
0,
0});
this.spinEdit4.Properties.MinValue = new decimal(new int[] {
1000,
0,
0,
0});
this.spinEdit4.Size = new System.Drawing.Size(70, 20);
this.spinEdit4.TabIndex = 5;
//
// labelControl4
//
this.labelControl4.Location = new System.Drawing.Point(34, 75);
this.labelControl4.Name = "labelControl4";
this.labelControl4.Size = new System.Drawing.Size(116, 13);
this.labelControl4.TabIndex = 4;
this.labelControl4.Text = "Automatic gearbox from";
//
// spinEdit2
//
this.spinEdit2.EditValue = new decimal(new int[] {
4000,
0,
0,
0});
this.spinEdit2.Location = new System.Drawing.Point(332, 46);
this.spinEdit2.Name = "spinEdit2";
this.spinEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit2.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit2.Properties.IsFloatValue = false;
this.spinEdit2.Properties.Mask.EditMask = "N00";
this.spinEdit2.Properties.MaxValue = new decimal(new int[] {
9000,
0,
0,
0});
this.spinEdit2.Properties.MinValue = new decimal(new int[] {
1000,
0,
0,
0});
this.spinEdit2.Size = new System.Drawing.Size(70, 20);
this.spinEdit2.TabIndex = 3;
//
// labelControl2
//
this.labelControl2.Location = new System.Drawing.Point(266, 49);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(46, 13);
this.labelControl2.TabIndex = 2;
this.labelControl2.Text = "rpm upto ";
//
// spinEdit1
//
this.spinEdit1.EditValue = new decimal(new int[] {
2750,
0,
0,
0});
this.spinEdit1.Location = new System.Drawing.Point(171, 46);
this.spinEdit1.Name = "spinEdit1";
this.spinEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit1.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit1.Properties.IsFloatValue = false;
this.spinEdit1.Properties.Mask.EditMask = "N00";
this.spinEdit1.Properties.MaxValue = new decimal(new int[] {
9000,
0,
0,
0});
this.spinEdit1.Properties.MinValue = new decimal(new int[] {
1000,
0,
0,
0});
this.spinEdit1.Size = new System.Drawing.Size(70, 20);
this.spinEdit1.TabIndex = 1;
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(34, 49);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(102, 13);
this.labelControl1.TabIndex = 0;
this.labelControl1.Text = "Manual gearbox from";
//
// simpleButton1
//
this.simpleButton1.Location = new System.Drawing.Point(376, 183);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(75, 23);
this.simpleButton1.TabIndex = 1;
this.simpleButton1.Text = "Ok";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// simpleButton2
//
this.simpleButton2.Location = new System.Drawing.Point(295, 183);
this.simpleButton2.Name = "simpleButton2";
this.simpleButton2.Size = new System.Drawing.Size(75, 23);
this.simpleButton2.TabIndex = 2;
this.simpleButton2.Text = "Cancel";
this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click);
//
// frmBoostAdaption
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(461, 217);
this.ControlBox = false;
this.Controls.Add(this.simpleButton2);
this.Controls.Add(this.simpleButton1);
this.Controls.Add(this.groupControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "frmBoostAdaption";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Boost adaption ranges";
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit();
this.groupControl1.ResumeLayout(false);
this.groupControl1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.spinEdit5.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraEditors.GroupControl groupControl1;
private DevExpress.XtraEditors.SpinEdit spinEdit5;
private DevExpress.XtraEditors.LabelControl labelControl5;
private DevExpress.XtraEditors.SpinEdit spinEdit3;
private DevExpress.XtraEditors.LabelControl labelControl3;
private DevExpress.XtraEditors.SpinEdit spinEdit4;
private DevExpress.XtraEditors.LabelControl labelControl4;
private DevExpress.XtraEditors.SpinEdit spinEdit2;
private DevExpress.XtraEditors.LabelControl labelControl2;
private DevExpress.XtraEditors.SpinEdit spinEdit1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.LabelControl labelControl6;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraEditors.SimpleButton simpleButton2;
}
}
| |
// Copyright (c) 2013 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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 NUnit.Framework;
using SharpYaml.Tokens;
namespace SharpYaml.Tests
{
public class ScannerTests : ScannerTestHelper
{
[Test]
public void VerifyTokensOnExample1()
{
AssertSequenceOfTokensFrom(ScannerFor("test1.yaml"),
StreamStart,
VersionDirective(1, 1),
TagDirective("!", "!foo"),
TagDirective("!yaml!", "tag:yaml.org,2002:"),
DocumentStart,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample2()
{
AssertSequenceOfTokensFrom(ScannerFor("test2.yaml"),
StreamStart,
SingleQuotedScalar("a scalar"),
StreamEnd);
}
[Test]
public void VerifyTokensOnExample3()
{
Scanner scanner = ScannerFor("test3.yaml");
AssertSequenceOfTokensFrom(scanner,
StreamStart,
DocumentStart,
SingleQuotedScalar("a scalar"),
DocumentEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample4()
{
AssertSequenceOfTokensFrom(ScannerFor("test4.yaml"),
StreamStart,
SingleQuotedScalar("a scalar"),
DocumentStart,
SingleQuotedScalar("another scalar"),
DocumentStart,
SingleQuotedScalar("yet another scalar"),
StreamEnd);
}
[Test]
public void VerifyTokensOnExample5()
{
AssertSequenceOfTokensFrom(ScannerFor("test5.yaml"),
StreamStart,
Anchor("A"),
FlowSequenceStart,
AnchorAlias("A"),
FlowSequenceEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample6()
{
AssertSequenceOfTokensFrom(ScannerFor("test6.yaml"),
StreamStart,
Tag("!!", "float"),
DoubleQuotedScalar("3.14"),
StreamEnd);
}
[Test]
public void VerifyTokensOnExample7()
{
AssertSequenceOfTokensFrom(ScannerFor("test7.yaml"),
StreamStart,
DocumentStart,
DocumentStart,
PlainScalar("a plain scalar"),
DocumentStart,
SingleQuotedScalar("a single-quoted scalar"),
DocumentStart,
DoubleQuotedScalar("a double-quoted scalar"),
DocumentStart,
LiteralScalar("a literal scalar"),
DocumentStart,
FoldedScalar("a folded scalar"),
StreamEnd);
}
[Test]
public void VerifyTokensOnExample8()
{
AssertSequenceOfTokensFrom(ScannerFor("test8.yaml"),
StreamStart,
FlowSequenceStart,
PlainScalar("item 1"),
FlowEntry,
PlainScalar("item 2"),
FlowEntry,
PlainScalar("item 3"),
FlowSequenceEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample9()
{
AssertSequenceOfTokensFrom(ScannerFor("test9.yaml"),
StreamStart,
FlowMappingStart,
Key,
PlainScalar("a simple key"),
Value,
PlainScalar("a value"),
FlowEntry,
Key,
PlainScalar("a complex key"),
Value,
PlainScalar("another value"),
FlowEntry,
FlowMappingEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample10()
{
AssertSequenceOfTokensFrom(ScannerFor("test10.yaml"),
StreamStart,
BlockSequenceStart,
BlockEntry,
PlainScalar("item 1"),
BlockEntry,
PlainScalar("item 2"),
BlockEntry,
BlockSequenceStart,
BlockEntry,
PlainScalar("item 3.1"),
BlockEntry,
PlainScalar("item 3.2"),
BlockEnd,
BlockEntry,
BlockMappingStart,
Key,
PlainScalar("key 1"),
Value,
PlainScalar("value 1"),
Key,
PlainScalar("key 2"),
Value,
PlainScalar("value 2"),
BlockEnd,
BlockEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample11()
{
AssertSequenceOfTokensFrom(ScannerFor("test11.yaml"),
StreamStart,
BlockMappingStart,
Key,
PlainScalar("a simple key"),
Value,
PlainScalar("a value"),
Key,
PlainScalar("a complex key"),
Value,
PlainScalar("another value"),
Key,
PlainScalar("a mapping"),
Value,
BlockMappingStart,
Key,
PlainScalar("key 1"),
Value,
PlainScalar("value 1"),
Key,
PlainScalar("key 2"),
Value,
PlainScalar("value 2"),
BlockEnd,
Key,
PlainScalar("a sequence"),
Value,
BlockSequenceStart,
BlockEntry,
PlainScalar("item 1"),
BlockEntry,
PlainScalar("item 2"),
BlockEnd,
BlockEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample12()
{
AssertSequenceOfTokensFrom(ScannerFor("test12.yaml"),
StreamStart,
BlockSequenceStart,
BlockEntry,
BlockSequenceStart,
BlockEntry,
PlainScalar("item 1"),
BlockEntry,
PlainScalar("item 2"),
BlockEnd,
BlockEntry,
BlockMappingStart,
Key,
PlainScalar("key 1"),
Value,
PlainScalar("value 1"),
Key,
PlainScalar("key 2"),
Value,
PlainScalar("value 2"),
BlockEnd,
BlockEntry,
BlockMappingStart,
Key,
PlainScalar("complex key"),
Value,
PlainScalar("complex value"),
BlockEnd,
BlockEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample13()
{
AssertSequenceOfTokensFrom(ScannerFor("test13.yaml"),
StreamStart,
BlockMappingStart,
Key,
PlainScalar("a sequence"),
Value,
BlockSequenceStart,
BlockEntry,
PlainScalar("item 1"),
BlockEntry,
PlainScalar("item 2"),
BlockEnd,
Key,
PlainScalar("a mapping"),
Value,
BlockMappingStart,
Key,
PlainScalar("key 1"),
Value,
PlainScalar("value 1"),
Key,
PlainScalar("key 2"),
Value,
PlainScalar("value 2"),
BlockEnd,
BlockEnd,
StreamEnd);
}
[Test]
public void VerifyTokensOnExample14()
{
AssertSequenceOfTokensFrom(ScannerFor("test14.yaml"),
StreamStart,
BlockMappingStart,
Key,
PlainScalar("key"),
Value,
BlockEntry,
PlainScalar("item 1"),
BlockEntry,
PlainScalar("item 2"),
BlockEnd,
StreamEnd);
}
private Scanner ScannerFor(string name) {
return new Scanner(YamlFile(name));
}
private void AssertSequenceOfTokensFrom(Scanner scanner, params Token[] tokens)
{
var tokenNumber = 1;
foreach (var expected in tokens)
{
Assert.True(scanner.MoveNext(), "Missing token number {0}", tokenNumber);
AssertToken(expected, scanner.Current, tokenNumber);
tokenNumber++;
}
Assert.False(scanner.MoveNext(), "Found extra tokens");
}
private void AssertToken(Token expected, Token actual, int tokenNumber)
{
Dump.WriteLine(expected.GetType().Name);
Assert.NotNull(actual);
Assert.AreEqual(expected.GetType(), actual.GetType(), "Token {0} is not of the expected type", tokenNumber);
foreach (var property in expected.GetType().GetProperties())
{
if (property.PropertyType != typeof(Mark) && property.CanRead)
{
var value = property.GetValue(actual, null);
var expectedValue = property.GetValue(expected, null);
Dump.WriteLine("\t{0} = {1}", property.Name, value);
Assert.AreEqual(expectedValue, value, "Comparing property {0} in token {1}", property.Name, tokenNumber);
}
}
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
// flibit Added This!!!
#pragma warning disable 3021
namespace OpenTK
{
/// <summary>2-component Vector of the Half type. Occupies 4 Byte total.</summary>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Vector2h : ISerializable, IEquatable<Vector2h>
{
#region Fields
/// <summary>The X component of the Half2.</summary>
public Half X;
/// <summary>The Y component of the Half2.</summary>
public Half Y;
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector2h(Half value)
{
X = value;
Y = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector2h(Single value)
{
X = new Half(value);
Y = new Half(value);
}
/// <summary>
/// The new Half2 instance will avoid conversion and copy directly from the Half parameters.
/// </summary>
/// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param>
public Vector2h(Half x, Half y)
{
X = x;
Y = y;
}
/// <summary>
/// The new Half2 instance will convert the 2 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
public Vector2h(Single x, Single y)
{
X = new Half(x);
Y = new Half(y);
}
/// <summary>
/// The new Half2 instance will convert the 2 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector2h(Single x, Single y, bool throwOnError)
{
X = new Half(x, throwOnError);
Y = new Half(y, throwOnError);
}
/// <summary>
/// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector2</param>
[CLSCompliant(false)]
public Vector2h(Vector2 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
}
/// <summary>
/// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector2</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector2h(Vector2 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
}
/// <summary>
/// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point.
/// This is the fastest constructor.
/// </summary>
/// <param name="v">OpenTK.Vector2</param>
public Vector2h(ref Vector2 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
}
/// <summary>
/// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector2</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector2h(ref Vector2 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
}
/// <summary>
/// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector2d</param>
public Vector2h(Vector2d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
}
/// <summary>
/// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector2d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector2h(Vector2d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
}
/// <summary>
/// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point.
/// This is the faster constructor.
/// </summary>
/// <param name="v">OpenTK.Vector2d</param>
[CLSCompliant(false)]
public Vector2h(ref Vector2d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
}
/// <summary>
/// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector2d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector2h(ref Vector2d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
}
#endregion Constructors
#region Half -> Single
/// <summary>
/// Returns this Half2 instance's contents as Vector2.
/// </summary>
/// <returns>OpenTK.Vector2</returns>
public Vector2 ToVector2()
{
return new Vector2(X, Y);
}
/// <summary>
/// Returns this Half2 instance's contents as Vector2d.
/// </summary>
public Vector2d ToVector2d()
{
return new Vector2d(X, Y);
}
#endregion Half -> Single
#region Conversions
/// <summary>Converts OpenTK.Vector2 to OpenTK.Half2.</summary>
/// <param name="v">The Vector2 to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector2h(Vector2 v)
{
return new Vector2h(v);
}
/// <summary>Converts OpenTK.Vector2d to OpenTK.Half2.</summary>
/// <param name="v">The Vector2d to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector2h(Vector2d v)
{
return new Vector2h(v);
}
/// <summary>Converts OpenTK.Half2 to OpenTK.Vector2.</summary>
/// <param name="h">The Half2 to convert.</param>
/// <returns>The resulting Vector2.</returns>
public static explicit operator Vector2(Vector2h h)
{
return new Vector2(h.X, h.Y);
}
/// <summary>Converts OpenTK.Half2 to OpenTK.Vector2d.</summary>
/// <param name="h">The Half2 to convert.</param>
/// <returns>The resulting Vector2d.</returns>
public static explicit operator Vector2d(Vector2h h)
{
return new Vector2d(h.X, h.Y);
}
#endregion Conversions
#region Constants
/// <summary>The size in bytes for an instance of the Half2 struct is 4.</summary>
public static readonly int SizeInBytes = 4;
#endregion Constants
#region ISerializable
/// <summary>Constructor used by ISerializable to deserialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Vector2h(SerializationInfo info, StreamingContext context)
{
this.X = (Half)info.GetValue("X", typeof(Half));
this.Y = (Half)info.GetValue("Y", typeof(Half));
}
/// <summary>Used by ISerialize to serialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("X", this.X);
info.AddValue("Y", this.Y);
}
#endregion ISerializable
#region Binary dump
/// <summary>Updates the X and Y components of this instance by reading from a Stream.</summary>
/// <param name="bin">A BinaryReader instance associated with an open Stream.</param>
public void FromBinaryStream(BinaryReader bin)
{
X.FromBinaryStream(bin);
Y.FromBinaryStream(bin);
}
/// <summary>Writes the X and Y components of this instance into a Stream.</summary>
/// <param name="bin">A BinaryWriter instance associated with an open Stream.</param>
public void ToBinaryStream(BinaryWriter bin)
{
X.ToBinaryStream(bin);
Y.ToBinaryStream(bin);
}
#endregion Binary dump
#region IEquatable<Half2> Members
/// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half2 vector.</summary>
/// <param name="other">OpenTK.Half2 to compare to this instance..</param>
/// <returns>True, if other is equal to this instance; false otherwise.</returns>
public bool Equals(Vector2h other)
{
return (this.X.Equals(other.X) && this.Y.Equals(other.Y));
}
#endregion
#region ToString()
/// <summary>Returns a string that contains this Half2's numbers in human-legible form.</summary>
public override string ToString()
{
return String.Format("({0}, {1})", X.ToString(), Y.ToString());
}
#endregion ToString()
#region BitConverter
/// <summary>Returns the Half2 as an array of bytes.</summary>
/// <param name="h">The Half2 to convert.</param>
/// <returns>The input as byte array.</returns>
public static byte[] GetBytes(Vector2h h)
{
byte[] result = new byte[SizeInBytes];
byte[] temp = Half.GetBytes(h.X);
result[0] = temp[0];
result[1] = temp[1];
temp = Half.GetBytes(h.Y);
result[2] = temp[0];
result[3] = temp[1];
return result;
}
/// <summary>Converts an array of bytes into Half2.</summary>
/// <param name="value">A Half2 in it's byte[] representation.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A new Half2 instance.</returns>
public static Vector2h FromBytes(byte[] value, int startIndex)
{
Vector2h h2 = new Vector2h();
h2.X = Half.FromBytes(value, startIndex);
h2.Y = Half.FromBytes(value, startIndex + 2);
return h2;
}
#endregion BitConverter
}
}
// flibit Added This!!!
#pragma warning restore 3021
| |
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 ClearScript.Installer.DemoWeb.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;
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class BsonReader : JsonReader
{
private const int MaxCharBytesSize = 128;
private static readonly byte[] _seqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence
private static readonly byte[] _seqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence
private static readonly byte[] _seqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence
private static readonly byte[] _seqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence
private readonly BinaryReader _reader;
private readonly List<ContainerContext> _stack;
private byte[] _byteBuffer;
private char[] _charBuffer;
private BsonType _currentElementType;
private BsonReaderState _bsonReaderState;
private ContainerContext _currentContext;
private bool _readRootValueAsArray;
private bool _jsonNet35BinaryCompatibility;
private DateTimeKind _dateTimeKindHandling;
private enum BsonReaderState
{
Normal,
ReferenceStart,
ReferenceRef,
ReferenceId,
CodeWScopeStart,
CodeWScopeCode,
CodeWScopeScope,
CodeWScopeScopeObject,
CodeWScopeScopeEnd
}
private class ContainerContext
{
public readonly BsonType Type;
public int Length;
public int Position;
public ContainerContext(BsonType type)
{
Type = type;
}
}
/// <summary>
/// Gets or sets a value indicating whether binary data reading should compatible with incorrect Json.NET 3.5 written binary.
/// </summary>
/// <value>
/// <c>true</c> if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, <c>false</c>.
/// </value>
public bool JsonNet35BinaryCompatibility
{
get { return _jsonNet35BinaryCompatibility; }
set { _jsonNet35BinaryCompatibility = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the root object will be read as a JSON array.
/// </summary>
/// <value>
/// <c>true</c> if the root object will be read as a JSON array; otherwise, <c>false</c>.
/// </value>
public bool ReadRootValueAsArray
{
get { return _readRootValueAsArray; }
set { _readRootValueAsArray = value; }
}
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get { return _dateTimeKindHandling; }
set { _dateTimeKindHandling = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
public BsonReader(Stream stream)
: this(stream, false, DateTimeKind.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
/// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(stream, "stream");
_reader = new BinaryReader(stream);
_stack = new List<ContainerContext>();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
private string ReadElement()
{
_currentElementType = ReadType();
string elementName = ReadString();
return elementName;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null.
/// </returns>
public override byte[] ReadAsBytes()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Bytes)
return (byte[])Value;
throw new JsonReaderException("Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>.</returns>
public override decimal? ReadAsDecimal()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float)
{
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal)Value;
}
throw new JsonReaderException("Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>
/// A <see cref="Nullable{DateTimeOffset}"/>.
/// </returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date)
{
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value));
return (DateTimeOffset)Value;
}
throw new JsonReaderException("Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
try
{
switch (_bsonReaderState)
{
case BsonReaderState.Normal:
return ReadNormal();
case BsonReaderState.ReferenceStart:
case BsonReaderState.ReferenceRef:
case BsonReaderState.ReferenceId:
return ReadReference();
case BsonReaderState.CodeWScopeStart:
case BsonReaderState.CodeWScopeCode:
case BsonReaderState.CodeWScopeScope:
case BsonReaderState.CodeWScopeScopeObject:
case BsonReaderState.CodeWScopeScopeEnd:
return ReadCodeWScope();
default:
throw new JsonReaderException("Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
}
}
catch (EndOfStreamException)
{
return false;
}
}
/// <summary>
/// Changes the <see cref="JsonReader.State"/> to Closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
_reader.Close();
}
private bool ReadCodeWScope()
{
switch (_bsonReaderState)
{
case BsonReaderState.CodeWScopeStart:
SetToken(JsonToken.PropertyName, "$code");
_bsonReaderState = BsonReaderState.CodeWScopeCode;
return true;
case BsonReaderState.CodeWScopeCode:
// total CodeWScope size - not used
ReadInt32();
SetToken(JsonToken.String, ReadLengthString());
_bsonReaderState = BsonReaderState.CodeWScopeScope;
return true;
case BsonReaderState.CodeWScopeScope:
if (CurrentState == State.PostValue)
{
SetToken(JsonToken.PropertyName, "$scope");
return true;
}
else
{
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeScopeObject;
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case BsonReaderState.CodeWScopeScopeObject:
bool result = ReadNormal();
if (result && TokenType == JsonToken.EndObject)
_bsonReaderState = BsonReaderState.CodeWScopeScopeEnd;
return result;
case BsonReaderState.CodeWScopeScopeEnd:
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
private bool ReadReference()
{
switch (CurrentState)
{
case State.ObjectStart:
{
SetToken(JsonToken.PropertyName, "$ref");
_bsonReaderState = BsonReaderState.ReferenceRef;
return true;
}
case State.Property:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.String, ReadLengthString());
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.Bytes, ReadBytes(12));
return true;
}
else
{
throw new JsonReaderException("Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
case State.PostValue:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.PropertyName, "$id");
_bsonReaderState = BsonReaderState.ReferenceId;
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
}
else
{
throw new JsonReaderException("Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
default:
throw new JsonReaderException("Unexpected state when reading BSON reference: " + CurrentState);
}
}
private bool ReadNormal()
{
switch (CurrentState)
{
case State.Start:
{
JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;
SetToken(token);
ContainerContext newContext = new ContainerContext(type);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case State.Complete:
case State.Closed:
return false;
case State.Property:
{
ReadType(_currentElementType);
return true;
}
case State.ObjectStart:
case State.ArrayStart:
case State.PostValue:
ContainerContext context = _currentContext;
if (context == null)
return false;
int lengthMinusEnd = context.Length - 1;
if (context.Position < lengthMinusEnd)
{
if (context.Type == BsonType.Array)
{
ReadElement();
ReadType(_currentElementType);
return true;
}
else
{
SetToken(JsonToken.PropertyName, ReadElement());
return true;
}
}
else if (context.Position == lengthMinusEnd)
{
if (ReadByte() != 0)
throw new JsonReaderException("Unexpected end of object byte value.");
PopContext();
if (_currentContext != null)
MovePosition(context.Length);
JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
SetToken(endToken);
return true;
}
else
{
throw new JsonReaderException("Read past end of current container context.");
}
case State.ConstructorStart:
break;
case State.Constructor:
break;
case State.Error:
break;
case State.Finished:
break;
default:
throw new ArgumentOutOfRangeException();
}
return false;
}
private void PopContext()
{
_stack.RemoveAt(_stack.Count - 1);
if (_stack.Count == 0)
_currentContext = null;
else
_currentContext = _stack[_stack.Count - 1];
}
private void PushContext(ContainerContext newContext)
{
_stack.Add(newContext);
_currentContext = newContext;
}
private byte ReadByte()
{
MovePosition(1);
return _reader.ReadByte();
}
private void ReadType(BsonType type)
{
switch (type)
{
case BsonType.Number:
SetToken(JsonToken.Float, ReadDouble());
break;
case BsonType.String:
case BsonType.Symbol:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.Object:
{
SetToken(JsonToken.StartObject);
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Array:
{
SetToken(JsonToken.StartArray);
ContainerContext newContext = new ContainerContext(BsonType.Array);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Binary:
SetToken(JsonToken.Bytes, ReadBinary());
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
break;
case BsonType.Oid:
byte[] oid = ReadBytes(12);
SetToken(JsonToken.Bytes, oid);
break;
case BsonType.Boolean:
bool b = Convert.ToBoolean(ReadByte());
SetToken(JsonToken.Boolean, b);
break;
case BsonType.Date:
long ticks = ReadInt64();
DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);
DateTime dateTime;
switch (DateTimeKindHandling)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
break;
case BsonType.Null:
SetToken(JsonToken.Null);
break;
case BsonType.Regex:
string expression = ReadString();
string modifiers = ReadString();
string regex = @"/" + expression + @"/" + modifiers;
SetToken(JsonToken.String, regex);
break;
case BsonType.Reference:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.ReferenceStart;
break;
case BsonType.Code:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.CodeWScope:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeStart;
break;
case BsonType.Integer:
SetToken(JsonToken.Integer, (long)ReadInt32());
break;
case BsonType.TimeStamp:
case BsonType.Long:
SetToken(JsonToken.Integer, ReadInt64());
break;
default:
throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type);
}
}
private byte[] ReadBinary()
{
int dataLength = ReadInt32();
BsonBinaryType binaryType = (BsonBinaryType)ReadByte();
#pragma warning disable 612,618
// the old binary type has the data length repeated in the data for some reason
if (binaryType == BsonBinaryType.Data && !_jsonNet35BinaryCompatibility)
{
dataLength = ReadInt32();
}
#pragma warning restore 612,618
return ReadBytes(dataLength);
}
private string ReadString()
{
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = offset;
byte b;
while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0)
{
_byteBuffer[count++] = b;
}
int byteCount = count - offset;
totalBytesRead += byteCount;
if (count < MaxCharBytesSize && builder == null)
{
// pref optimization to avoid reading into a string builder
// if string is smaller than the buffer then return it directly
int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
MovePosition(totalBytesRead + 1);
return new string(_charBuffer, 0, length);
}
else
{
// calculate the index of the end of the last full character in the buffer
int lastFullCharStop = GetLastFullCharStop(count - 1);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
if (builder == null)
builder = new StringBuilder(MaxCharBytesSize * 2);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
// reached end of string
if (count < MaxCharBytesSize)
{
MovePosition(totalBytesRead + 1);
return builder.ToString();
}
offset = 0;
}
}
}
while (true);
}
private string ReadLengthString()
{
int length = ReadInt32();
MovePosition(length);
string s = GetString(length - 1);
_reader.ReadByte();
return s;
}
private string GetString(int length)
{
if (length == 0)
return string.Empty;
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
? MaxCharBytesSize - offset
: length - totalBytesRead;
int byteCount = _reader.BaseStream.Read(_byteBuffer, offset, count);
if (byteCount == 0)
throw new EndOfStreamException("Unable to read beyond the end of the stream.");
totalBytesRead += byteCount;
// Above, byteCount is how many bytes we read this time.
// Below, byteCount is how many bytes are in the _byteBuffer.
byteCount += offset;
if (byteCount == length)
{
// pref optimization to avoid reading into a string builder
// first iteration and all bytes read then return string directly
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
return new string(_charBuffer, 0, charCount);
}
else
{
int lastFullCharStop = GetLastFullCharStop(byteCount - 1);
if (builder == null)
builder = new StringBuilder(length);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
offset = 0;
}
}
}
while (totalBytesRead < length);
return builder.ToString();
}
private int GetLastFullCharStop(int start)
{
int lookbackPos = start;
int bis = 0;
while (lookbackPos >= 0)
{
bis = BytesInSequence(_byteBuffer[lookbackPos]);
if (bis == 0)
{
lookbackPos--;
continue;
}
else if (bis == 1)
{
break;
}
else
{
lookbackPos--;
break;
}
}
if (bis == start - lookbackPos)
{
//Full character.
return start;
}
else
{
return lookbackPos;
}
}
private int BytesInSequence(byte b)
{
if (b <= _seqRange1[1]) return 1;
if (b >= _seqRange2[0] && b <= _seqRange2[1]) return 2;
if (b >= _seqRange3[0] && b <= _seqRange3[1]) return 3;
if (b >= _seqRange4[0] && b <= _seqRange4[1]) return 4;
return 0;
}
private void EnsureBuffers()
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
_charBuffer = new char[charBufferSize];
}
}
private double ReadDouble()
{
MovePosition(8);
return _reader.ReadDouble();
}
private int ReadInt32()
{
MovePosition(4);
return _reader.ReadInt32();
}
private long ReadInt64()
{
MovePosition(8);
return _reader.ReadInt64();
}
private BsonType ReadType()
{
MovePosition(1);
return (BsonType)_reader.ReadSByte();
}
private void MovePosition(int count)
{
_currentContext.Position += count;
}
private byte[] ReadBytes(int count)
{
MovePosition(count);
return _reader.ReadBytes(count);
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.