context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal class AttributeNamedParameterCompletionProvider : CommonCompletionProvider
{
private const string EqualsString = "=";
private const string SpaceEqualsString = " =";
private const string ColonString = ":";
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
var document = context.Document;
var position = context.Position;
var cancellationToken = context.CancellationToken;
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (syntaxTree.IsInNonUserCode(position, cancellationToken))
{
return;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
{
return;
}
var attributeArgumentList = token.Parent as AttributeArgumentListSyntax;
var attributeSyntax = token.Parent.Parent as AttributeSyntax;
if (attributeSyntax == null || attributeArgumentList == null)
{
return;
}
if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token))
{
context.IsExclusive = true;
}
// We actually want to collect two sets of named parameters to present the user. The
// normal named parameters that come from the attribute constructors. These will be
// presented like "foo:". And also the named parameters that come from the writable
// fields/properties in the attribute. These will be presented like "bar =".
var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position);
var workspace = document.Project.Solution.Workspace;
var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false);
var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false);
var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false);
context.AddItems(nameEqualsItems);
// If we're after a name= parameter, then we only want to show name= parameters.
// Otherwise, show name: parameters too.
if (!IsAfterNameEqualsArgument(token))
{
context.AddItems(nameColonItems);
}
}
private bool IsAfterNameColonArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
private bool IsAfterNameEqualsArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameEquals != null)
{
return true;
}
}
}
}
return false;
}
private async Task<IEnumerable<CompletionItem>> GetNameEqualsItemsAsync(CompletionContext context, SemanticModel semanticModel,
SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters)
{
var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, context.Position, attributeSyntax, context.CancellationToken);
var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name));
var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false);
return from p in attributeNamedParameters
where !existingNamedParameters.Contains(p.Name)
select SymbolCompletionItem.Create(
displayText: p.Name.ToIdentifierToken().ToString() + SpaceEqualsString,
insertionText: null,
symbol: p,
contextPosition: token.SpanStart,
sortText: p.Name,
rules: CompletionItemRules.Default);
}
private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync(
CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters)
{
var parameterLists = GetParameterLists(semanticModel, context.Position, attributeSyntax, context.CancellationToken);
parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters));
var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false);
return from pl in parameterLists
from p in pl
where !existingNamedParameters.Contains(p.Name)
select SymbolCompletionItem.Create(
displayText: p.Name.ToIdentifierToken().ToString() + ColonString,
insertionText: null,
symbol: p,
contextPosition: token.SpanStart,
sortText: p.Name,
rules: CompletionItemRules.Default);
}
public override Task<CompletionDescription> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
{
return SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken);
}
private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters)
{
return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty();
}
private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position)
{
var existingArguments1 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameColon != null)
.Select(a => a.NameColon.Name.Identifier.ValueText);
var existingArguments2 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameEquals != null)
.Select(a => a.NameEquals.Name.Identifier.ValueText);
return existingArguments1.Concat(existingArguments2).ToSet();
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (within != null && attributeType != null)
{
return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
}
return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>();
}
private IEnumerable<ISymbol> GetAttributeNamedParameters(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within);
}
protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken)
{
return Task.FromResult(GetTextChange(selectedItem, ch));
}
private TextChange? GetTextChange(CompletionItem selectedItem, char? ch)
{
var displayText = selectedItem.DisplayText;
if (ch != null)
{
// If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The
// typed space character will be passed through to the editor, and they can then type the '='.
if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - SpaceEqualsString.Length));
}
// If the user types '=', do not complete the '=' at the end of the named parameter because the typed '='
// will be passed through to the editor.
if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - EqualsString.Length));
}
// If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':'
// will be passed through to the editor.
if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - ColonString.Length));
}
}
return new TextChange(selectedItem.Span, displayText);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Hashtable = System.Collections.IDictionary;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
using XmlDeserializationEvents = System.Object;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSerializerImplementation
{
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' />
public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' />
public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' />
public virtual IDictionary ReadMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' />
public virtual IDictionary WriteMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' />
public virtual IDictionary TypedSerializers { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' />
public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' />
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSerializer
{
private TempAssembly _tempAssembly;
private bool _typedSerializer;
private Type _primitiveType;
private XmlMapping _mapping;
private XmlDeserializationEvents _events = new XmlDeserializationEvents();
#if NET_NATIVE
private XmlSerializer innerSerializer;
private readonly Type rootType;
#endif
private static TempAssemblyCache s_cache = new TempAssemblyCache();
private static volatile XmlSerializerNamespaces s_defaultNamespaces;
private static XmlSerializerNamespaces DefaultNamespaces
{
get
{
if (s_defaultNamespaces == null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
if (s_defaultNamespaces == null)
{
s_defaultNamespaces = nss;
}
}
return s_defaultNamespaces;
}
}
private static InternalHashtable s_xmlSerializerTable = new InternalHashtable();
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' />
///<internalonly/>
protected XmlSerializer()
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) :
this(type, overrides, extraTypes, root, defaultNamespace, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !NET_NATIVE
public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null, null)
#else
public XmlSerializer(Type type, Type[] extraTypes) : this(type)
#endif // NET_NATIVE
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
{
_tempAssembly = GenerateTempAssembly(xmlTypeMapping);
_mapping = xmlTypeMapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type) : this(type, (string)null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException("type");
#if NET_NATIVE
// The ctor is not supported, but we cannot throw PNSE unconditionally
// because the ctor is used by ctor(Type) which passes in a null defaultNamespace.
if (!string.IsNullOrEmpty(defaultNamespace))
{
throw new PlatformNotSupportedException();
}
rootType = type;
#endif
_mapping = GetKnownMapping(type, defaultNamespace);
if (_mapping != null)
{
_primitiveType = type;
return;
}
#if !NET_NATIVE
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
lock (s_cache)
{
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
{
// need to reflect and generate new serialization assembly
XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
}
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
#else
XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();
if (contract != null)
{
this.innerSerializer = contract.GetSerializer(type);
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
{
#if NET_NATIVE
throw new PlatformNotSupportedException();
#else
if (type == null)
throw new ArgumentNullException("type");
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
if (extraTypes != null)
{
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
}
_mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
{
return GenerateTempAssembly(xmlMapping, null, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
{
if (xmlMapping == null)
throw new ArgumentNullException("xmlMapping");
return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o)
{
Serialize(textWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o)
{
Serialize(stream, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(xmlWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
Serialize(xmlWriter, o, namespaces, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
{
Serialize(xmlWriter, o, namespaces, encodingStyle, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
try
{
if (_primitiveType != null)
{
SerializePrimitive(xmlWriter, o, namespaces);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationWriter writer = CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
try
{
Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else
_tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
try
{
this.innerSerializer.Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
throw new InvalidOperationException(SR.XmlGenError, e);
}
xmlWriter.Flush();
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(Stream stream)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing) 2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(stream, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(TextReader textReader)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing) 2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(textReader, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(XmlReader xmlReader)
{
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle)
{
return Deserialize(xmlReader, encodingStyle, _events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
try
{
if (_primitiveType != null)
{
return DeserializePrimitive(xmlReader, events);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationReader reader = CreateReader();
reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
try
{
return Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else
{
return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
}
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
XmlSerializationReader reader = this.innerSerializer.CreateReader();
reader.Init(xmlReader, encodingStyle);
try
{
return this.innerSerializer.Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
if (xmlReader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
}
else
{
throw new InvalidOperationException(SR.XmlSerializeError, e);
}
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool CanDeserialize(XmlReader xmlReader)
{
if (_primitiveType != null)
{
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType];
return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty);
}
else if (_tempAssembly != null)
{
return _tempAssembly.CanRead(_mapping, xmlReader);
}
else
{
return false;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings)
{
return FromMappings(mappings, (Type)null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0) return new XmlSerializer[0];
XmlSerializerImplementation contract = null;
TempAssembly tempAssembly = null;
{
if (XmlMapping.IsShallow(mappings))
{
return new XmlSerializer[0];
}
else
{
if (type == null)
{
tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null);
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
contract = tempAssembly.Contract;
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
}
return serializers;
}
else
{
// Use XmlSerializer cache when the type is not null.
return GetSerializersFromCache(mappings, type);
}
}
}
}
private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
InternalHashtable typedMappingTable = null;
lock (s_xmlSerializerTable)
{
typedMappingTable = s_xmlSerializerTable[type] as InternalHashtable;
if (typedMappingTable == null)
{
typedMappingTable = new InternalHashtable();
s_xmlSerializerTable[type] = typedMappingTable;
}
}
lock (typedMappingTable)
{
InternalHashtable pendingKeys = new InternalHashtable();
for (int i = 0; i < mappings.Length; i++)
{
XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
serializers[i] = typedMappingTable[mappingKey] as XmlSerializer;
if (serializers[i] == null)
{
pendingKeys.Add(mappingKey, i);
}
}
if (pendingKeys.Count > 0)
{
XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
int index = 0;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
pendingMappings[index++] = mappingKey.Mapping;
}
TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null);
XmlSerializerImplementation contract = tempAssembly.Contract;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
index = (int)pendingKeys[mappingKey];
serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);
typedMappingTable[mappingKey] = serializers[index];
}
}
}
return serializers;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromTypes(Type[] types)
{
if (types == null)
return new XmlSerializer[0];
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length];
for (int i = 0; i < types.Length; i++)
{
mappings[i] = importer.ImportTypeMapping(types[i]);
}
return FromMappings(mappings);
}
#if NET_NATIVE
// this the global XML serializer contract introduced for multi-file
private static XmlSerializerImplementation xmlSerializerContract;
internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly()
{
// hack to pull in SetXmlSerializerContract which is only referenced from the
// code injected by MainMethodInjector transform
// there's probably also a way to do this via [DependencyReductionRoot],
// but I can't get the compiler to find that...
if (xmlSerializerContract == null)
SetXmlSerializerContract(null);
// this method body used to be rewritten by an IL transform
// with the restructuring for multi-file, it has become a regular method
return xmlSerializerContract;
}
public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
{
xmlSerializerContract = xmlSerializerImplementation;
}
#endif
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' />
///<internalonly/>
protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
///<internalonly/>
protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' />
///<internalonly/>
protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' />
///<internalonly/>
protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); }
internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping)
{
_tempAssembly = tempAssembly;
_mapping = mapping;
_typedSerializer = true;
}
private static XmlTypeMapping GetKnownMapping(Type type, string ns)
{
if (ns != null && ns != string.Empty)
return null;
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type];
if (typeDesc == null)
return null;
ElementAccessor element = new ElementAccessor();
element.Name = typeDesc.DataType.Name;
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null));
return mapping;
}
private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();
writer.Init(xmlWriter, namespaces, null, null, null);
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
writer.Write_string(o);
break;
case TypeCode.Int32:
writer.Write_int(o);
break;
case TypeCode.Boolean:
writer.Write_boolean(o);
break;
case TypeCode.Int16:
writer.Write_short(o);
break;
case TypeCode.Int64:
writer.Write_long(o);
break;
case TypeCode.Single:
writer.Write_float(o);
break;
case TypeCode.Double:
writer.Write_double(o);
break;
case TypeCode.Decimal:
writer.Write_decimal(o);
break;
case TypeCode.DateTime:
writer.Write_dateTime(o);
break;
case TypeCode.Char:
writer.Write_char(o);
break;
case TypeCode.Byte:
writer.Write_unsignedByte(o);
break;
case TypeCode.SByte:
writer.Write_byte(o);
break;
case TypeCode.UInt16:
writer.Write_unsignedShort(o);
break;
case TypeCode.UInt32:
writer.Write_unsignedInt(o);
break;
case TypeCode.UInt64:
writer.Write_unsignedLong(o);
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
writer.Write_QName(o);
}
else if (_primitiveType == typeof(byte[]))
{
writer.Write_base64Binary(o);
}
else if (_primitiveType == typeof(Guid))
{
writer.Write_guid(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
}
private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
{
XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader();
reader.Init(xmlReader, events, null, null);
object o;
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
o = reader.Read_string();
break;
case TypeCode.Int32:
o = reader.Read_int();
break;
case TypeCode.Boolean:
o = reader.Read_boolean();
break;
case TypeCode.Int16:
o = reader.Read_short();
break;
case TypeCode.Int64:
o = reader.Read_long();
break;
case TypeCode.Single:
o = reader.Read_float();
break;
case TypeCode.Double:
o = reader.Read_double();
break;
case TypeCode.Decimal:
o = reader.Read_decimal();
break;
case TypeCode.DateTime:
o = reader.Read_dateTime();
break;
case TypeCode.Char:
o = reader.Read_char();
break;
case TypeCode.Byte:
o = reader.Read_unsignedByte();
break;
case TypeCode.SByte:
o = reader.Read_byte();
break;
case TypeCode.UInt16:
o = reader.Read_unsignedShort();
break;
case TypeCode.UInt32:
o = reader.Read_unsignedInt();
break;
case TypeCode.UInt64:
o = reader.Read_unsignedLong();
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
o = reader.Read_QName();
}
else if (_primitiveType == typeof(byte[]))
{
o = reader.Read_base64Binary();
}
else if (_primitiveType == typeof(Guid))
{
o = reader.Read_guid();
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
return o;
}
private class XmlSerializerMappingKey
{
public XmlMapping Mapping;
public XmlSerializerMappingKey(XmlMapping mapping)
{
this.Mapping = mapping;
}
public override bool Equals(object obj)
{
XmlSerializerMappingKey other = obj as XmlSerializerMappingKey;
if (other == null)
return false;
if (this.Mapping.Key != other.Mapping.Key)
return false;
if (this.Mapping.ElementName != other.Mapping.ElementName)
return false;
if (this.Mapping.Namespace != other.Mapping.Namespace)
return false;
if (this.Mapping.IsSoap != other.Mapping.IsSoap)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = this.Mapping.IsSoap ? 0 : 1;
if (this.Mapping.Key != null)
hashCode ^= this.Mapping.Key.GetHashCode();
if (this.Mapping.ElementName != null)
hashCode ^= this.Mapping.ElementName.GetHashCode();
if (this.Mapping.Namespace != null)
hashCode ^= this.Mapping.Namespace.GetHashCode();
return hashCode;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Net;
using System.Reflection;
namespace OpenSim.Server.Handlers.Login
{
public class LLLoginHandlers
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ILoginService m_LocalService;
private bool m_Proxy;
public LLLoginHandlers(ILoginService service, bool hasProxy)
{
m_LocalService = service;
m_Proxy = hasProxy;
}
public XmlRpcResponse HandleXMLRPCLogin(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
if (m_Proxy && request.Params[3] != null)
{
IPEndPoint ep = Util.GetClientIPFromXFF((string)request.Params[3]);
if (ep != null)
// Bang!
remoteClient = ep;
}
if (requestData != null)
{
// Debug code to show exactly what login parameters the viewer is sending us.
// TODO: Extract into a method that can be generally applied if one doesn't already exist.
// foreach (string key in requestData.Keys)
// {
// object value = requestData[key];
// Console.WriteLine("{0}:{1}", key, value);
// if (value is ArrayList)
// {
// ICollection col = value as ICollection;
// foreach (object item in col)
// Console.WriteLine(" {0}", item);
// }
// }
if (requestData.ContainsKey("first") && requestData["first"] != null &&
requestData.ContainsKey("last") && requestData["last"] != null && (
(requestData.ContainsKey("passwd") && requestData["passwd"] != null) ||
(!requestData.ContainsKey("passwd") && requestData.ContainsKey("web_login_key") && requestData["web_login_key"] != null && requestData["web_login_key"].ToString() != UUID.Zero.ToString())
))
{
string first = requestData["first"].ToString();
string last = requestData["last"].ToString();
string passwd = null;
if (requestData.ContainsKey("passwd"))
{
passwd = requestData["passwd"].ToString();
}
else if (requestData.ContainsKey("web_login_key"))
{
passwd = "$1$" + requestData["web_login_key"].ToString();
m_log.InfoFormat("[LOGIN]: XMLRPC Login Req key {0}", passwd);
}
string startLocation = string.Empty;
UUID scopeID = UUID.Zero;
if (requestData["scope_id"] != null)
scopeID = new UUID(requestData["scope_id"].ToString());
if (requestData.ContainsKey("start"))
startLocation = requestData["start"].ToString();
string clientVersion = "Unknown";
if (requestData.Contains("version") && requestData["version"] != null)
clientVersion = requestData["version"].ToString();
// We should do something interesting with the client version...
string channel = "Unknown";
if (requestData.Contains("channel") && requestData["channel"] != null)
channel = requestData["channel"].ToString();
string mac = "Unknown";
if (requestData.Contains("mac") && requestData["mac"] != null)
mac = requestData["mac"].ToString();
string id0 = "Unknown";
if (requestData.Contains("id0") && requestData["id0"] != null)
id0 = requestData["id0"].ToString();
//m_log.InfoFormat("[LOGIN]: XMLRPC Login Requested for {0} {1}, starting in {2}, using {3}", first, last, startLocation, clientVersion);
LoginResponse reply = null;
reply = m_LocalService.Login(first, last, passwd, startLocation, scopeID, clientVersion, channel, mac, id0, remoteClient);
XmlRpcResponse response = new XmlRpcResponse();
response.Value = reply.ToHashtable();
return response;
}
}
return FailedXMLRPCResponse();
}
public XmlRpcResponse HandleXMLRPCLoginBlocked(XmlRpcRequest request, IPEndPoint client)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable resp = new Hashtable();
resp["reason"] = "presence";
resp["message"] = "Logins are currently restricted. Please try again later.";
resp["login"] = "false";
response.Value = resp;
return response;
}
public XmlRpcResponse HandleXMLRPCSetLoginLevel(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
if (requestData != null)
{
if (requestData.ContainsKey("first") && requestData["first"] != null &&
requestData.ContainsKey("last") && requestData["last"] != null &&
requestData.ContainsKey("level") && requestData["level"] != null &&
requestData.ContainsKey("passwd") && requestData["passwd"] != null)
{
string first = requestData["first"].ToString();
string last = requestData["last"].ToString();
string passwd = requestData["passwd"].ToString();
int level = Int32.Parse(requestData["level"].ToString());
m_log.InfoFormat("[LOGIN]: XMLRPC Set Level to {2} Requested by {0} {1}", first, last, level);
Hashtable reply = m_LocalService.SetLevel(first, last, passwd, level, remoteClient);
XmlRpcResponse response = new XmlRpcResponse();
response.Value = reply;
return response;
}
}
XmlRpcResponse failResponse = new XmlRpcResponse();
Hashtable failHash = new Hashtable();
failHash["success"] = "false";
failResponse.Value = failHash;
return failResponse;
}
public OSD HandleLLSDLogin(OSD request, IPEndPoint remoteClient)
{
if (request.Type == OSDType.Map)
{
OSDMap map = (OSDMap)request;
if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
{
string startLocation = string.Empty;
if (map.ContainsKey("start"))
startLocation = map["start"].AsString();
UUID scopeID = UUID.Zero;
if (map.ContainsKey("scope_id"))
scopeID = new UUID(map["scope_id"].AsString());
m_log.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" + map["last"].AsString() + "' / " + startLocation);
LoginResponse reply = null;
reply = m_LocalService.Login(map["first"].AsString(), map["last"].AsString(), map["passwd"].AsString(), startLocation, scopeID,
map["version"].AsString(), map["channel"].AsString(), map["mac"].AsString(), map["id0"].AsString(), remoteClient);
return reply.ToOSDMap();
}
}
return FailedOSDResponse();
}
public void HandleWebSocketLoginEvents(string path, WebSocketHttpServerHandler sock)
{
sock.MaxPayloadSize = 16384; //16 kb payload
sock.InitialMsgTimeout = 5000; //5 second first message to trigger at least one of these events
sock.NoDelay_TCP_Nagle = true;
sock.OnData += delegate(object sender, WebsocketDataEventArgs data) { sock.Close("fail"); };
sock.OnPing += delegate(object sender, PingEventArgs pingdata) { sock.Close("fail"); };
sock.OnPong += delegate(object sender, PongEventArgs pongdata) { sock.Close("fail"); };
sock.OnText += delegate(object sender, WebsocketTextEventArgs text)
{
OSD request = null;
try
{
request = OSDParser.DeserializeJson(text.Data);
if (!(request is OSDMap))
{
sock.SendMessage(OSDParser.SerializeJsonString(FailedOSDResponse()));
}
else
{
OSDMap req = request as OSDMap;
string first = req["firstname"].AsString();
string last = req["lastname"].AsString();
string passwd = req["passwd"].AsString();
string start = req["startlocation"].AsString();
string version = req["version"].AsString();
string channel = req["channel"].AsString();
string mac = req["mac"].AsString();
string id0 = req["id0"].AsString();
UUID scope = UUID.Zero;
IPEndPoint endPoint =
(sender as WebSocketHttpServerHandler).GetRemoteIPEndpoint();
LoginResponse reply = null;
reply = m_LocalService.Login(first, last, passwd, start, scope, version,
channel, mac, id0, endPoint);
sock.SendMessage(OSDParser.SerializeJsonString(reply.ToOSDMap()));
}
}
catch (Exception)
{
sock.SendMessage(OSDParser.SerializeJsonString(FailedOSDResponse()));
}
finally
{
sock.Close("success");
}
};
sock.HandshakeAndUpgrade();
}
private XmlRpcResponse FailedXMLRPCResponse()
{
Hashtable hash = new Hashtable();
hash["reason"] = "key";
hash["message"] = "Incomplete login credentials. Check your username and password.";
hash["login"] = "false";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
private OSD FailedOSDResponse()
{
OSDMap map = new OSDMap();
map["reason"] = OSD.FromString("key");
map["message"] = OSD.FromString("Invalid login credentials. Check your username and passwd.");
map["login"] = OSD.FromString("false");
return map;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Modeling;
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Adapter.Oplock;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Xrt.Runtime;
[assembly: NativeType("System.Diagnostics.Tracing.*")]
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Model.Oplock
{
public static class OplockModel
{
#region State
public static ModelState State = ModelState.Uninitialized;
public static OplockConfig Config;
public static ModelOplockOpen Open;
public static bool Share_ForceLevel2Oplock;
public static bool Share_Type_Include_STYPE_CLUSTER_SOFS;
public static DialectRevision Connection_Dialect;
public static ModelSMB2Request Request;
#endregion
#region Rules
/// <summary>
/// Call for loading server configuration
/// </summary>
[Rule(Action = "call ReadConfig(out _)")]
public static void ReadConfigCall()
{
Condition.IsTrue(State == ModelState.Uninitialized);
}
/// <summary>
/// Return for loading server configuration
/// </summary>
/// <param name="c">Server configuration related to model</param>
[Rule(Action = "return ReadConfig(out c)")]
public static void ReadConfigReturn(OplockConfig c)
{
Condition.IsTrue(State == ModelState.Uninitialized);
Condition.IsNotNull(c);
Condition.IsTrue(c.MaxSmbVersionSupported == ModelDialectRevision.Smb2002
|| c.MaxSmbVersionSupported == ModelDialectRevision.Smb21
|| c.MaxSmbVersionSupported == ModelDialectRevision.Smb30
|| c.MaxSmbVersionSupported == ModelDialectRevision.Smb302);
Config = c;
State = ModelState.Initialized;
}
/// <summary>
/// Setup connection by perform following
/// 1. Negotiate
/// 2. SessionSetup
/// 3. TreeConnect
/// </summary>
/// <param name="maxSmbVersionClientSupported">Max SMB2 dialect that client supports</param>
/// <param name="shareFlag">Indicate if the share force level 2 oplock</param>
/// <param name="shareType">Indicate if the share type includes STYPE_CLUSTER_SOFS</param>
[Rule]
public static void SetupConnection(ModelDialectRevision maxSmbVersionClientSupported, ModelShareFlag shareFlag, ModelShareType shareType)
{
Condition.IsTrue(State == ModelState.Initialized);
Open = null;
Request = null;
Connection_Dialect = DialectRevision.Smb2Unknown;
Connection_Dialect = ModelHelper.DetermineNegotiateDialect(maxSmbVersionClientSupported, Config.MaxSmbVersionSupported);
Share_ForceLevel2Oplock = shareFlag == ModelShareFlag.SMB2_SHAREFLAG_FORCE_LEVELII_OPLOCK;
Share_Type_Include_STYPE_CLUSTER_SOFS = shareType == ModelShareType.STYPE_CLUSTER_SOFS;
State = ModelState.Connected;
}
/// <summary>
/// Call to request Oplock in 1st open and operate the same file from another open
/// </summary>
/// <param name="requestedOplockLevel">Oplock level that requested in 1st open</param>
/// <param name="fileOperation">File operation from another open on the same file</param>
[Rule(Action = "call RequestOplockAndOperateFileRequest(requestedOplockLevel, fileOperation,out _, out _)")]
public static void RequestOplockAndOperateFileCall(RequestedOplockLevel_Values requestedOplockLevel, OplockFileOperation fileOperation)
{
Condition.IsTrue(State == ModelState.Connected);
Condition.IsNull(Request);
// <46> Section 2.2.14: Windows-based clients never use exclusive oplocks. Because there are no situations where it would
// require an exclusive oplock where it would not also require an SMB2_OPLOCK_LEVEL_BATCH, it always requests an SMB2_OPLOCK_LEVEL_BATCH.
Condition.IsTrue(requestedOplockLevel != RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE
&& requestedOplockLevel != RequestedOplockLevel_Values.OPLOCK_LEVEL_LEASE
&& requestedOplockLevel != RequestedOplockLevel_Values.OPLOCK_LEVEL_EXCLUSIVE);
Request = new ModelRequestOplockAndTriggerBreakRequest(requestedOplockLevel);
}
/// <summary>
/// Return to request Oplock in 1st open and operate the same file from another open
/// </summary>
/// <param name="grantedOplockLevel">Oplock level that granted in 1st open</param>
/// <param name="c">Server configure</param>
[Rule(Action = "return RequestOplockAndOperateFileRequest(_, _, out grantedOplockLevel, out c)")]
public static void RequestOplockAndOperateFileReturn(OplockLevel_Values grantedOplockLevel, OplockConfig c)
{
Condition.IsTrue(State == ModelState.Connected);
Condition.IsNotNull(Request);
ModelRequestOplockAndTriggerBreakRequest requestOplockAndTriggerBreakRequest = ModelHelper.RetrieveOutstandingRequest<ModelRequestOplockAndTriggerBreakRequest>(ref Request);
Condition.IsTrue(Config.Platform == c.Platform);
if (Share_ForceLevel2Oplock
&& (requestOplockAndTriggerBreakRequest.RequestedOplockLevel == RequestedOplockLevel_Values.OPLOCK_LEVEL_BATCH
|| requestOplockAndTriggerBreakRequest.RequestedOplockLevel == RequestedOplockLevel_Values.OPLOCK_LEVEL_EXCLUSIVE))
{
ModelHelper.Log(LogType.Requirement,
"3.3.5.9: If TreeConnect.Share.ForceLevel2Oplock is TRUE, " +
"and RequestedOplockLevel is SMB2_OPLOCK_LEVEL_BATCH or SMB2_OPLOCK_LEVEL_EXCLUSIVE, " +
"the server SHOULD<245> set RequestedOplockLevel to SMB2_OPLOCK_LEVEL_II.");
if (Config.Platform != Platform.NonWindows)
{
ModelHelper.Log(LogType.TestInfo, "The SUT platform is Windows.");
Condition.IsTrue(grantedOplockLevel == OplockLevel_Values.OPLOCK_LEVEL_II);
// Skip following WBN which is for pre-Win8
// <226> Section 3.3.5.9: Windows Vista and Windows Server 2008 do not support the SMB2_SHAREFLAG_FORCE_LEVELII_OPLOCK flag
// and ignore the TreeConnect.Share.ForceLevel2Oplock value.
}
}
if (ModelUtility.IsSmb3xFamily(Connection_Dialect)
&& Share_Type_Include_STYPE_CLUSTER_SOFS
&& requestOplockAndTriggerBreakRequest.RequestedOplockLevel == RequestedOplockLevel_Values.OPLOCK_LEVEL_BATCH)
{
ModelHelper.Log(LogType.Requirement,
"3.3.5.9: If Connection.Dialect belongs to the SMB 3.x dialect family TreeConnect.Share.Type includes STYPE_CLUSTER_SOFS " +
"and the RequestedOplockLevel is SMB2_OPLOCK_LEVEL_BATCH, the server MUST set RequestedOplockLevel to SMB2_OPLOCK_LEVEL_II.");
// The Oplock acquisition depends on underlying object store implemention specific
// we may not garantee level2 would be always granted
// Only assert it's not batch
ModelHelper.Log(LogType.TestInfo, "All the above conditions are met.");
Condition.IsTrue(grantedOplockLevel != OplockLevel_Values.OPLOCK_LEVEL_BATCH);
}
Open = new ModelOplockOpen();
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to SMB2_OPLOCK_LEVEL_NONE.");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_NONE;
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is set to None.");
Open.OplockState = OplockState.None;
// Acquire Oplock from underlying object
// If the underlying object store grants the oplock,
// then Open.OplockState is set to Held and Open.OplockLevel is set to the level of the oplock acquired.
if (grantedOplockLevel != OplockLevel_Values.OPLOCK_LEVEL_NONE)
{
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is set to Held.");
Open.OplockState = OplockState.Held;
Open.OplockLevel = grantedOplockLevel;
}
}
/// <summary>
/// Indicate oplock break
/// </summary>
/// <param name="acceptableAckOplockLevel">New oplock break in the notification</param>
[Rule]
public static void OplockBreakNotification(OPLOCK_BREAK_Notification_Packet_OplockLevel_Values acceptableAckOplockLevel)
{
Condition.IsTrue(State == ModelState.Connected);
ModelHelper.Log(LogType.Requirement, "3.3.4.6: The new oplock level MUST be either SMB2_OPLOCK_LEVEL_NONE or SMB2_OPLOCK_LEVEL_II.");
Condition.IsTrue(acceptableAckOplockLevel == OPLOCK_BREAK_Notification_Packet_OplockLevel_Values.OPLOCK_LEVEL_II
|| acceptableAckOplockLevel == OPLOCK_BREAK_Notification_Packet_OplockLevel_Values.OPLOCK_LEVEL_NONE);
ModelHelper.Log(LogType.Requirement,
"The server MUST locate the open by walking the GlobalOpenTable to find an entry whose Open.LocalOpen matches the one provided in the oplock break. ");
ModelHelper.Log(LogType.Requirement,
"If no entry is found, the break indication MUST be ignored and the server MUST complete the oplock break call with SMB2_OPLOCK_LEVEL_NONE as the new oplock level.");
ModelHelper.Log(LogType.TestInfo, "Open should not be NULL.");
Condition.IsNotNull(Open);
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is set to Breaking.");
Open.OplockState = OplockState.Breaking;
}
/// <summary>
/// Request of oplock break acknowledgement
/// </summary>
/// <param name="volatilePortion">Indicate if the open could be found by volatile portion</param>
/// <param name="persistentPortion">Indicate if the persistent portion matches durable fileId</param>
/// <param name="oplockLevel">Oplock level in oplock break acknowledgement request</param>
[Rule]
public static void OplockBreakAcknowledgementRequest(OplockVolatilePortion volatilePortion, OplockPersistentPortion persistentPortion, OplockLevel_Values oplockLevel)
{
Combination.Isolated(volatilePortion == OplockVolatilePortion.VolatilePortionNotFound);
Combination.Isolated(persistentPortion == OplockPersistentPortion.PersistentNotMatchesDurableFileId);
// Isolate the values that are not allowed
Combination.Isolated(oplockLevel == OplockLevel_Values.OPLOCK_LEVEL_BATCH);
Combination.Isolated(oplockLevel == OplockLevel_Values.OPLOCK_LEVEL_EXCLUSIVE);
Combination.Isolated(oplockLevel == OplockLevel_Values.OPLOCK_LEVEL_LEASE);
Condition.IsTrue(State == ModelState.Connected);
Condition.IsNull(Request);
bool volatilePortionFound = volatilePortion == OplockVolatilePortion.VolatilePortionFound;
bool persistentMatchesDurableFileId = persistentPortion == OplockPersistentPortion.PersistentMatchesDurableFileId;
Request = new ModelOplockBreakAcknowledgementRequest(volatilePortionFound, persistentMatchesDurableFileId, oplockLevel);
}
/// <summary>
/// Response of oplock break acknowledgement
/// </summary>
/// <param name="status">Status of the response</param>
/// <param name="oplockLevel">Oplock level in oplock break acknowledgement response</param>
/// <param name="oplockLevelOnOpen">Current oplock level on the open</param>
[Rule]
public static void OplockBreakResponse(ModelSmb2Status status, OPLOCK_BREAK_Response_OplockLevel_Values oplockLevel, OplockLevel_Values oplockLevelOnOpen)
{
Condition.IsTrue(State == ModelState.Connected);
Condition.IsNotNull(Request);
ModelOplockBreakAcknowledgementRequest oplockBreakAckRequest = ModelHelper.RetrieveOutstandingRequest<ModelOplockBreakAcknowledgementRequest>(ref Request);
ModelHelper.Log(LogType.Requirement,
"3.3.5.22.1 Processing an Oplock Acknowledgment");
if (!oplockBreakAckRequest.VolatilePortionFound
|| !oplockBreakAckRequest.PersistentMatchesDurableFileId)
{
ModelHelper.Log(LogType.Requirement,
"Next, the server MUST locate the open on which the client is acknowledging an oplock break by performing a lookup in Session.OpenTable " +
"using FileId.Volatile of the request as the lookup key. If no open is found, or if Open.DurableFileId is not equal to FileId.Persistent, " +
"the server MUST fail the request with STATUS_FILE_CLOSED. ");
ModelHelper.Log(LogType.TestTag, TestTag.InvalidIdentifier);
if (!oplockBreakAckRequest.VolatilePortionFound)
{
ModelHelper.Log(LogType.TestInfo, "Open is not found.");
}
if (!oplockBreakAckRequest.PersistentMatchesDurableFileId)
{
ModelHelper.Log(LogType.TestInfo, "Open.DurableFileId is not equal to FileId.Persistent.");
}
Condition.IsTrue(status == ModelSmb2Status.STATUS_FILE_CLOSED);
return;
}
// We need this to avoid Open.OplockLevel being symbolic which will result case exploration failure
Condition.IsTrue(Open.OplockLevel == oplockLevelOnOpen);
Condition.IsTrue(oplockLevelOnOpen == OplockLevel_Values.OPLOCK_LEVEL_NONE
|| oplockLevelOnOpen == OplockLevel_Values.OPLOCK_LEVEL_II
|| oplockLevelOnOpen == OplockLevel_Values.OPLOCK_LEVEL_BATCH);
if (oplockBreakAckRequest.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_LEASE)
{
ModelHelper.Log(LogType.Requirement,
"If the OplockLevel in the acknowledgment is SMB2_OPLOCK_LEVEL_LEASE, the server MUST do the following:");
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is {0}.", Open.OplockState);
if (Open.OplockState != OplockState.Breaking)
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is not Breaking, stop processing the acknowledgment, " +
"and send an error response with STATUS_INVALID_PARAMETER.");
ModelHelper.Log(LogType.TestTag, TestTag.Compatibility);
Condition.IsTrue(status == ModelSmb2Status.STATUS_INVALID_PARAMETER);
return;
}
else
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is Breaking, complete the oplock break request received from the object store as described in section 3.3.4.6, " +
"with a new level SMB2_OPLOCK_LEVEL_NONE in an implementation-specific manner,<350> and set Open.OplockLevel to SMB2_OPLOCK_LEVEL_NONE, " +
"and Open.OplockState to None.");
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to SMB2_OPLOCK_LEVEL_NONE, and Open.OplockState is set to None");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_NONE;
Open.OplockState = OplockState.None;
// Do not assert implementation-specific manner
return;
}
}
if ((Open.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_EXCLUSIVE
|| Open.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_BATCH)
&& (oplockBreakAckRequest.OplockLevel != OplockLevel_Values.OPLOCK_LEVEL_II && oplockBreakAckRequest.OplockLevel != OplockLevel_Values.OPLOCK_LEVEL_NONE))
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockLevel is SMB2_OPLOCK_LEVEL_EXCLUSIVE or SMB2_OPLOCK_LEVEL_BATCH, " +
"and if OplockLevel is not SMB2_OPLOCK_LEVEL_II or SMB2_OPLOCK_LEVEL_NONE, the server MUST do the following:");
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is {0}.", Open.OplockState);
if (Open.OplockState != OplockState.Breaking)
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is not Breaking, stop processing the acknowledgment, " +
"and send an error response with STATUS_INVALID_OPLOCK_PROTOCOL.");
ModelHelper.Log(LogType.TestTag, TestTag.Compatibility);
Condition.IsTrue(status == ModelSmb2Status.STATUS_INVALID_OPLOCK_PROTOCOL);
return;
}
else
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is Breaking, complete the oplock break request received from the object store, " +
"as described in section 3.3.4.6, with a new level SMB2_OPLOCK_LEVEL_NONE in an implementation-specific manner," +
"<351> and set Open.OplockLevel to SMB2_OPLOCK_LEVEL_NONE and Open.OplockState to None.");
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to SMB2_OPLOCK_LEVEL_NONE, and Open.OplockState is set to None");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_NONE;
Open.OplockState = OplockState.None;
// Do not assert implementation-specific manner
return;
}
}
if (Open.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_II
&& oplockBreakAckRequest.OplockLevel != OplockLevel_Values.OPLOCK_LEVEL_NONE)
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockLevel is SMB2_OPLOCK_LEVEL_II, and if OplockLevel is not SMB2_OPLOCK_LEVEL_NONE, " +
"the server MUST do the following:");
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is {0}.", Open.OplockState);
if (Open.OplockState != OplockState.Breaking)
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is not Breaking, stop processing the acknowledgment, and send an error response with STATUS_INVALID_OPLOCK_PROTOCOL.");
ModelHelper.Log(LogType.TestTag, TestTag.Compatibility);
Condition.IsTrue(status == ModelSmb2Status.STATUS_INVALID_OPLOCK_PROTOCOL);
return;
}
else
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is Breaking, complete the oplock break request received from the object store, " +
"as described in section 3.3.4.6, with a new level SMB2_OPLOCK_LEVEL_NONE in an implementation-specific manner," +
"<352> and set Open.OplockLevel to SMB2_OPLOCK_LEVEL_NONE and Open.OplockState to None.");
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to SMB2_OPLOCK_LEVEL_NONE, and Open.OplockState is set to None");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_NONE;
Open.OplockState = OplockState.None;
// Do not assert implementation-specific manner
return;
}
}
if (oplockBreakAckRequest.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_II
|| oplockBreakAckRequest.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_NONE)
{
ModelHelper.Log(LogType.Requirement,
"If OplockLevel is SMB2_OPLOCK_LEVEL_II or SMB2_OPLOCK_LEVEL_NONE, the server MUST do the following:");
ModelHelper.Log(LogType.TestInfo, "Open.OplockState is {0}.", Open.OplockState);
if (Open.OplockState != OplockState.Breaking)
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is not Breaking, stop processing the acknowledgment, " +
"and send an error response with STATUS_INVALID_DEVICE_STATE.");
ModelHelper.Log(LogType.TestTag, TestTag.Compatibility);
Condition.IsTrue(status == ModelSmb2Status.STATUS_INVALID_DEVICE_STATE);
return;
}
else
{
ModelHelper.Log(LogType.Requirement,
"If Open.OplockState is Breaking, " +
"complete the oplock break request received from the object store as described in section 3.3.4.6, " +
"with a new level received in OplockLevel in an implementation-specific manner.<353>");
if (status != ModelSmb2Status.STATUS_SUCCESS)
{
ModelHelper.Log(LogType.Requirement,
"If the object store indicates an error, set the Open.OplockLevel to SMB2_OPLOCK_LEVEL_NONE, " +
"the Open.OplockState to None, and send the error response with the error code received.");
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to SMB2_OPLOCK_LEVEL_NONE, and Open.OplockState is set to None");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_NONE;
Open.OplockState = OplockState.None;
return;
}
else
{
ModelHelper.Log(LogType.Requirement,
"If the object store indicates success, update Open.OplockLevel and Open.OplockState as follows:");
if (oplockBreakAckRequest.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_II)
{
ModelHelper.Log(LogType.Requirement,
"If OplockLevel is SMB2_OPLOCK_LEVEL_II, " +
"set Open.OplockLevel to SMB2_OPLOCK_LEVEL_II and Open.OplockState to Held.");
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to OPLOCK_LEVEL_II, and Open.OplockState is set to None");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_II;
Open.OplockState = OplockState.Held;
}
if (oplockBreakAckRequest.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_NONE)
{
ModelHelper.Log(LogType.Requirement,
"If OplockLevel is SMB2_OPLOCK_LEVEL_NONE, " +
"set Open.OplockLevel to SMB2_OPLOCK_LEVEL_NONE and the Open.OplockState to None.");
ModelHelper.Log(LogType.TestInfo, "Open.OplockLevel is set to SMB2_OPLOCK_LEVEL_NONE, and Open.OplockState is set to None");
Open.OplockLevel = OplockLevel_Values.OPLOCK_LEVEL_NONE;
Open.OplockState = OplockState.None;
}
}
}
}
ModelHelper.Log(LogType.Requirement,
"The server then MUST construct an oplock break response using the syntax specified in section 2.2.25 with the following value:");
ModelHelper.Log(LogType.Requirement,
"OplockLevel MUST be set to Open.OplockLevel.");
ModelHelper.Log(LogType.TestInfo,
"Open.OplockLevel is {0}.", Open.OplockLevel);
Condition.IsTrue(Open.OplockLevel == (OplockLevel_Values)oplockLevel);
Condition.IsTrue(status == ModelSmb2Status.STATUS_SUCCESS);
}
#endregion
}
}
| |
/*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using BrockAllen.MembershipReboot;
using IdentityServer3.Core;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Services.Default;
namespace FulcrumSeed.WebApi.App_Packages.IdentityServer3.MembershipReboot
{
public class MembershipRebootUserService<TAccount> : UserServiceBase
where TAccount : UserAccount
{
public string DisplayNameClaimType { get; set; }
protected readonly UserAccountService<TAccount> userAccountService;
public MembershipRebootUserService(UserAccountService<TAccount> userAccountService)
{
if (userAccountService == null) throw new ArgumentNullException("userAccountService");
this.userAccountService = userAccountService;
}
public override Task GetProfileDataAsync(ProfileDataRequestContext ctx)
{
var subject = ctx.Subject;
var requestedClaimTypes = ctx.RequestedClaimTypes;
var acct = userAccountService.GetByID(subject.GetSubjectId().ToGuid());
if (acct == null)
{
throw new ArgumentException("Invalid subject identifier");
}
var claims = GetClaimsFromAccount(acct);
if (requestedClaimTypes != null && requestedClaimTypes.Any())
{
claims = claims.Where(x => requestedClaimTypes.Contains(x.Type));
}
ctx.IssuedClaims = claims;
return Task.FromResult(0);
}
protected virtual IEnumerable<Claim> GetClaimsFromAccount(TAccount account)
{
var claims = new List<Claim>{
new Claim(Constants.ClaimTypes.Subject, GetSubjectForAccount(account)),
new Claim(Constants.ClaimTypes.UpdatedAt, IdentityModel.EpochTimeExtensions.ToEpochTime(account.LastUpdated).ToString(), ClaimValueTypes.Integer),
new Claim("tenant", account.Tenant),
new Claim(Constants.ClaimTypes.PreferredUserName, account.Username),
};
if (!String.IsNullOrWhiteSpace(account.Email))
{
claims.Add(new Claim(Constants.ClaimTypes.Email, account.Email));
claims.Add(new Claim(Constants.ClaimTypes.EmailVerified, account.IsAccountVerified ? "true" : "false"));
}
if (!String.IsNullOrWhiteSpace(account.MobilePhoneNumber))
{
claims.Add(new Claim(Constants.ClaimTypes.PhoneNumber, account.MobilePhoneNumber));
claims.Add(new Claim(Constants.ClaimTypes.PhoneNumberVerified, !String.IsNullOrWhiteSpace(account.MobilePhoneNumber) ? "true" : "false"));
}
claims.AddRange(account.Claims.Select(x => new Claim(x.Type, x.Value)));
claims.AddRange(userAccountService.MapClaims(account));
return claims;
}
protected virtual string GetSubjectForAccount(TAccount account)
{
return account.ID.ToString("D");
}
protected virtual string GetDisplayNameForAccount(Guid accountID)
{
var acct = userAccountService.GetByID(accountID);
var claims = GetClaimsFromAccount(acct);
string name = null;
if (DisplayNameClaimType != null)
{
name = acct.Claims.Where(x => x.Type == DisplayNameClaimType).Select(x => x.Value).FirstOrDefault();
}
return name
?? acct.Claims.Where(x => x.Type == Constants.ClaimTypes.Name).Select(x => x.Value).FirstOrDefault()
?? acct.Claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault()
?? acct.Username;
}
protected virtual Task<IEnumerable<Claim>> GetClaimsForAuthenticateResultAsync(TAccount account)
{
return Task.FromResult((IEnumerable<Claim>)null);
}
public override async Task AuthenticateLocalAsync(LocalAuthenticationContext ctx)
{
var username = ctx.UserName;
var password = ctx.Password;
var message = ctx.SignInMessage;
AuthenticateResult result = null;
try
{
TAccount account;
if (ValidateLocalCredentials(username, password, message, out account))
{
result = await PostAuthenticateLocalAsync(account, message);
if (result == null)
{
var subject = GetSubjectForAccount(account);
var name = GetDisplayNameForAccount(account.ID);
var claims = await GetClaimsForAuthenticateResultAsync(account);
result = new AuthenticateResult(subject, name, claims);
}
}
else
{
if (account != null)
{
if (!account.IsLoginAllowed)
{
result = new AuthenticateResult("Account is not allowed to login");
}
else if (account.IsAccountClosed)
{
result = new AuthenticateResult("Account is closed");
}
}
}
}
catch(ValidationException ex)
{
result = new AuthenticateResult(ex.Message);
}
ctx.AuthenticateResult = result;
}
protected virtual Task<AuthenticateResult> PostAuthenticateLocalAsync(TAccount account, SignInMessage message)
{
return Task.FromResult<AuthenticateResult>(null);
}
protected virtual bool ValidateLocalCredentials(string username, string password, SignInMessage message, out TAccount account)
{
var tenant = String.IsNullOrWhiteSpace(message.Tenant) ? userAccountService.Configuration.DefaultTenant : message.Tenant;
return userAccountService.Authenticate(tenant, username, password, out account);
}
public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
{
var externalUser = ctx.ExternalIdentity;
var message = ctx.SignInMessage;
if (externalUser == null)
{
throw new ArgumentNullException("externalUser");
}
try
{
var tenant = String.IsNullOrWhiteSpace(message.Tenant) ? userAccountService.Configuration.DefaultTenant : message.Tenant;
var acct = this.userAccountService.GetByLinkedAccount(tenant, externalUser.Provider, externalUser.ProviderId);
if (acct == null)
{
ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(tenant, externalUser.Provider, externalUser.ProviderId, externalUser.Claims);
}
else
{
ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(acct.ID, externalUser.Provider, externalUser.ProviderId, externalUser.Claims);
}
}
catch (ValidationException ex)
{
ctx.AuthenticateResult = new AuthenticateResult(ex.Message);
}
}
protected virtual async Task<AuthenticateResult> ProcessNewExternalAccountAsync(string tenant, string provider, string providerId, IEnumerable<Claim> claims)
{
var user = await TryGetExistingUserFromExternalProviderClaimsAsync(provider, claims);
if (user == null)
{
user = await InstantiateNewAccountFromExternalProviderAsync(provider, providerId, claims);
var email = claims.GetValue(Constants.ClaimTypes.Email);
user = userAccountService.CreateAccount(
tenant,
Guid.NewGuid().ToString("N"),
null, email,
null, null,
user);
}
userAccountService.AddOrUpdateLinkedAccount(user, provider, providerId);
var result = await AccountCreatedFromExternalProviderAsync(user.ID, provider, providerId, claims);
if (result != null) return result;
return await SignInFromExternalProviderAsync(user.ID, provider);
}
protected virtual Task<TAccount> TryGetExistingUserFromExternalProviderClaimsAsync(string provider, IEnumerable<Claim> claims)
{
return Task.FromResult<TAccount>(null);
}
protected virtual Task<TAccount> InstantiateNewAccountFromExternalProviderAsync(string provider, string providerId, IEnumerable<Claim> claims)
{
// we'll let the default creation happen, but can override to initialize properties if needed
return Task.FromResult<TAccount>(null);
}
protected virtual async Task<AuthenticateResult> AccountCreatedFromExternalProviderAsync(Guid accountID, string provider, string providerId, IEnumerable<Claim> claims)
{
SetAccountEmail(accountID, ref claims);
SetAccountPhone(accountID, ref claims);
return await UpdateAccountFromExternalClaimsAsync(accountID, provider, providerId, claims);
}
protected virtual async Task<AuthenticateResult> SignInFromExternalProviderAsync(Guid accountID, string provider)
{
var account = userAccountService.GetByID(accountID);
var claims = await GetClaimsForAuthenticateResultAsync(account);
return new AuthenticateResult(
subject: accountID.ToString("D"),
name: GetDisplayNameForAccount(accountID),
claims:claims,
identityProvider: provider,
authenticationMethod: Constants.AuthenticationMethods.External);
}
protected virtual Task<AuthenticateResult> UpdateAccountFromExternalClaimsAsync(Guid accountID, string provider, string providerId, IEnumerable<Claim> claims)
{
userAccountService.AddClaims(accountID, new UserClaimCollection(claims));
return Task.FromResult<AuthenticateResult>(null);
}
protected virtual async Task<AuthenticateResult> ProcessExistingExternalAccountAsync(Guid accountID, string provider, string providerId, IEnumerable<Claim> claims)
{
return await SignInFromExternalProviderAsync(accountID, provider);
}
protected virtual void SetAccountEmail(Guid accountID, ref IEnumerable<Claim> claims)
{
var email = claims.GetValue(Constants.ClaimTypes.Email);
if (email != null)
{
var acct = userAccountService.GetByID(accountID);
if (acct.Email == null)
{
try
{
var email_verified = claims.GetValue(Constants.ClaimTypes.EmailVerified);
if (email_verified != null && email_verified == "true")
{
userAccountService.SetConfirmedEmail(acct.ID, email);
}
else
{
userAccountService.ChangeEmailRequest(acct.ID, email);
}
var emailClaims = new string[] { Constants.ClaimTypes.Email, Constants.ClaimTypes.EmailVerified };
claims = claims.Where(x => !emailClaims.Contains(x.Type));
}
catch (ValidationException)
{
// presumably the email is already associated with another account
// so eat the validation exception and let the claim pass thru
}
}
}
}
protected virtual void SetAccountPhone(Guid accountID, ref IEnumerable<Claim> claims)
{
var phone = claims.GetValue(Constants.ClaimTypes.PhoneNumber);
if (phone != null)
{
var acct = userAccountService.GetByID(accountID);
if (acct.MobilePhoneNumber == null)
{
try
{
var phone_verified = claims.GetValue(Constants.ClaimTypes.PhoneNumberVerified);
if (phone_verified != null && phone_verified == "true")
{
userAccountService.SetConfirmedMobilePhone(acct.ID, phone);
}
else
{
userAccountService.ChangeMobilePhoneRequest(acct.ID, phone);
}
var phoneClaims = new string[] { Constants.ClaimTypes.PhoneNumber, Constants.ClaimTypes.PhoneNumberVerified };
claims = claims.Where(x => !phoneClaims.Contains(x.Type));
}
catch (ValidationException)
{
// presumably the phone is already associated with another account
// so eat the validation exception and let the claim pass thru
}
}
}
}
public override Task IsActiveAsync(IsActiveContext ctx)
{
var subject = ctx.Subject;
var acct = userAccountService.GetByID(subject.GetSubjectId().ToGuid());
ctx.IsActive = acct != null && !acct.IsAccountClosed && acct.IsLoginAllowed;
return Task.FromResult(0);
}
}
static class Extensions
{
public static Guid ToGuid(this string s)
{
Guid g;
if (Guid.TryParse(s, out g))
{
return g;
}
return Guid.Empty;
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// CESchedulerPairTests.cs
// Tests Ported from the TPL test bed
//
// Summary:
// Implements the tests for the new scheduler ConcurrentExclusiveSchedulerPair
//
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Security;
using Xunit;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class TrackingTaskScheduler : TaskScheduler
{
public TrackingTaskScheduler(int maxConLevel)
{
//We need to set the value to 1 so that each time a scheduler is created, its tasks will start with one.
_counter = 1;
if (maxConLevel < 1 && maxConLevel != -1/*infinite*/)
throw new ArgumentException("Maximum concurrency level should between 1 and int32.Maxvalue");
_maxConcurrencyLevel = maxConLevel;
}
[SecurityCritical]
protected override void QueueTask(Task task)
{
if (task == null) throw new ArgumentNullException("When reqeusting to QueueTask, the input task can not be null");
Task.Factory.StartNew(() =>
{
lock (_lockObj) //Locking so that if mutliple threads in threadpool does not incorrectly increment the counter.
{
//store the current value of the counter (This becomes the unique ID for this scheduler's Task)
SchedulerID.Value = _counter;
_counter++;
}
ExecuteTask(task); //Extracted out due to security attribute reason.
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
[SecuritySafeCritical] //This has to be SecuritySafeCritical since its accesses TaskScheduler.TryExecuteTask (which is safecritical)
private void ExecuteTask(Task task)
{
base.TryExecuteTask(task);
}
[SecurityCritical]
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (taskWasPreviouslyQueued) return false;
return TryExecuteTask(task);
}
//public int SchedulerID
//{
// get;
// set;
//}
[SecurityCritical]
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
private Object _lockObj = new Object();
private int _counter = 1; //This is used ot keep track of how many scheduler tasks were created
public ThreadLocal<int> SchedulerID = new ThreadLocal<int>(); //This is the ID of the scheduler.
/// <summary>The maximum concurrency level for the scheduler.</summary>
private readonly int _maxConcurrencyLevel;
public override int MaximumConcurrencyLevel { get { return _maxConcurrencyLevel; } }
}
public class CESchedulerPairTests
{
#region Test cases
/// <summary>
/// Test to ensure that ConcurrentExclusiveSchedulerPair can be created using user defined parameters
/// and those parameters are respected when tasks are executed
/// </summary>
/// <remarks>maxItemsPerTask and which scheduler is used are verified in other testcases</remarks>
[Theory]
[InlineData("default")]
[InlineData("scheduler")]
[InlineData("maxconcurrent")]
[InlineData("all")]
public static void TestCreationOptions(String ctorType)
{
ConcurrentExclusiveSchedulerPair schedPair = null;
//Need to define the default values since these values are passed to the verification methods
TaskScheduler scheduler = TaskScheduler.Default;
int maxConcurrentLevel = Environment.ProcessorCount;
//Based on input args, use one of the ctor overloads
switch (ctorType.ToLower())
{
case "default":
schedPair = new ConcurrentExclusiveSchedulerPair();
break;
case "scheduler":
schedPair = new ConcurrentExclusiveSchedulerPair(scheduler);
break;
case "maxconcurrent":
maxConcurrentLevel = 2;
schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrentLevel);
break;
case "all":
maxConcurrentLevel = Int32.MaxValue;
schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, -1/*MaxConcurrentLevel*/, -1/*MaxItemsPerTask*/); //-1 gets converted to Int32.MaxValue
break;
default:
throw new NotImplementedException(String.Format("The option specified {0} to create the ConcurrentExclusiveSchedulerPair is invalid", ctorType));
}
//Create the factories that use the exclusive scheduler and the concurrent scheduler. We test to ensure
//that the ConcurrentExclusiveSchedulerPair created are valid by scheduling work on them.
TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler);
List<Task> taskList = new List<Task>(); //Store all tasks created, to enable wait until all of them are finished
// Schedule some dummy work that should be run with as much parallelism as possible
for (int i = 0; i < 50; i++)
{
//In the current design, when there are no more tasks to execute, the Task used by concurrentexclusive scheduler dies
//by sleeping we simulate some non trival work that takes time and causes the concurrentexclusive scheduler Task
//to stay around for addition work.
taskList.Add(readers.StartNew(() => { new ManualResetEvent(false).WaitOne(10); }));
}
// Schedule work where each item must be run when no other items are running
for (int i = 0; i < 10; i++) taskList.Add(writers.StartNew(() => { new ManualResetEvent(false).WaitOne(5); }));
//Wait on the tasks to finish to ensure that the ConcurrentExclusiveSchedulerPair created can schedule and execute tasks without issues
foreach (var item in taskList)
{
item.Wait();
}
//verify that maxconcurrency was respected.
if (ctorType == "maxconcurrent")
{
Assert.Equal(maxConcurrentLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel);
}
Assert.Equal(1, schedPair.ExclusiveScheduler.MaximumConcurrencyLevel);
//verify that the schedulers have not completed
Assert.False(schedPair.Completion.IsCompleted, "The schedulers should not have completed as a completion request was not issued.");
//complete the scheduler and make sure it shuts down successfully
schedPair.Complete();
schedPair.Completion.Wait();
//make sure no additional work may be scheduled
foreach (var schedPairScheduler in new TaskScheduler[] { schedPair.ConcurrentScheduler, schedPair.ExclusiveScheduler })
{
Exception caughtException = null;
try
{
Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, schedPairScheduler);
}
catch (Exception exc)
{
caughtException = exc;
}
Assert.True(
caughtException is TaskSchedulerException && caughtException.InnerException is InvalidOperationException,
"Queueing after completion should fail");
}
}
/// <summary>
/// Test to verify that only upto maxItemsPerTask are executed by a single ConcurrentExclusiveScheduler Task
/// </summary>
/// <remarks>In ConcurrentExclusiveSchedulerPair, each tasks scheduled are run under an internal Task. The basic idea for the test
/// is that each time ConcurrentExclusiveScheduler is called QueueTasK a counter (which acts as scheduler's Task id) is incremented.
/// When a task executes, it observes the parent Task Id and if it matches the one its local cache, it increments its local counter (which tracks
/// the items executed by a ConcurrentExclusiveScheduler Task). At any given time the Task's local counter cant exceed maxItemsPerTask</remarks>
[Theory]
[InlineData(4, 1, true)]
[InlineData(1, 4, true)]
[InlineData(4, 1, false)]
[InlineData(1, 4, false)]
public static void TestMaxItemsPerTask(int maxConcurrency, int maxItemsPerTask, bool completeBeforeTaskWait)
{
//Create a custom TaskScheduler with specified max concurrency (TrackingTaskScheduler is defined in Common\tools\CommonUtils\TPLTestSchedulers.cs)
TrackingTaskScheduler scheduler = new TrackingTaskScheduler(maxConcurrency);
//We need to use the custom scheduler to achieve the results. As a by-product, we test to ensure custom schedulers are supported
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrency, maxItemsPerTask);
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); //get reader and writer schedulers
TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);
//These are threadlocals to ensure that no concurrency side effects occur
ThreadLocal<int> itemsExecutedCount = new ThreadLocal<int>(); //Track the items executed by CEScheduler Task
ThreadLocal<int> schedulerIDInsideTask = new ThreadLocal<int>(); //Used to store the Scheduler ID observed by a Task Executed by CEScheduler Task
//Work done by both reader and writer tasks
Action work = () =>
{
//Get the id of the parent Task (which is the task created by the scheduler). Each task run by the scheduler task should
//see the same SchedulerID value since they are run on the same thread
int id = ((TrackingTaskScheduler)scheduler).SchedulerID.Value;
if (id == schedulerIDInsideTask.Value)
{ //since ids match, this is one more Task being executed by the CEScheduler Task
itemsExecutedCount.Value = ++itemsExecutedCount.Value;
//This does not need to be thread safe since we are looking to ensure that only n number of tasks were executed and not the order
//in which they were executed. Also asserting inside the thread is fine since we just want the test to be marked as failure
Assert.True(itemsExecutedCount.Value <= maxItemsPerTask, string.Format("itemsExecutedCount={0} cant be greater than maxValue={1}. Parent TaskID={2}",
itemsExecutedCount, maxItemsPerTask, id));
}
else
{ //Since ids dont match, this is the first Task being executed in the CEScheduler Task
schedulerIDInsideTask.Value = id; //cache the scheduler ID seen by the thread, so other tasks running in same thread can see this
itemsExecutedCount.Value = 1;
}
//Give enough time for a Task to stay around, so that other tasks will be executed by the same CEScheduler Task
//or else the CESchedulerTask will die and each Task might get executed by a different CEScheduler Task. This does not affect the
//verifications, but its increases the chance of finding a bug if the maxItemPerTask is not respected
new ManualResetEvent(false).WaitOne(20);
};
List<Task> taskList = new List<Task>();
int maxConcurrentTasks = maxConcurrency * maxItemsPerTask * 5;
int maxExclusiveTasks = maxConcurrency * maxItemsPerTask * 2;
// Schedule Tasks in both concurrent and exclusive mode
for (int i = 0; i < maxConcurrentTasks; i++)
taskList.Add(readers.StartNew(work));
for (int i = 0; i < maxExclusiveTasks; i++)
taskList.Add(writers.StartNew(work));
if (completeBeforeTaskWait)
{
schedPair.Complete();
schedPair.Completion.Wait();
Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
}
//finally wait for all of the tasks, to ensure they all executed properly
Task.WaitAll(taskList.ToArray());
if (!completeBeforeTaskWait)
{
schedPair.Complete();
schedPair.Completion.Wait();
Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
}
}
/// <summary>
/// When user specfices a concurrency level above the level allowed by the task scheduler, the concurrency level should be set
/// to the concurrencylevel specified in the taskscheduler. Also tests that the maxConcurrencyLevel specified was respected
/// </summary>
[Fact]
public static void TestLowerConcurrencyLevel()
{
//a custom scheduler with maxConcurrencyLevel of one
int customSchedulerConcurrency = 1;
TrackingTaskScheduler scheduler = new TrackingTaskScheduler(customSchedulerConcurrency);
// specify a maxConcurrencyLevel > TaskScheduler's maxconcurrencyLevel to ensure the pair takes the min of the two
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, Int32.MaxValue);
Assert.Equal(scheduler.MaximumConcurrencyLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel);
//Now schedule a reader task that would block and verify that more reader tasks scheduled are not executed
//(as long as the first task is blocked)
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler);
ManualResetEvent blockReaderTaskEvent = new ManualResetEvent(false);
ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false);
//Add a reader tasks that would block
readers.StartNew(() => { blockMainThreadEvent.Set(); blockReaderTaskEvent.WaitOne(); });
blockMainThreadEvent.WaitOne(); // wait for the blockedTask to start execution
//Now add more reader tasks
int maxConcurrentTasks = Environment.ProcessorCount;
List<Task> taskList = new List<Task>();
for (int i = 0; i < maxConcurrentTasks; i++)
taskList.Add(readers.StartNew(() => { })); //schedule some dummy reader tasks
foreach (Task task in taskList)
{
bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion);
Assert.True(wasTaskStarted, string.Format("Additional reader tasks should not start when scheduler concurrency is {0} and a reader task is blocked", customSchedulerConcurrency));
}
//finally unblock the blocjedTask and wait for all of the tasks, to ensure they all executed properly
blockReaderTaskEvent.Set();
Task.WaitAll(taskList.ToArray());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestConcurrentBlockage(bool useReader)
{
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair();
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler);
TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);
ManualResetEvent blockExclusiveTaskEvent = new ManualResetEvent(false);
ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false);
ManualResetEvent blockMre = new ManualResetEvent(false);
//Schedule a concurrent task and ensure that it is executed, just for fun
Task<bool> conTask = readers.StartNew<bool>(() => { new ManualResetEvent(false).WaitOne(10); ; return true; });
conTask.Wait();
Assert.True(conTask.Result, "The concurrenttask when executed successfully should have returned true");
//Now scehdule a exclusive task that is blocked(thereby preventing other concurrent tasks to finish)
Task<bool> exclusiveTask = writers.StartNew<bool>(() => { blockMainThreadEvent.Set(); blockExclusiveTaskEvent.WaitOne(); return true; });
//With exclusive task in execution mode, schedule a number of concurrent tasks and ensure they are not executed
blockMainThreadEvent.WaitOne();
List<Task> taskList = new List<Task>();
for (int i = 0; i < 20; i++) taskList.Add(readers.StartNew<bool>(() => { blockMre.WaitOne(10); return true; }));
foreach (Task task in taskList)
{
bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion);
Assert.True(wasTaskStarted, "Concurrent tasks should not be executed when a exclusive task is getting executed");
}
blockExclusiveTaskEvent.Set();
Task.WaitAll(taskList.ToArray());
}
[Theory]
[MemberData(nameof(ApiType))]
public static void TestIntegration(String apiType, bool useReader)
{
Debug.WriteLine(string.Format(" Running apiType:{0} useReader:{1}", apiType, useReader));
int taskCount = Environment.ProcessorCount; //To get varying number of tasks as a function of cores
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair();
CountdownEvent cde = new CountdownEvent(taskCount); //Used to track how many tasks were executed
Action work = () => { cde.Signal(); }; //Work done by all APIs
//Choose the right scheduler to use based on input parameter
TaskScheduler scheduler = useReader ? schedPair.ConcurrentScheduler : schedPair.ExclusiveScheduler;
SelectAPI2Target(apiType, taskCount, scheduler, work);
cde.Wait(); //This will cause the test to block (and timeout) until all tasks are finished
}
/// <summary>
/// Test to ensure that invalid parameters result in exceptions
/// </summary>
[Fact]
public static void TestInvalidParameters()
{
Assert.Throws<ArgumentNullException>(() => new ConcurrentExclusiveSchedulerPair(null)); //TargetScheduler is null
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 0)); //maxConcurrencyLevel is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -2)); //maxConcurrencyLevel is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, 0)); //maxItemsPerTask is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, -2)); //maxItemsPerTask is invalid
}
/// <summary>
/// Test to ensure completion task works successfully
/// </summary>
[Fact]
public static void TestCompletionTask()
{
// Completion tasks is valid after initialization
{
var cesp = new ConcurrentExclusiveSchedulerPair();
Assert.True(cesp.Completion != null, "CompletionTask should never be null (after initialization)");
Assert.True(!cesp.Completion.IsCompleted, "CompletionTask should not have completed");
}
// Completion task is valid after complete is called
{
var cesp = new ConcurrentExclusiveSchedulerPair();
cesp.Complete();
Assert.True(cesp.Completion != null, "CompletionTask should never be null (after complete)");
cesp.Completion.Wait();
}
// Complete method may be called multiple times, and CompletionTask still completes
{
var cesp = new ConcurrentExclusiveSchedulerPair();
for (int i = 0; i < 20; i++) cesp.Complete(); // ensure multiple calls to Complete succeed
Assert.True(cesp.Completion != null, "CompletionTask should never be null (after multiple completes)");
cesp.Completion.Wait();
}
// Can create a bunch of schedulers, do work on them all, complete them all, and they all complete
{
var cesps = new ConcurrentExclusiveSchedulerPair[100];
for (int i = 0; i < cesps.Length; i++)
{
cesps[i] = new ConcurrentExclusiveSchedulerPair();
}
for (int i = 0; i < cesps.Length; i++)
{
Action work = () => new ManualResetEvent(false).WaitOne(2); ;
Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ConcurrentScheduler);
Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ExclusiveScheduler);
}
for (int i = 0; i < cesps.Length; i++)
{
cesps[i].Complete();
cesps[i].Completion.Wait();
}
}
// Validate that CESP does not implement IDisposable
Assert.Equal(null, new ConcurrentExclusiveSchedulerPair() as IDisposable);
}
/// <summary>
/// Ensure that CESPs can be layered on other CESPs.
/// </summary
[Fact]
public static void TestSchedulerNesting()
{
// Create a hierarchical set of scheduler pairs
var cespParent = new ConcurrentExclusiveSchedulerPair();
var cespChild1 = new ConcurrentExclusiveSchedulerPair(cespParent.ConcurrentScheduler);
var cespChild1Child1 = new ConcurrentExclusiveSchedulerPair(cespChild1.ConcurrentScheduler);
var cespChild1Child2 = new ConcurrentExclusiveSchedulerPair(cespChild1.ExclusiveScheduler);
var cespChild2 = new ConcurrentExclusiveSchedulerPair(cespParent.ExclusiveScheduler);
var cespChild2Child1 = new ConcurrentExclusiveSchedulerPair(cespChild2.ConcurrentScheduler);
var cespChild2Child2 = new ConcurrentExclusiveSchedulerPair(cespChild2.ExclusiveScheduler);
// these are ordered such that we will complete the child schedulers before we complete their parents. That way
// we don't complete a parent that's still in use.
var cesps = new[] {
cespChild1Child1,
cespChild1Child2,
cespChild1,
cespChild2Child1,
cespChild2Child2,
cespChild2,
cespParent,
};
// Get the schedulers from all of the pairs
List<TaskScheduler> schedulers = new List<TaskScheduler>();
foreach (var s in cesps)
{
schedulers.Add(s.ConcurrentScheduler);
schedulers.Add(s.ExclusiveScheduler);
}
// Keep track of all created tasks
var tasks = new List<Task>();
// Queue lots of work to each scheduler
foreach (var scheduler in schedulers)
{
// Create a function that schedules and inlines recursively queued tasks
Action<int> recursiveWork = null;
recursiveWork = depth =>
{
if (depth > 0)
{
Action work = () =>
{
new ManualResetEvent(false).WaitOne(1);
recursiveWork(depth - 1);
};
TaskFactory factory = new TaskFactory(scheduler);
Debug.WriteLine(string.Format("Start tasks in scheduler {0}", scheduler.Id));
Task t1 = factory.StartNew(work); Task t2 = factory.StartNew(work); Task t3 = factory.StartNew(work);
Task.WaitAll(t1, t2, t3);
}
};
for (int i = 0; i < 2; i++)
{
tasks.Add(Task.Factory.StartNew(() => recursiveWork(2), CancellationToken.None, TaskCreationOptions.None, scheduler));
}
}
// Wait for all tasks to complete, then complete the schedulers
Task.WaitAll(tasks.ToArray());
foreach (var cesp in cesps)
{
cesp.Complete();
cesp.Completion.Wait();
}
}
/// <summary>
/// Ensure that continuations and parent/children which hop between concurrent and exclusive work correctly.
/// EH
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestConcurrentExclusiveChain(bool syncContinuations)
{
var scheduler = new TrackingTaskScheduler(Environment.ProcessorCount);
var cesp = new ConcurrentExclusiveSchedulerPair(scheduler);
// continuations
{
var starter = new Task(() => { });
var t = starter;
for (int i = 0; i < 10; i++)
{
t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ConcurrentScheduler);
t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ExclusiveScheduler);
}
starter.Start(cesp.ExclusiveScheduler);
t.Wait();
}
// parent/child
{
var errorString = "hello faulty world";
var root = Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
throw new InvalidOperationException(errorString);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler).Wait();
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler);
}, CancellationToken.None, TaskCreationOptions.None, cesp.ConcurrentScheduler);
((IAsyncResult)root).AsyncWaitHandle.WaitOne();
Assert.True(root.IsFaulted, "Root should have been faulted by child's error");
var ae = root.Exception.Flatten();
Assert.True(ae.InnerException is InvalidOperationException && ae.InnerException.Message == errorString,
"Child's exception should have propagated to the root.");
}
}
#endregion
#region Helper Methods
public static void SelectAPI2Target(string apiType, int taskCount, TaskScheduler scheduler, Action work)
{
switch (apiType)
{
case "StartNew":
for (int i = 0; i < taskCount; i++) new TaskFactory(scheduler).StartNew(() => { work(); });
break;
case "Start":
for (int i = 0; i < taskCount; i++) new Task(() => { work(); }).Start(scheduler);
break;
case "ContinueWith":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory().StartNew(() => { }).ContinueWith((t) => { work(); }, scheduler);
}
break;
case "FromAsync":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory(scheduler).FromAsync(Task.Factory.StartNew(() => { }), (iar) => { work(); });
}
break;
case "ContinueWhenAll":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory(scheduler).ContinueWhenAll(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); });
}
break;
case "ContinueWhenAny":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory(scheduler).ContinueWhenAny(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); });
}
break;
default:
throw new ArgumentOutOfRangeException(String.Format("Api name specified {0} is invalid or is of incorrect case", apiType));
}
}
/// <summary>
/// Used to provide parameters for the TestIntegration test
/// </summary>
public static IEnumerable<object[]> ApiType
{
get
{
List<Object[]> values = new List<object[]>();
foreach (String apiType in new String[] {
"StartNew", "Start", "ContinueWith", /* FromAsync: Not supported in .NET Native */ "ContinueWhenAll", "ContinueWhenAny" })
{
foreach (bool useReader in new bool[] { true, false })
{
values.Add(new Object[] { apiType, useReader });
}
}
return values;
}
}
#endregion
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Linq;
using Glass.Mapper.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Globalization;
namespace Glass.Mapper.Sc.Configuration
{
/// <summary>
/// Class SitecoreTypeConfiguration
/// </summary>
public class SitecoreTypeConfiguration : AbstractTypeConfiguration
{
/// <summary>
/// Gets or sets the template id.
/// </summary>
/// <value>The template id.</value>
public ID TemplateId { get; set; }
/// <summary>
/// Gets or sets the branch id.
/// </summary>
/// <value>The branch id.</value>
public ID BranchId { get; set; }
/// <summary>
/// Gets or sets the id config.
/// </summary>
/// <value>The id config.</value>
public SitecoreIdConfiguration IdConfig { get; set; }
/// <summary>
/// Gets or sets the language config.
/// </summary>
/// <value>The language config.</value>
public SitecoreInfoConfiguration LanguageConfig { get; set; }
/// <summary>
/// Gets or sets the version config.
/// </summary>
/// <value>The version config.</value>
public SitecoreInfoConfiguration VersionConfig { get; set; }
/// <summary>
/// Gets or sets the item config
/// </summary>
public SitecoreItemConfiguration ItemConfig { get; set; }
/// <summary>
/// Gets or sets the ItemUri config
/// </summary>
public SitecoreInfoConfiguration ItemUriConfig { get; set; }
/// <summary>
/// Indicates that the class is used in a code first scenario.
/// </summary>
/// <value><c>true</c> if [code first]; otherwise, <c>false</c>.</value>
public bool CodeFirst { get; set; }
/// <summary>
/// Overrides the default template name when using code first
/// </summary>
/// <value>The name of the template.</value>
public string TemplateName { get; set; }
/// <summary>
/// Forces Glass to do a template check and only returns an class if the item
/// matches the template ID or inherits a template with the templateId
/// </summary>
public SitecoreEnforceTemplate EnforceTemplate { get; set; }
/// <summary>
/// Adds the property.
/// </summary>
/// <param name="property">The property.</param>
public override void AddProperty(AbstractPropertyConfiguration property)
{
if (property is SitecoreIdConfiguration)
IdConfig = property as SitecoreIdConfiguration;
var infoProperty = property as SitecoreInfoConfiguration;
if (infoProperty != null)
{
switch (infoProperty.Type)
{
case SitecoreInfoType.Language:
LanguageConfig = infoProperty;
break;
case SitecoreInfoType.Version:
VersionConfig = infoProperty;
break;
case SitecoreInfoType.ItemUri:
ItemUriConfig = infoProperty;
break;
}
}
if (property is SitecoreItemConfiguration)
ItemConfig = property as SitecoreItemConfiguration;
base.AddProperty(property);
}
public ID GetId(object target)
{
ID id = ID.Null;
if (IdConfig != null)
{
if (IdConfig.PropertyInfo.PropertyType == typeof (Guid))
{
var guidId = (Guid) IdConfig.PropertyInfo.GetValue(target, null);
id = new ID(guidId);
}
else if (IdConfig.PropertyInfo.PropertyType == typeof (ID))
{
id = IdConfig.PropertyInfo.GetValue(target, null) as ID;
}
else
{
throw new NotSupportedException("Cannot get ID for item");
}
}
else if (ItemUriConfig != null)
{
var itemUri = (ItemUri)ItemUriConfig.PropertyInfo.GetValue(target, null);
if (itemUri != null)
{
id = itemUri.ItemID;
}
}
return id;
}
/// <summary>
/// Dumps information about the current type configuration to the Sitecore logs.
/// </summary>
public virtual void LogDumpConfiguration()
{
Sitecore.Diagnostics.Log.Debug("CD - Configuration Dump for {0}".Formatted(Type.FullName), this);
var interaces = Type.GetInterfaces();
if (interaces.Any())
{
Sitecore.Diagnostics.Log.Debug("CD - {0}".Formatted(interaces.Select(x => x.FullName).Aggregate((x, y) => "{0}, {1}".Formatted(x, y))), this);
}
if (Properties != null)
{
foreach (var property in Properties)
{
Sitecore.Diagnostics.Log.Debug("CD - property: {0} - {1}".Formatted(property.PropertyInfo.Name, property.PropertyInfo.PropertyType.FullName), this);
}
}
}
/// <summary>
/// Resolves the item.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="database">The database.</param>
/// <returns>
/// Item.
/// </returns>
/// <exception cref="System.NotSupportedException">You can not save a class that does not contain a property that represents the item ID. Ensure that at least one property has been marked to contain the Sitecore ID.
/// or
/// Cannot get ID for item</exception>
public Item ResolveItem(object target, Database database)
{
if (target == null)
return null;
ID id;
Language language = null;
int versionNumber = -1;
if (ItemConfig != null)
{
var item = ItemConfig.PropertyGetter(target) as Item;
if (item != null)
return item;
}
if (IdConfig == null && ItemUriConfig == null)
{
string message =
"Failed item resolve - You cannot save a class that does not contain a property that represents the item ID. Ensure that at least one property has been marked to contain the Sitecore ID. Type: {0}"
.Formatted(target.GetType().FullName);
Sitecore.Diagnostics.Log.Error(message, this);
LogDumpConfiguration();
throw new NotSupportedException(message);
}
id = GetId(target);
language = GetLanguage(target);
versionNumber = GetVersion(target);
if (language != null && versionNumber > 0)
{
return database.GetItem(id, language, new global::Sitecore.Data.Version(versionNumber));
}
else if (language != null)
{
return database.GetItem(id, language);
}
else
{
return database.GetItem(id);
}
}
public int GetVersion(object target)
{
int versionNumber = -1;
if (VersionConfig != null)
{
var valueInt = VersionConfig.PropertyInfo.GetValue(target, null);
if (valueInt is int)
{
versionNumber = (int)valueInt;
}
else if (valueInt is string)
{
int.TryParse(valueInt as string, out versionNumber);
}
}
else if (ItemUriConfig != null)
{
var itemUri = (ItemUri)ItemUriConfig.PropertyInfo.GetValue(target, null);
if (itemUri != null)
{
versionNumber = itemUri.Version.Number;
}
}
return versionNumber;
}
/// <summary>
/// Gets the language.
/// </summary>
/// <param name="target">The target.</param>
/// <returns></returns>
public Language GetLanguage(object target)
{
Language language = null;
if (LanguageConfig != null)
{
object langValue = LanguageConfig.PropertyInfo.GetValue(target, null);
if (langValue == null)
{
language = Language.Current;
}
else if (langValue is Language)
{
language = langValue as Language;
}
else if (langValue is string)
{
language = LanguageManager.GetLanguage(langValue as string);
}
}
else if (ItemUriConfig != null)
{
var itemUri = (ItemUri)ItemUriConfig.PropertyInfo.GetValue(target, null);
if (itemUri != null)
{
language = itemUri.Language;
}
}
return language;
}
/// <summary>
/// Called to map each property automatically
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
protected override AbstractPropertyConfiguration AutoMapProperty(System.Reflection.PropertyInfo property)
{
string name = property.Name;
SitecoreInfoType infoType;
if (name.ToLowerInvariant() == "id")
{
var idConfig = new SitecoreIdConfiguration();
idConfig.PropertyInfo = property;
return idConfig;
}
if (name.ToLowerInvariant() == "parent")
{
var parentConfig = new SitecoreParentConfiguration();
parentConfig.PropertyInfo = property;
return parentConfig;
}
if (name.ToLowerInvariant() == "children")
{
var childrenConfig = new SitecoreChildrenConfiguration();
childrenConfig.PropertyInfo = property;
return childrenConfig;
}
if (name.ToLowerInvariant() == "item" && property.PropertyType == typeof(Item))
{
var itemConfig = new SitecoreItemConfiguration();
itemConfig.PropertyInfo = property;
return itemConfig;
}
if (Enum.TryParse(name, true, out infoType))
{
SitecoreInfoConfiguration infoConfig = new SitecoreInfoConfiguration();
infoConfig.PropertyInfo = property;
infoConfig.Type = infoType;
return infoConfig;
}
SitecoreFieldConfiguration fieldConfig = new SitecoreFieldConfiguration();
fieldConfig.FieldName = name;
fieldConfig.PropertyInfo = property;
return fieldConfig;
}
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Fungus.EditorUtils
{
/// <summary>
/// Common base for PopupWindowContent that is a search filterable list a la AddComponent
///
/// Inspired by https://github.com/roboryantron/UnityEditorJunkie/blob/master/Assets/SearchableEnum/Code/Editor/SearchablePopup.cs
/// </summary>
public abstract class BasePopupWindowContent : PopupWindowContent
{
/// <summary>
/// Called when the user has confirmed an item from the menu.
/// </summary>
/// <param name="index">Index of into the original list of items to show given to the popupcontent</param>
abstract protected void SelectByOrigIndex(int index);
/// <summary>
/// Called during Base Ctor, must fill allItems list so the ctor can continue to fill
/// the visible items and current selected index.
/// </summary>
abstract protected void PrepareAllItems();
/// <summary>
/// Internal representation of 1 row of our popup list
/// </summary>
public class FilteredListItem
{
public FilteredListItem(int index, string str, string tip = "")
{
origIndex = index;
name = str;
lowerName = str.ToLowerInvariant();
content = new GUIContent(str, tip);
}
public int origIndex;
public string name, lowerName;
public GUIContent content;
}
protected int hoverIndex;
protected readonly string SEARCH_CONTROL_NAME = "PopupSearchControlName";
protected readonly float ROW_HEIGHT = EditorGUIUtility.singleLineHeight;
protected List<FilteredListItem> allItems = new List<FilteredListItem>(),
visibleItems = new List<FilteredListItem>();
protected string currentFilter = string.Empty;
protected Vector2 scroll;
protected int scrollToIndex;
protected float scrollOffset;
protected int currentIndex;
protected Vector2 size;
protected bool hasNoneOption = false;
static readonly char[] SEARCH_SPLITS = new char[]{ CATEGORY_CHAR, ' ' };
protected static readonly char CATEGORY_CHAR = '/';
public BasePopupWindowContent(string currentHandlerName, int width, int height, bool showNoneOption = false)
{
this.size = new Vector2(width, height);
hasNoneOption = showNoneOption;
PrepareAllItems();
allItems.Sort((lhs, rhs) =>
{
//order root level objects first
var islhsRoot = lhs.lowerName.IndexOf(CATEGORY_CHAR) != -1;
var isrhsRoot = rhs.lowerName.IndexOf(CATEGORY_CHAR) != -1;
if(islhsRoot == isrhsRoot)
return lhs.lowerName.CompareTo(rhs.lowerName);
return islhsRoot ? 1 : -1;
});
UpdateFilter();
currentIndex = Mathf.Max(0, visibleItems.FindIndex(x=>x.name.Contains(currentHandlerName)));
hoverIndex = currentIndex;
}
public override void OnGUI(Rect rect)
{
Rect searchRect = new Rect(0, 0, rect.width, EditorStyles.toolbar.fixedHeight);
Rect scrollRect = Rect.MinMaxRect(0, searchRect.yMax, rect.xMax, rect.yMax);
HandleKeyboard();
DrawSearch(searchRect);
DrawSelectionArea(scrollRect);
}
public override Vector2 GetWindowSize()
{
return size;
}
private void DrawSearch(Rect rect)
{
if (Event.current.type == EventType.Repaint)
EditorStyles.toolbar.Draw(rect, false, false, false, false);
Rect searchRect = new Rect(rect);
searchRect.xMin += 6;
searchRect.xMax -= 6;
searchRect.y += 2;
GUI.FocusControl(SEARCH_CONTROL_NAME);
GUI.SetNextControlName(SEARCH_CONTROL_NAME);
var prevFilter = currentFilter;
currentFilter = GUI.TextField(searchRect, currentFilter);
if (prevFilter != currentFilter)
{
UpdateFilter();
}
}
private void UpdateFilter()
{
var curlower = currentFilter.ToLowerInvariant();
var lowers = curlower.Split(SEARCH_SPLITS);
lowers = lowers.Where(x => x.Length > 0).ToArray();
if (lowers == null || lowers.Length == 0)
{
visibleItems.AddRange(allItems);
}
else
{
visibleItems = allItems.Where(x =>
{
//we want all tokens
foreach (var item in lowers)
{
if (!x.lowerName.Contains(item))
return false;
}
return true;
}).ToList();
}
hoverIndex = 0;
scroll = Vector2.zero;
if(hasNoneOption)
visibleItems.Insert(0, new FilteredListItem(-1, "None"));
}
private void DrawSelectionArea(Rect scrollRect)
{
Rect contentRect = new Rect(0, 0,
scrollRect.width - GUI.skin.verticalScrollbar.fixedWidth,
visibleItems.Count * ROW_HEIGHT);
scroll = GUI.BeginScrollView(scrollRect, scroll, contentRect);
Rect rowRect = new Rect(0, 0, scrollRect.width, ROW_HEIGHT);
for (int i = 0; i < visibleItems.Count; i++)
{
if (scrollToIndex == i &&
(Event.current.type == EventType.Repaint
|| Event.current.type == EventType.Layout))
{
Rect r = new Rect(rowRect);
r.y += scrollOffset;
GUI.ScrollTo(r);
scrollToIndex = -1;
scroll.x = 0;
}
if (rowRect.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.MouseMove ||
Event.current.type == EventType.ScrollWheel)
{
//if new item force update so it's snappier
if (hoverIndex != 1)
{
this.editorWindow.Repaint();
}
hoverIndex = i;
}
if (Event.current.type == EventType.MouseDown)
{
//onSelectionMade(list.Entries[i].Index);
SelectByOrigIndex(visibleItems[i].origIndex);
EditorWindow.focusedWindow.Close();
}
}
DrawRow(rowRect, i);
rowRect.y = rowRect.yMax;
}
GUI.EndScrollView();
}
private static void DrawBox(Rect rect, Color tint)
{
Color c = GUI.color;
GUI.color = tint;
GUI.Box(rect, "");
GUI.color = c;
}
private void DrawRow(Rect rowRect, int i)
{
if (i == currentIndex)
DrawBox(rowRect, Color.cyan);
else if (i == hoverIndex)
DrawBox(rowRect, Color.white);
Rect labelRect = new Rect(rowRect);
//labelRect.xMin += ROW_INDENT;
GUI.Label(labelRect, visibleItems[i].content);
}
/// <summary>
/// Process keyboard input to navigate the choices or make a selection.
/// </summary>
private void HandleKeyboard()
{
if (Event.current.type == EventType.KeyDown)
{
if (Event.current.keyCode == KeyCode.DownArrow)
{
hoverIndex = Mathf.Min(visibleItems.Count - 1, hoverIndex + 1);
Event.current.Use();
scrollToIndex = hoverIndex;
scrollOffset = ROW_HEIGHT;
}
if (Event.current.keyCode == KeyCode.UpArrow)
{
hoverIndex = Mathf.Max(0, hoverIndex - 1);
Event.current.Use();
scrollToIndex = hoverIndex;
scrollOffset = -ROW_HEIGHT;
}
if (Event.current.keyCode == KeyCode.Return)
{
if (hoverIndex >= 0 && hoverIndex < visibleItems.Count)
{
SelectByOrigIndex(visibleItems[hoverIndex].origIndex);
EditorWindow.focusedWindow.Close();
}
}
if (Event.current.keyCode == KeyCode.Escape)
{
EditorWindow.focusedWindow.Close();
}
}
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Runtime.InteropServices;
using System.Windows.Interop;
using SpatialAnalysis.CellularEnvironment;
namespace SpatialAnalysis.Data.ImportData
{
/// <summary>
/// Interaction logic for DataImportInterface.xaml
/// </summary>
public partial class DataImportInterface : Window
{
/// <summary>
/// Gets or sets the scale.
/// </summary>
/// <value>The scale.</value>
public double Scale { get; set; }
/// <summary>
/// Gets or sets the index of the x.
/// </summary>
/// <value>The index of the x.</value>
public int X_Index { get; set; }
/// <summary>
/// Gets or sets the index of the y.
/// </summary>
/// <value>The index of the y.</value>
public int Y_Index { get; set; }
/// <summary>
/// Gets or sets the selected indexes.
/// </summary>
/// <value>The selected indexes.</value>
public HashSet<int> SelectedIndices { get; set; }
private Dictionary<string, int> FieldsToID { get; set; }
private Dictionary<int, string> IDToFields { get; set; }
/// <summary>
/// The names of the data fields
/// </summary>
public string[] Names;
private string[] importedData { get; set; }
private CellularFloor cellularFloor { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DataImportInterface"/> class.
/// </summary>
/// <param name="inputData">The input data.</param>
/// <param name="cellularFloor_">The cellular floor.</param>
public DataImportInterface(string[] inputData, CellularFloor cellularFloor_)
{
InitializeComponent();
this.cellularFloor = cellularFloor_;
this.importedData = inputData;
this.Remove.Content = "<";
this.RemoveAll.Content = "<< All";
this.FieldsToID = new Dictionary<string, int>();
this.IDToFields = new Dictionary<int, string>();
this.Names = inputData[0].Split(',');
for (int i = 0; i < this.Names.Length; i++)
{
this.FieldsToID.Add(this.Names[i], i);
this.IDToFields.Add(i, this.Names[i]);
this.fields_X.Items.Add(this.Names[i]);
this.fields_Y.Items.Add(this.Names[i]);
}
this.SelectedIndices = new HashSet<int>();
this.X_Index = -1;
this.Y_Index = -1;
}
#region Hiding the close button
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
//Hiding the close button
private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
#endregion
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.X_Index = -1;
this.Y_Index = -1;
this.Close();
}
private void Done_Click(object sender, RoutedEventArgs e)
{
if (this.Selected.Items.Count == 0)
{
this.X_Index = -1;
this.Y_Index = -1;
this.Close();
return;
}
else
{
double k;
if (double.TryParse(this.ScaleBox.Text, out k))
{
this.Scale = k;
}
else
{
MessageBox.Show("Enter appropriate input for scale");
return;
}
}
foreach (object item in this.Selected.Items)
{
this.SelectedIndices.Add(this.FieldsToID[(string)item]);
}
this.Close();
}
private void Add_Click(object sender, RoutedEventArgs e)
{
int i = this.Imported.SelectedIndex;
if (i != -1)
{
string s = (string)this.Imported.SelectedItem;
this.Selected.Items.Add(s);
this.Imported.Items.RemoveAt(i);
}
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
int i = this.Selected.SelectedIndex;
if (i != -1)
{
string s = (string)this.Selected.SelectedItem;
this.Imported.Items.Add(s);
this.Selected.Items.RemoveAt(i);
}
}
private void fields_X_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string name = (string)this.fields_X.SelectedItem;
if (this.fields_X.SelectedIndex == -1)
{
this.X_Index = -1;
this.AnalyzeX.Visibility = System.Windows.Visibility.Hidden;
}
else
{
this.X_Index = this.FieldsToID[name];
this.AnalyzeX.Visibility = System.Windows.Visibility.Visible;
}
if (this.Y_Index == -1 || this.X_Index == -1)
{
this.Imported.Items.Clear();
this.Selected.Items.Clear();
this.Selected.IsEnabled = false;
this.Imported.IsEnabled = false;
return;
}
if (this.Y_Index == this.X_Index)
{
MessageBox.Show("The fields for X and Y cannot be the same!\nTo Continue make Separate selections...");
this.Imported.Items.Clear();
this.Selected.Items.Clear();
this.Selected.IsEnabled = false;
this.Imported.IsEnabled = false;
return;
}
if (this.Y_Index != -1 && this.X_Index != -1)
{
this.Selected.Items.Clear();
this.Imported.Items.Clear();
for (int i = 0; i < this.Names.Length; i++)
{
if (i != this.X_Index && i != this.Y_Index)
{
this.Imported.Items.Add(this.Names[i]);
}
}
this.Imported.IsEnabled = true;
this.Selected.IsEnabled = true;
}
}
private void AnalyzeX_Click(object sender, RoutedEventArgs e)
{
var sortedInput = ParseCSV.GetRange(this.importedData, this.X_Index);
double average_space = (sortedInput[sortedInput.Length - 1] - sortedInput[0]) / (sortedInput.Length - 1);
double spacingVariance = 0;
for (int i = 0; i < sortedInput.Length - 1; i++)
{
double space = sortedInput[i + 1] - sortedInput[i];
space -= average_space;
spacingVariance += space * space;
}
spacingVariance /= (sortedInput.Length - 1);
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("Field Name:\t\t{0}", this.IDToFields[this.X_Index]));
sb.AppendLine(string.Format("Field Index:\t\t{0}", this.X_Index.ToString()));
sb.AppendLine(string.Format("Number of X Spaces:\t{0}", sortedInput.Length.ToString()));
sb.AppendLine(string.Format("Average of X Space:\t{0}", average_space.ToString()));
sb.AppendLine(string.Format("Variance of X Space:\t{0}", Math.Sqrt(spacingVariance).ToString()));
sb.AppendLine("Input Range: ");
sb.AppendLine(string.Format("\tMin:\t{0}", sortedInput[0].ToString()));
sb.AppendLine(string.Format("\tMax:\t{0}", sortedInput[sortedInput.Length - 1].ToString()));
sb.AppendLine("Output Range: ");
sb.AppendLine(string.Format("\tMin:\t{0}", this.cellularFloor.Origin.U.ToString()));
sb.AppendLine(string.Format("\tMax:\t{0}", this.cellularFloor.TopRight.U.ToString()));
MessageBox.Show(sb.ToString(), "Fields Data Description");
sb.Clear();
sb = null;
sortedInput = null;
}
private void fields_Y_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string name = (string)this.fields_Y.SelectedItem;
if (this.fields_Y.SelectedIndex == -1)
{
this.Y_Index = -1;
this.AnalyzeY.Visibility = System.Windows.Visibility.Hidden;
}
else
{
this.Y_Index = this.FieldsToID[name];
this.AnalyzeY.Visibility = System.Windows.Visibility.Visible;
}
if (this.Y_Index == -1 || this.X_Index == -1)
{
this.Imported.Items.Clear();
this.Selected.Items.Clear();
this.Selected.IsEnabled = false;
this.Imported.IsEnabled = false;
return;
}
if (this.Y_Index == this.X_Index)
{
MessageBox.Show("The fields for X and Y cannot be the same!\nTo Continue make Separate selections...");
this.Imported.Items.Clear();
this.Selected.Items.Clear();
this.Selected.IsEnabled = false;
this.Imported.IsEnabled = false;
return;
}
if (this.Y_Index != -1 && this.X_Index != -1)
{
this.Selected.Items.Clear();
this.Imported.Items.Clear();
for (int i = 0; i < this.Names.Length; i++)
{
if (i != this.X_Index && i != this.Y_Index)
{
this.Imported.Items.Add(this.Names[i]);
}
}
this.Selected.IsEnabled = true;
this.Imported.IsEnabled = true;
}
}
private void AnalyzeY_Click(object sender, RoutedEventArgs e)
{
var sortedInput = ParseCSV.GetRange(this.importedData, this.Y_Index);
double average_space = (sortedInput[sortedInput.Length - 1] - sortedInput[0]) / (sortedInput.Length - 1);
double spacingVariance = 0;
for (int i = 0; i < sortedInput.Length - 1; i++)
{
double space = sortedInput[i + 1] - sortedInput[i];
space -= average_space;
spacingVariance += space * space;
}
spacingVariance /= (sortedInput.Length - 1);
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("Field Name:\t\t{0}", this.IDToFields[this.Y_Index]));
sb.AppendLine(string.Format("Field Index:\t\t{0}", this.Y_Index.ToString()));
sb.AppendLine(string.Format("Number of Y Spaces:\t{0}", sortedInput.Length.ToString()));
sb.AppendLine(string.Format("Average of Y Space:\t{0}", average_space.ToString()));
sb.AppendLine(string.Format("Variance of Y Space:\t{0}", Math.Sqrt(spacingVariance).ToString()));
sb.AppendLine("Range: ");
sb.AppendLine(string.Format("\tMin:\t{0}", sortedInput[0].ToString()));
sb.AppendLine(string.Format("\tMax:\t{0}", sortedInput[sortedInput.Length - 1].ToString()));
sb.AppendLine("Output Range: ");
sb.AppendLine(string.Format("\tMin:\t{0}", this.cellularFloor.Origin.V.ToString()));
sb.AppendLine(string.Format("\tMax:\t{0}", this.cellularFloor.TopRight.V.ToString()));
MessageBox.Show(sb.ToString(), "Fields Data Description");
sb.Clear();
sb = null;
sortedInput = null;
}
private void RemoveAll_Click(object sender, RoutedEventArgs e)
{
if (this.Selected.IsEnabled)
{
foreach (var item in this.Selected.Items)
{
string s = (string)item;
this.Imported.Items.Add(s);
}
this.Selected.Items.Clear();
}
}
private void AddAll_Click(object sender, RoutedEventArgs e)
{
if (this.Selected.IsEnabled)
{
foreach (var item in this.Imported.Items)
{
string s = (string)item;
this.Selected.Items.Add(s);
}
this.Imported.Items.Clear();
}
}
private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
System.Diagnostics.Process.Start("https://en.wikipedia.org/wiki/Bilinear_interpolation");
}
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
this.Cursor = Cursors.Hand;
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
this.Cursor = Cursors.Arrow;
}
}
}
| |
// 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 TestNotZAndNotCSByte()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCSByte();
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 BooleanTwoComparisonOpTest__TestNotZAndNotCSByte
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int Op2ElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private BooleanTwoComparisonOpTest__DataTable<SByte, SByte> _dataTable;
static BooleanTwoComparisonOpTest__TestNotZAndNotCSByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestNotZAndNotCSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<SByte, SByte>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestNotZAndNotC(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCSByte();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, bool result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Threading;
using System.IO;
using System.Data;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using WebsitePanel.Providers;
using OS = WebsitePanel.Providers.OS;
using WebsitePanel.Providers.OS;
using WebsitePanel.Providers.Web;
namespace WebsitePanel.EnterpriseServer
{
public class FilesController
{
public static SystemSettings GetFileManagerSettings()
{
return SystemController.GetSystemSettingsInternal(SystemSettings.FILEMANAGER_SETTINGS, false);
}
public static OS.OperatingSystem GetOS(int packageId)
{
int sid = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
if (sid <= 0)
return null;
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, sid);
return os;
}
public static string GetHomeFolder(int packageId)
{
// check context
string key = "HomeFolder" + packageId.ToString();
if (HttpContext.Current != null && HttpContext.Current.Items[key] != null)
return (string)HttpContext.Current.Items[key];
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(packageId, typeof(HomeFolder));
string path = (items.Count > 0) ? items[0].Name : null;
// place to context
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = path;
return path;
}
public static string GetFullPackagePath(int packageId, string path)
{
string homeFolder = GetHomeFolder(packageId);
string correctedPath = CorrectRelativePath(path);
return Path.Combine(homeFolder, correctedPath);
}
public static string GetFullUncPackagePath(int packageId, int serviceId, string path)
{
return ConvertToUncPath(serviceId, GetFullPackagePath(packageId, path));
}
public static string GetVirtualPackagePath(int packageId, string fullPath)
{
if (String.IsNullOrEmpty(fullPath))
return fullPath;
// check for UNC
int signIdx = fullPath.IndexOf("$");
if (signIdx > -1)
{
fullPath = fullPath.Substring(signIdx - 1).Replace("$", ":");
}
string homeFolder = GetHomeFolder(packageId);
string path = "\\";
if(fullPath.Length >= homeFolder.Length)
path = fullPath.Substring(homeFolder.Length);
if (path == "")
path = "\\";
return path;
}
public static string CorrectRelativePath(string relativePath)
{
// clean path
string correctedPath = Regex.Replace(relativePath.Replace("/", "\\"),
@"\.\\|\.\.|\\\\|\?|\:|\""|\<|\>|\||%|\$", "");
if (correctedPath.StartsWith("\\"))
correctedPath = correctedPath.Substring(1);
return correctedPath;
}
public static List<SystemFile> GetFiles(int packageId, string path, bool includeFiles)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
List<SystemFile> filteredFiles = new List<SystemFile>();
SystemFile[] files = os.GetFiles(fullPath);
foreach (SystemFile file in files)
{
if (file.IsDirectory || includeFiles)
filteredFiles.Add(file);
}
return filteredFiles;
}
public static List<SystemFile> GetFilesByMask(int packageId, string path, string filesMask)
{
return null;
}
public static byte[] GetFileBinaryContent(int packageId, string path)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// create file
return os.GetFileBinaryContent(fullPath);
}
public static byte[] GetFileBinaryContentUsingEncoding(int packageId, string path, string encoding)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// create file
return os.GetFileBinaryContentUsingEncoding(fullPath, encoding);
}
public static int UpdateFileBinaryContent(int packageId, string path, byte[] content)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "UPDATE_BINARY_CONTENT", path, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// create file
os.UpdateFileBinaryContent(fullPath, content);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int UpdateFileBinaryContentUsingEncoding(int packageId, string path, byte[] content, string encoding)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "UPDATE_BINARY_CONTENT", path, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// create file
os.UpdateFileBinaryContentUsingEncoding(fullPath, content, encoding);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static byte[] GetFileBinaryChunk(int packageId, string path, int offset, int length)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
return os.GetFileBinaryChunk(fullPath, offset, length);
}
public static int AppendFileBinaryChunk(int packageId, string path, byte[] chunk)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
os.AppendFileBinaryContent(fullPath, chunk);
return 0;
}
public static int DeleteFiles(int packageId, string[] files)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// place log record
TaskManager.StartTask("FILES", "DELETE_FILES", packageId);
if (files != null)
{
foreach (string file in files)
TaskManager.Write(file);
}
try
{
OS.OperatingSystem os = GetOS(packageId);
for (int i = 0; i < files.Length; i++)
files[i] = GetFullPackagePath(packageId, files[i]);
// delete files
os.DeleteFiles(files);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int CreateFile(int packageId, string path)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "CREATE_FILE", path, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// cannot create a file with the same name as a directory
if (os.DirectoryExists(fullPath))
return BusinessErrorCodes.ERROR_FILE_CREATE_FILE_WITH_DIR_NAME;
// create file
os.CreateFile(fullPath);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static bool FileExists(int packageId, string path)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
return os.FileExists(fullPath);
}
public static bool DirectoryExists(int packageId, string path)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
return os.DirectoryExists(fullPath);
}
public static int CreateFolder(int packageId, string path)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "CREATE_FOLDER", path, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// create folder
os.CreateDirectory(fullPath);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int CopyFiles(int packageId, string[] files, string destFolder)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// check dest folder exists
if (!DirectoryExists(packageId, destFolder)) return BusinessErrorCodes.ERROR_FILE_DEST_FOLDER_NONEXISTENT;
// place log record
TaskManager.StartTask("FILES", "COPY_FILES", packageId);
TaskManager.WriteParameter("Destination folder", destFolder);
if (files != null)
{
foreach (string file in files)
TaskManager.Write(file);
}
try
{
OS.OperatingSystem os = GetOS(packageId);
string destFullFolder = GetFullPackagePath(packageId, destFolder);
for (int i = 0; i < files.Length; i++)
{
string srcFilePath = GetFullPackagePath(packageId, files[i]);
string destFilePath = Path.Combine(destFullFolder,
srcFilePath.Substring(srcFilePath.LastIndexOf("\\") + 1));
if (srcFilePath == destFilePath)
{
return BusinessErrorCodes.ERROR_FILE_COPY_TO_SELF;
}
//Check that we're not trying to copy a folder into its own subfolder
else if (destFilePath.StartsWith(srcFilePath + "\\"))
{
return BusinessErrorCodes.ERROR_FILE_COPY_TO_OWN_SUBFOLDER;
}
else
{
os.CopyFile(srcFilePath, destFilePath);
}
}
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int MoveFiles(int packageId, string[] files, string destFolder)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// check dest folder exists
if (!DirectoryExists(packageId, destFolder)) return BusinessErrorCodes.ERROR_FILE_DEST_FOLDER_NONEXISTENT;
// place log record
TaskManager.StartTask("FILES", "MOVE_FILES", packageId);
TaskManager.WriteParameter("Destination folder", destFolder);
if (files != null)
{
foreach (string file in files)
TaskManager.Write(file);
}
try
{
OS.OperatingSystem os = GetOS(packageId);
string destFullFolder = GetFullPackagePath(packageId, destFolder);
for (int i = 0; i < files.Length; i++)
{
string srcFilePath = GetFullPackagePath(packageId, files[i]);
string destFilePath = Path.Combine(destFullFolder,
srcFilePath.Substring(srcFilePath.LastIndexOf("\\") + 1));
if (srcFilePath == destFilePath)
{
return BusinessErrorCodes.ERROR_FILE_COPY_TO_SELF;
}
//Check that we're not trying to copy a folder into its own subfolder
else if (destFilePath.StartsWith(srcFilePath + "\\"))
{
return BusinessErrorCodes.ERROR_FILE_COPY_TO_OWN_SUBFOLDER;
}
else if (os.FileExists(destFilePath) || os.DirectoryExists(destFilePath))
{
return BusinessErrorCodes.ERROR_FILE_MOVE_PATH_ALREADY_EXISTS;
}
else
{
os.MoveFile(srcFilePath, destFilePath);
}
}
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int RenameFile(int packageId, string oldPath, string newPath)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// place log record
TaskManager.StartTask("FILES", "RENAME_FILE", oldPath, packageId);
TaskManager.WriteParameter("New name", newPath);
try
{
OS.OperatingSystem os = GetOS(packageId);
string oldFullPath = GetFullPackagePath(packageId, oldPath);
string destFullPath = GetFullPackagePath(packageId, newPath);
os.MoveFile(oldFullPath, destFullPath);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static string[] UnzipFiles(int packageId, string[] files)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return null;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return null;
// place log record
TaskManager.StartTask("FILES", "UNZIP_FILES", packageId);
if (files != null)
{
foreach (string file in files)
TaskManager.Write(file);
}
try
{
List<string> unzippedFiles = new List<string>();
OS.OperatingSystem os = GetOS(packageId);
for (int i = 0; i < files.Length; i++)
{
string zipFilePath = GetFullPackagePath(packageId, files[i]);
string destFolderPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf("\\"));
unzippedFiles.AddRange(os.UnzipFiles(zipFilePath, destFolderPath));
}
return unzippedFiles.ToArray();
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int ZipFiles(int packageId, string[] files, string archivePath)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "ZIP_FILES", archivePath, packageId);
if (files != null)
{
foreach (string file in files)
TaskManager.Write(file);
}
try
{
OS.OperatingSystem os = GetOS(packageId);
string zipFilePath = GetFullPackagePath(packageId, archivePath);
List<string> archFiles = new List<string>();
string rootFolder = "";
foreach (string file in files)
{
string archFile = GetFullPackagePath(packageId, file);
int idx = archFile.LastIndexOf("\\");
rootFolder = archFile.Substring(0, idx);
archFiles.Add(archFile.Substring(idx + 1));
}
os.ZipFiles(zipFilePath, rootFolder, archFiles.ToArray());
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int ZipRemoteFiles(int packageId, string rootFolder, string[] files, string archivePath)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "ZIP_FILES", archivePath, packageId);
if (files != null)
{
foreach (string file in files)
TaskManager.Write(file);
}
try
{
OS.OperatingSystem os = GetOS(packageId);
string zipFilePath = GetFullPackagePath(packageId, archivePath);
List<string> archFiles = new List<string>();
string root = String.IsNullOrEmpty(rootFolder) ? "" : GetFullPackagePath(packageId, rootFolder);
foreach (string file in files)
{
string archFile = GetFullPackagePath(packageId, file);
if (!String.IsNullOrEmpty(rootFolder))
{
archFiles.Add(archFile.Substring(root.Length + 1));
}
else
{
int idx = archFile.LastIndexOf("\\");
root = archFile.Substring(0, idx);
archFiles.Add(archFile.Substring(idx + 1));
}
}
os.ZipFiles(zipFilePath, root, archFiles.ToArray());
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int CreateAccessDatabase(int packageId, string dbPath)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "CREATE_ACCESS_DATABASE", dbPath, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, dbPath);
os.CreateAccessDatabase(fullPath);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int CalculatePackageDiskspace(int packageId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// place log record
TaskManager.StartTask("SPACE", "CALCULATE_DISKSPACE", packageId);
try
{
// create thread parameters
ThreadStartParameters prms = new ThreadStartParameters();
prms.UserId = SecurityContext.User.UserId;
prms.Parameters = new object[] { packageId };
Thread t = new Thread(new ParameterizedThreadStart(CalculatePackageDiskspaceAsync));
t.Start(prms);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
private static void CalculatePackageDiskspaceAsync(object objPrms)
{
ThreadStartParameters prms = (ThreadStartParameters)objPrms;
// impersonate thread
SecurityContext.SetThreadPrincipal(prms.UserId);
int packageId = (int)prms.Parameters[0];
try
{
// calculate
CalculatePackagesDiskspaceTask calc = new CalculatePackagesDiskspaceTask();
calc.CalculatePackage(packageId);
}
catch (Exception ex)
{
// write to audit log
TaskManager.WriteError(ex);
}
}
public static UserPermission[] GetFilePermissions(int packageId, string path)
{
try
{
// get all accounts
UserPermission[] users = GetAvailableSecurityAccounts(packageId);
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// get users OU defined on web server
string usersOU = WebServerController.GetWebUsersOU(packageId);
users = os.GetGroupNtfsPermissions(fullPath, users, usersOU);
return users;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
}
public static int SetFilePermissions(int packageId, string path, UserPermission[] users, bool resetChildPermissions)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// place log record
TaskManager.StartTask("FILES", "SET_PERMISSIONS", path, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// get users OU defined on web server
string usersOU = WebServerController.GetWebUsersOU(packageId);
os.GrantGroupNtfsPermissions(fullPath, users, usersOU, resetChildPermissions);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
// Synchronizing
public static FolderGraph GetFolderGraph(int packageId, string path)
{
OS.OperatingSystem os = GetOS(packageId);
string fullPath = GetFullPackagePath(packageId, path);
// get graph
return os.GetFolderGraph(fullPath);
}
public static void ExecuteSyncActions(int packageId, FileSyncAction[] actions)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return;
OS.OperatingSystem os = GetOS(packageId);
// update actions
foreach (FileSyncAction action in actions)
{
if (!String.IsNullOrEmpty(action.SrcPath))
action.SrcPath = GetFullPackagePath(packageId, action.SrcPath);
if (!String.IsNullOrEmpty(action.DestPath))
action.DestPath = GetFullPackagePath(packageId, action.DestPath);
}
// perform sync
os.ExecuteSyncActions(actions);
}
public static string ConvertToUncPath(int serviceId, string path)
{
// load web service info
ServiceInfo svc = ServerController.GetServiceInfo(serviceId);
// load web server info
ServerInfo srv = ServerController.GetServerByIdInternal(svc.ServerId);
return "\\\\" + srv.ServerName + "\\" + path.Replace(":", "$");
}
private static UserPermission[] GetAvailableSecurityAccounts(int packageId)
{
List<UserPermission> users = new List<UserPermission>();
// all web sites
List<WebSite> sites = WebServerController.GetWebSites(packageId, false);
int webServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Web);
if (webServiceId > 0)
{
List<string> siteIds = new List<string>();
foreach (WebSite site in sites)
siteIds.Add(site.SiteId);
WebServer web = WebServerController.GetWebServer(webServiceId);
string[] siteAccounts = web.GetSitesAccounts(siteIds.ToArray());
for (int i = 0; i < sites.Count; i++)
{
UserPermission user = new UserPermission();
user.DisplayName = sites[i].Name;
user.AccountName = siteAccounts[i];
users.Add(user);
}
}
// add "network service"
UserPermission ns = new UserPermission();
ns.DisplayName = "NETWORK SERVICE";
ns.AccountName = "NETWORK SERVICE";
users.Add(ns);
return users.ToArray();
}
public static int SetFolderQuota(int packageId, string path, string driveName, string quotas)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "SET_QUOTA_ON_FOLDER", path, packageId);
try
{
// disk space quota
// This gets all the disk space allocated for a specific customer
// It includes the package Add Ons * Quatity + Hosting Plan System disk space value. //Quotas.OS_DISKSPACE
QuotaValueInfo diskSpaceQuota = PackageController.GetPackageQuota(packageId, quotas);
#region figure Quota Unit
// Quota Unit
string unit = String.Empty;
if (diskSpaceQuota.QuotaDescription.ToLower().Contains("gb"))
unit = "GB";
else if (diskSpaceQuota.QuotaDescription.ToLower().Contains("mb"))
unit = "MB";
else
unit = "KB";
#endregion
OS.OperatingSystem os = GetOS(packageId);
os.SetQuotaLimitOnFolder(path, driveName, QuotaType.Hard, diskSpaceQuota.QuotaAllocatedValue.ToString() + unit, 0, String.Empty, String.Empty);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int ApplyEnableHardQuotaFeature(int packageId)
{
if (SecurityContext.CheckAccount(DemandAccount.IsActive | DemandAccount.IsAdmin | DemandAccount.NotDemo) != 0)
throw new Exception("This method could be called by serveradmin only.");
// place log record
TaskManager.StartTask("FILES", "APPLY_ENABLEHARDQUOTAFEATURE");
try
{
// request OS service
//int osId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
//if (osId == 0)
// return -1;
//OS.OperatingSystem os = new OS.OperatingSystem();
//ServiceProviderProxy.Init(os, osId);
////Get operating system settings
// StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
// bool diskQuotaEnabled = (osSesstings["EnableHardQuota"] != null) ? bool.Parse(osSesstings["EnableHardQuota"]) : false;
//string driveName = osSesstings["LocationDrive"];
//if (!diskQuotaEnabled)
// return -1;
List<PackageInfo> allPackages = PackageController.GetPackagePackages(packageId, true);
foreach (PackageInfo childPackage in allPackages)
{
// request OS service
int osId = PackageController.GetPackageServiceId(childPackage.PackageId, ResourceGroups.Os);
if (osId == 0)
continue;
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osId);
//Get operating system settings
StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
string driveName = osSesstings["LocationDrive"];
if (String.IsNullOrEmpty(driveName))
continue;
string homeFolder = FilesController.GetHomeFolder(childPackage.PackageId);
FilesController.SetFolderQuota(childPackage.PackageId, homeFolder, driveName, Quotas.OS_DISKSPACE);
}
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return 0;
}
public static int DeleteDirectoryRecursive(int packageId, string rootPath)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FILES", "DELETE_DIRECTORY_RECURSIVE", rootPath, packageId);
try
{
OS.OperatingSystem os = GetOS(packageId);
os.DeleteDirectoryRecursive(rootPath);
return 0;
}
catch (Exception ex)
{
//Log and return a generic error rather than throwing an exception
TaskManager.WriteError(ex);
return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED;
}
finally
{
TaskManager.CompleteTask();
}
}
}
}
| |
using Signum.Engine.Linq;
using Signum.Utilities.Reflection;
using Signum.Entities.Internal;
namespace Signum.Engine.Cache;
internal class CachedTableConstructor
{
public CachedTableBase cachedTable;
public ITable table;
public ParameterExpression origin;
public AliasGenerator? aliasGenerator;
public Alias? currentAlias;
public Type tupleType;
public string? remainingJoins;
public CachedTableConstructor(CachedTableBase cachedTable, AliasGenerator? aliasGenerator)
{
this.cachedTable = cachedTable;
this.table = cachedTable.Table;
if (aliasGenerator != null)
{
this.aliasGenerator = aliasGenerator;
this.currentAlias = aliasGenerator.NextTableAlias(table.Name.Name);
}
this.tupleType = TupleReflection.TupleChainType(table.Columns.Values.Select(GetColumnType));
this.origin = Expression.Parameter(tupleType, "origin");
}
public Expression GetTupleProperty(IColumn column)
{
return TupleReflection.TupleChainProperty(origin, table.Columns.Values.IndexOf(column));
}
internal string CreatePartialInnerJoin(IColumn column)
{
return "INNER JOIN {0} {1} ON {1}.{2}=".FormatWith(table.Name.ToString(), currentAlias, column.Name.SqlEscape(Schema.Current.Settings.IsPostgres));
}
internal Type GetColumnType(IColumn column)
{
return column.Type;
}
internal Func<FieldReader, object> GetRowReader()
{
ParameterExpression reader = Expression.Parameter(typeof(FieldReader));
var tupleConstructor = TupleReflection.TupleChainConstructor(
table.Columns.Values.Select((c, i) => FieldReader.GetExpression(reader, i, GetColumnType(c)))
);
return Expression.Lambda<Func<FieldReader, object>>(tupleConstructor, reader).Compile();
}
internal Func<object, PrimaryKey> GetPrimaryKeyGetter(IColumn column)
{
var access = TupleReflection.TupleChainProperty(Expression.Convert(originObject, tupleType), table.Columns.Values.IndexOf(column));
var primaryKey = NewPrimaryKey(access);
return Expression.Lambda<Func<object, PrimaryKey>>(primaryKey, originObject).Compile();
}
internal Func<object, PrimaryKey?> GetPrimaryKeyNullableGetter(IColumn column)
{
var access = TupleReflection.TupleChainProperty(Expression.Convert(originObject, tupleType), table.Columns.Values.IndexOf(column));
var primaryKey = WrapPrimaryKey(access);
return Expression.Lambda<Func<object, PrimaryKey?>>(primaryKey, originObject).Compile();
}
static ConstructorInfo ciPrimaryKey = ReflectionTools.GetConstuctorInfo(() => new PrimaryKey(1));
internal static Expression NewPrimaryKey(Expression expression)
{
return Expression.New(ciPrimaryKey, Expression.Convert(expression, typeof(IComparable)));
}
static GenericInvoker<Func<ICacheLogicController, AliasGenerator?, string, string?, CachedTableBase>> ciCachedTable =
new((controller, aliasGenerator, lastPartialJoin, remainingJoins) =>
new CachedTable<Entity>(controller, aliasGenerator, lastPartialJoin, remainingJoins));
static GenericInvoker<Func<ICacheLogicController, AliasGenerator, string, string?, CachedTableBase>> ciCachedSemiTable =
new((controller, aliasGenerator, lastPartialJoin, remainingJoins) =>
new CachedLiteTable<Entity>(controller, aliasGenerator, lastPartialJoin, remainingJoins));
static GenericInvoker<Func<ICacheLogicController, TableMList, AliasGenerator?, string, string?, CachedTableBase>> ciCachedTableMList =
new((controller, relationalTable, aliasGenerator, lastPartialJoin, remainingJoins) =>
new CachedTableMList<Entity>(controller, relationalTable, aliasGenerator, lastPartialJoin, remainingJoins));
static Expression NullId = Expression.Constant(null, typeof(PrimaryKey?));
public Expression MaterializeField(Field field)
{
if (field is FieldValue)
{
var value = GetTupleProperty((IColumn)field);
return value.Type == field.FieldType ? value : Expression.Convert(value, field.FieldType);
}
if (field is FieldEnum)
return Expression.Convert(GetTupleProperty((IColumn)field), field.FieldType);
if (field is IFieldReference fr)
{
var nullRef = Expression.Constant(null, field.FieldType);
bool isLite = fr.IsLite;
if (field is FieldReference)
{
IColumn column = (IColumn)field;
return GetEntity(isLite, column, field.FieldType.CleanType());
}
if (field is FieldImplementedBy ib)
{
var call = ib.ImplementationColumns.Aggregate((Expression)nullRef, (acum, kvp) =>
{
IColumn column = (IColumn)kvp.Value;
Expression entity = GetEntity(isLite, column, kvp.Key);
return Expression.Condition(Expression.NotEqual(WrapPrimaryKey(GetTupleProperty(column)), NullId),
Expression.Convert(entity, field.FieldType),
acum);
});
return call;
}
if (field is FieldImplementedByAll iba)
{
Expression id = GetTupleProperty(iba.Column);
Expression typeId = GetTupleProperty(iba.ColumnType);
if (isLite)
{
var liteCreate = Expression.Call(miGetIBALite.MakeGenericMethod(field.FieldType.CleanType()),
Expression.Constant(Schema.Current),
NewPrimaryKey(typeId.UnNullify()),
id.UnNullify());
var liteRequest = Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(field.FieldType)!), liteCreate);
return Expression.Condition(Expression.NotEqual(WrapPrimaryKey(id), NullId), liteRequest, nullRef);
}
else
{
return Expression.Call(retriever, miRequestIBA.MakeGenericMethod(field.FieldType), typeId, id);
}
}
}
if (field is FieldEmbedded fe)
{
var bindings = new List<Expression>();
var embParam = Expression.Parameter(fe.FieldType);
bindings.Add(Expression.Assign(embParam, Expression.New(fe.FieldType)));
bindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(embParam.Type), embParam));
foreach (var f in fe.EmbeddedFields.Values)
{
Expression value = MaterializeField(f.Field);
var assigment = Expression.Assign(Expression.Field(embParam, f.FieldInfo), value);
bindings.Add(assigment);
}
if (fe.Mixins != null)
{
foreach (var mixin in fe.Mixins.Values)
{
ParameterExpression mixParam = Expression.Parameter(mixin.FieldType);
var mixBlock = MaterializeMixin(embParam, mixin, mixParam);
bindings.Add(mixBlock);
}
}
bindings.Add(embParam);
Expression block = Expression.Block(new[] { embParam }, bindings);
if (fe.HasValue == null)
return block;
return Expression.Condition(
Expression.Equal(GetTupleProperty(fe.HasValue), Expression.Constant(true)),
block,
Expression.Constant(null, field.FieldType));
}
if (field is FieldMList mListField)
{
var idColumn = table.Columns.Values.OfType<FieldPrimaryKey>().First();
string lastPartialJoin = CreatePartialInnerJoin(idColumn);
Type elementType = field.FieldType.ElementType()!;
CachedTableBase ctb = ciCachedTableMList.GetInvoker(elementType)(cachedTable.controller, mListField.TableMList, aliasGenerator, lastPartialJoin, remainingJoins);
if (cachedTable.subTables == null)
cachedTable.subTables = new List<CachedTableBase>();
cachedTable.subTables.Add(ctb);
return Expression.Call(Expression.Constant(ctb), ctb.GetType().GetMethod(nameof(CachedTableMList<int>.GetMList))!, NewPrimaryKey(GetTupleProperty(idColumn)), retriever);
}
throw new InvalidOperationException("Unexpected {0}".FormatWith(field.GetType().Name));
}
private Expression GetEntity(bool isLite, IColumn column, Type type)
{
Expression id = GetTupleProperty(column);
if (isLite)
{
Expression lite;
switch (CacheLogic.GetCacheType(type))
{
case CacheType.Cached:
{
lite = Expression.Call(retriever, miRequestLite.MakeGenericMethod(type),
Lite.NewExpression(type, NewPrimaryKey(id.UnNullify()), Expression.Constant(null, typeof(string))));
lite = Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(typeof(LiteImp)), lite.TryConvert(typeof(LiteImp))).TryConvert(lite.Type);
break;
}
case CacheType.Semi:
{
string lastPartialJoin = CreatePartialInnerJoin(column);
CachedTableBase ctb = ciCachedSemiTable.GetInvoker(type)(cachedTable.controller, aliasGenerator!, lastPartialJoin, remainingJoins);
if (cachedTable.subTables == null)
cachedTable.subTables = new List<CachedTableBase>();
cachedTable.subTables.Add(ctb);
ctb.ParentColumn = column;
lite = Expression.Call(Expression.Constant(ctb), ctb.GetType().GetMethod("GetLite")!, NewPrimaryKey(id.UnNullify()), retriever);
break;
}
default: throw new InvalidOperationException("{0} should be cached at this stage".FormatWith(type));
}
if (!id.Type.IsNullable())
return lite;
return Expression.Condition(Expression.Equal(id, NullId), Expression.Constant(null, Lite.Generate(type)), lite);
}
else
{
switch (CacheLogic.GetCacheType(type))
{
case CacheType.Cached: return Expression.Call(retriever, miRequest.MakeGenericMethod(type), WrapPrimaryKey(id.Nullify()));
case CacheType.Semi:
{
string lastPartialJoin = CreatePartialInnerJoin(column);
CachedTableBase ctb = ciCachedTable.GetInvoker(type)(cachedTable.controller, aliasGenerator, lastPartialJoin, remainingJoins);
if (cachedTable.subTables == null)
cachedTable.subTables = new List<CachedTableBase>();
cachedTable.subTables.Add(ctb);
ctb.ParentColumn = column;
var entity = Expression.Parameter(type);
LambdaExpression lambda = Expression.Lambda(typeof(Action<>).MakeGenericType(type),
Expression.Call(Expression.Constant(ctb), ctb.GetType().GetMethod("Complete")!, entity, retriever),
entity);
return Expression.Call(retriever, miComplete.MakeGenericMethod(type), WrapPrimaryKey(id.Nullify()), lambda);
}
default: throw new InvalidOperationException("{0} should be cached at this stage".FormatWith(type));
}
}
}
static readonly MethodInfo miWrap = ReflectionTools.GetMethodInfo(() => PrimaryKey.Wrap(1));
internal static Expression WrapPrimaryKey(Expression expression)
{
return Expression.Call(miWrap, Expression.Convert(expression, typeof(IComparable)));
}
static MethodInfo miRequestLite = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestLite<Entity>(null)).GetGenericMethodDefinition();
static MethodInfo miRequestIBA = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestIBA<Entity>(null, null)).GetGenericMethodDefinition();
static MethodInfo miRequest = ReflectionTools.GetMethodInfo((IRetriever r) => r.Request<Entity>(null)).GetGenericMethodDefinition();
static MethodInfo miComplete = ReflectionTools.GetMethodInfo((IRetriever r) => r.Complete<Entity>(0, null!)).GetGenericMethodDefinition();
static MethodInfo miModifiablePostRetrieving = ReflectionTools.GetMethodInfo((IRetriever r) => r.ModifiablePostRetrieving<EmbeddedEntity>(null)).GetGenericMethodDefinition();
internal static ParameterExpression originObject = Expression.Parameter(typeof(object), "originObject");
internal static ParameterExpression retriever = Expression.Parameter(typeof(IRetriever), "retriever");
static MethodInfo miGetIBALite = ReflectionTools.GetMethodInfo((Schema s) => GetIBALite<Entity>(null!, 1, "")).GetGenericMethodDefinition();
public static Lite<T> GetIBALite<T>(Schema schema, PrimaryKey typeId, string id) where T : Entity
{
Type type = schema.GetType(typeId);
return (Lite<T>)Lite.Create(type, PrimaryKey.Parse(id, type));
}
public static MemberExpression peModified = Expression.Property(retriever, ReflectionTools.GetPropertyInfo((IRetriever me) => me.ModifiedState));
public static ConstructorInfo ciKVPIntString = ReflectionTools.GetConstuctorInfo(() => new KeyValuePair<PrimaryKey, string>(1, ""));
public static Action<IRetriever, Modifiable> resetModifiedAction;
static CachedTableConstructor()
{
ParameterExpression modif = Expression.Parameter(typeof(Modifiable));
resetModifiedAction = Expression.Lambda<Action<IRetriever, Modifiable>>(Expression.Assign(
Expression.Property(modif, ReflectionTools.GetPropertyInfo((Modifiable me) => me.Modified)),
CachedTableConstructor.peModified),
CachedTableConstructor.retriever, modif).Compile();
}
static readonly MethodInfo miMixin = ReflectionTools.GetMethodInfo((Entity i) => i.Mixin<CorruptMixin>()).GetGenericMethodDefinition();
Expression GetMixin(ParameterExpression me, Type mixinType)
{
return Expression.Call(me, miMixin.MakeGenericMethod(mixinType));
}
internal BlockExpression MaterializeEntity(ParameterExpression me, Table table)
{
List<Expression> instructions = new List<Expression>();
instructions.Add(Expression.Assign(origin, Expression.Convert(CachedTableConstructor.originObject, tupleType)));
foreach (var f in table.Fields.Values.Where(f => !(f.Field is FieldPrimaryKey)))
{
Expression value = MaterializeField(f.Field);
var assigment = Expression.Assign(Expression.Field(me, f.FieldInfo), value);
instructions.Add(assigment);
}
if (table.Mixins != null)
{
foreach (var mixin in table.Mixins.Values)
{
ParameterExpression mixParam = Expression.Parameter(mixin.FieldType);
var mixBlock = MaterializeMixin(me, mixin, mixParam);
instructions.Add(mixBlock);
}
}
var block = Expression.Block(new[] { origin }, instructions);
return block;
}
private BlockExpression MaterializeMixin(ParameterExpression me, FieldMixin mixin, ParameterExpression mixParam)
{
List<Expression> mixBindings = new List<Expression>();
mixBindings.Add(Expression.Assign(mixParam, GetMixin(me, mixin.FieldType)));
mixBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(mixin.FieldType), mixParam));
foreach (var f in mixin.Fields.Values)
{
Expression value = MaterializeField(f.Field);
var assigment = Expression.Assign(Expression.Field(mixParam, f.FieldInfo), value);
mixBindings.Add(assigment);
}
var mixBlock = Expression.Block(new[] { mixParam }, mixBindings);
return mixBlock;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace System.Security.Cryptography.Asn1
{
// ITU-T-REC.X.680-201508 sec 4.
internal enum AsnEncodingRules
{
BER,
CER,
DER,
}
// Uses a masked overlay of the tag class encoding.
// T-REC-X.690-201508 sec 8.1.2.2
internal enum TagClass : byte
{
Universal = 0,
Application = 0b0100_0000,
ContextSpecific = 0b1000_0000,
Private = 0b1100_0000,
}
// ITU-T-REC.X.680-201508 sec 8.6
internal enum UniversalTagNumber
{
EndOfContents = 0,
Boolean = 1,
Integer = 2,
BitString = 3,
OctetString = 4,
Null = 5,
ObjectIdentifier = 6,
ObjectDescriptor = 7,
External = 8,
InstanceOf = External,
Real = 9,
Enumerated = 10,
Embedded = 11,
UTF8String = 12,
RelativeObjectIdentifier = 13,
Time = 14,
// 15 is reserved
Sequence = 16,
SequenceOf = Sequence,
Set = 17,
SetOf = Set,
NumericString = 18,
PrintableString = 19,
TeletexString = 20,
T61String = TeletexString,
VideotexString = 21,
IA5String = 22,
UtcTime = 23,
GeneralizedTime = 24,
GraphicString = 25,
VisibleString = 26,
ISO646String = VisibleString,
GeneralString = 27,
UniversalString = 28,
UnrestrictedCharacterString = 29,
BMPString = 30,
Date = 31,
TimeOfDay = 32,
DateTime = 33,
Duration = 34,
ObjectIdentifierIRI = 35,
RelativeObjectIdentifierIRI = 36,
}
// Represents a BER-family encoded tag.
// T-REC-X.690-201508 sec 8.1.2
internal struct Asn1Tag : IEquatable<Asn1Tag>
{
private const byte ClassMask = 0b1100_0000;
private const byte ConstructedMask = 0b0010_0000;
private const byte ControlMask = ClassMask | ConstructedMask;
private const byte TagNumberMask = 0b0001_1111;
internal static readonly Asn1Tag EndOfContents = new Asn1Tag(0, (int)UniversalTagNumber.EndOfContents);
internal static readonly Asn1Tag Boolean = new Asn1Tag(0, (int)UniversalTagNumber.Boolean);
internal static readonly Asn1Tag Integer = new Asn1Tag(0, (int)UniversalTagNumber.Integer);
internal static readonly Asn1Tag PrimitiveBitString = new Asn1Tag(0, (int)UniversalTagNumber.BitString);
internal static readonly Asn1Tag ConstructedBitString = new Asn1Tag(ConstructedMask, (int)UniversalTagNumber.BitString);
internal static readonly Asn1Tag PrimitiveOctetString = new Asn1Tag(0, (int)UniversalTagNumber.OctetString);
internal static readonly Asn1Tag ConstructedOctetString = new Asn1Tag(ConstructedMask, (int)UniversalTagNumber.OctetString);
internal static readonly Asn1Tag Null = new Asn1Tag(0, (int)UniversalTagNumber.Null);
internal static readonly Asn1Tag ObjectIdentifier = new Asn1Tag(0, (int)UniversalTagNumber.ObjectIdentifier);
internal static readonly Asn1Tag Enumerated = new Asn1Tag(0, (int)UniversalTagNumber.Enumerated);
internal static readonly Asn1Tag Sequence = new Asn1Tag(ConstructedMask, (int)UniversalTagNumber.Sequence);
internal static readonly Asn1Tag SetOf = new Asn1Tag(ConstructedMask, (int)UniversalTagNumber.SetOf);
internal static readonly Asn1Tag UtcTime = new Asn1Tag(0, (int)UniversalTagNumber.UtcTime);
internal static readonly Asn1Tag GeneralizedTime = new Asn1Tag(0, (int)UniversalTagNumber.GeneralizedTime);
private readonly byte _controlFlags;
private readonly int _tagValue;
public TagClass TagClass => (TagClass)(_controlFlags & ClassMask);
public bool IsConstructed => (_controlFlags & ConstructedMask) != 0;
public int TagValue => _tagValue;
private Asn1Tag(byte controlFlags, int tagValue)
{
_controlFlags = (byte)(controlFlags & ControlMask);
_tagValue = tagValue;
}
public Asn1Tag(UniversalTagNumber universalTagNumber, bool isConstructed = false)
: this(isConstructed ? ConstructedMask : (byte)0, (int)universalTagNumber)
{
// T-REC-X.680-201508 sec 8.6 (Table 1)
const UniversalTagNumber ReservedIndex = (UniversalTagNumber)15;
if (universalTagNumber < UniversalTagNumber.EndOfContents ||
universalTagNumber > UniversalTagNumber.RelativeObjectIdentifierIRI ||
universalTagNumber == ReservedIndex)
{
throw new ArgumentOutOfRangeException(nameof(universalTagNumber));
}
}
public Asn1Tag(TagClass tagClass, int tagValue, bool isConstructed = false)
: this((byte)((byte)tagClass | (isConstructed ? ConstructedMask : 0)), tagValue)
{
if (tagClass < TagClass.Universal || tagClass > TagClass.Private)
{
throw new ArgumentOutOfRangeException(nameof(tagClass));
}
if (tagValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(tagValue));
}
}
public Asn1Tag AsConstructed()
{
return new Asn1Tag((byte)(_controlFlags | ConstructedMask), _tagValue);
}
public Asn1Tag AsPrimitive()
{
return new Asn1Tag((byte)(_controlFlags & ~ConstructedMask), _tagValue);
}
public static bool TryParse(ReadOnlySpan<byte> source, out Asn1Tag tag, out int bytesRead)
{
tag = default(Asn1Tag);
bytesRead = 0;
if (source.IsEmpty)
{
return false;
}
byte first = source[bytesRead];
bytesRead++;
uint tagValue = (uint)(first & TagNumberMask);
if (tagValue == TagNumberMask)
{
// Multi-byte encoding
// T-REC-X.690-201508 sec 8.1.2.4
const byte ContinuationFlag = 0x80;
const byte ValueMask = ContinuationFlag - 1;
tagValue = 0;
byte current;
do
{
if (source.Length <= bytesRead)
{
bytesRead = 0;
return false;
}
current = source[bytesRead];
byte currentValue = (byte)(current & ValueMask);
bytesRead++;
// If TooBigToShift is shifted left 7, the content bit shifts out.
// So any value greater than or equal to this cannot be shifted without loss.
const int TooBigToShift = 0b00000010_00000000_00000000_00000000;
if (tagValue >= TooBigToShift)
{
bytesRead = 0;
return false;
}
tagValue <<= 7;
tagValue |= currentValue;
// The first byte cannot have the value 0 (T-REC-X.690-201508 sec 8.1.2.4.2.c)
if (tagValue == 0)
{
bytesRead = 0;
return false;
}
}
while ((current & ContinuationFlag) == ContinuationFlag);
// This encoding is only valid for tag values greater than 30.
// (T-REC-X.690-201508 sec 8.1.2.3, 8.1.2.4)
if (tagValue <= 30)
{
bytesRead = 0;
return false;
}
// There's not really any ambiguity, but prevent negative numbers from showing up.
if (tagValue > int.MaxValue)
{
bytesRead = 0;
return false;
}
}
Debug.Assert(bytesRead > 0);
tag = new Asn1Tag(first, (int)tagValue);
return true;
}
public int CalculateEncodedSize()
{
const int SevenBits = 0b0111_1111;
const int FourteenBits = 0b0011_1111_1111_1111;
const int TwentyOneBits = 0b0001_1111_1111_1111_1111_1111;
const int TwentyEightBits = 0b0000_1111_1111_1111_1111_1111_1111_1111;
if (TagValue < TagNumberMask)
return 1;
if (TagValue <= SevenBits)
return 2;
if (TagValue <= FourteenBits)
return 3;
if (TagValue <= TwentyOneBits)
return 4;
if (TagValue <= TwentyEightBits)
return 5;
return 6;
}
public bool TryWrite(Span<byte> destination, out int bytesWritten)
{
int spaceRequired = CalculateEncodedSize();
if (destination.Length < spaceRequired)
{
bytesWritten = 0;
return false;
}
if (spaceRequired == 1)
{
byte value = (byte)(_controlFlags | TagValue);
destination[0] = value;
bytesWritten = 1;
return true;
}
byte firstByte = (byte)(_controlFlags | TagNumberMask);
destination[0] = firstByte;
int remaining = TagValue;
int idx = spaceRequired - 1;
while (remaining > 0)
{
int segment = remaining & 0x7F;
// The last byte doesn't get the marker, which we write first.
if (remaining != TagValue)
{
segment |= 0x80;
}
Debug.Assert(segment <= byte.MaxValue);
destination[idx] = (byte)segment;
remaining >>= 7;
idx--;
}
Debug.Assert(idx == 0);
bytesWritten = spaceRequired;
return true;
}
public bool Equals(Asn1Tag other)
{
return _controlFlags == other._controlFlags && _tagValue == other._tagValue;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Asn1Tag && Equals((Asn1Tag)obj);
}
public override int GetHashCode()
{
// Most TagValue values will be in the 0-30 range,
// the GetHashCode value only has collisions when TagValue is
// between 2^29 and uint.MaxValue
return (_controlFlags << 24) ^ _tagValue;
}
public static bool operator ==(Asn1Tag left, Asn1Tag right)
{
return left.Equals(right);
}
public static bool operator !=(Asn1Tag left, Asn1Tag right)
{
return !left.Equals(right);
}
public override string ToString()
{
const string ConstructedPrefix = "Constructed ";
string classAndValue;
if (TagClass == TagClass.Universal)
{
classAndValue = ((UniversalTagNumber)TagValue).ToString();
}
else
{
classAndValue = TagClass + "-" + TagValue;
}
if (IsConstructed)
{
return ConstructedPrefix + classAndValue;
}
return classAndValue;
}
}
internal static class AsnCharacterStringEncodings
{
private static readonly Text.Encoding s_utf8Encoding = new UTF8Encoding(false, throwOnInvalidBytes: true);
private static readonly Text.Encoding s_bmpEncoding = new BMPEncoding();
private static readonly Text.Encoding s_ia5Encoding = new IA5Encoding();
private static readonly Text.Encoding s_visibleStringEncoding = new VisibleStringEncoding();
private static readonly Text.Encoding s_printableStringEncoding = new PrintableStringEncoding();
internal static Text.Encoding GetEncoding(UniversalTagNumber encodingType)
{
switch (encodingType)
{
case UniversalTagNumber.UTF8String:
return s_utf8Encoding;
case UniversalTagNumber.PrintableString:
return s_printableStringEncoding;
case UniversalTagNumber.IA5String:
return s_ia5Encoding;
case UniversalTagNumber.VisibleString:
return s_visibleStringEncoding;
case UniversalTagNumber.BMPString:
return s_bmpEncoding;
default:
throw new ArgumentOutOfRangeException(nameof(encodingType), encodingType, null);
}
}
}
internal abstract class SpanBasedEncoding : Text.Encoding
{
protected SpanBasedEncoding()
: base(0, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback)
{
}
protected abstract int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write);
protected abstract int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write);
public override int GetByteCount(char[] chars, int index, int count)
{
return GetByteCount(new ReadOnlySpan<char>(chars, index, count));
}
public override unsafe int GetByteCount(char* chars, int count)
{
return GetByteCount(new ReadOnlySpan<char>(chars, count));
}
public override int GetByteCount(string s)
{
return GetByteCount(s.AsSpan());
}
public
#if netcoreapp
override
#endif
int GetByteCount(ReadOnlySpan<char> chars)
{
return GetBytes(chars, Span<byte>.Empty, write: false);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return GetBytes(
new ReadOnlySpan<char>(chars, charIndex, charCount),
new Span<byte>(bytes, byteIndex, bytes.Length - byteIndex),
write: true);
}
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return GetBytes(
new ReadOnlySpan<char>(chars, charCount),
new Span<byte>(bytes, byteCount),
write: true);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(new ReadOnlySpan<byte>(bytes, index, count));
}
public override unsafe int GetCharCount(byte* bytes, int count)
{
return GetCharCount(new ReadOnlySpan<byte>(bytes, count));
}
public
#if netcoreapp
override
#endif
int GetCharCount(ReadOnlySpan<byte> bytes)
{
return GetChars(bytes, Span<char>.Empty, write: false);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return GetChars(
new ReadOnlySpan<byte>(bytes, byteIndex, byteCount),
new Span<char>(chars, charIndex, chars.Length - charIndex),
write: true);
}
public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return GetChars(
new ReadOnlySpan<byte>(bytes, byteCount),
new Span<char>(chars, charCount),
write: true);
}
}
internal class IA5Encoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41, Table 8.
// ISO International Register of Coded Character Sets to be used with Escape Sequences 001
// is ASCII 0x00 - 0x1F
// ISO International Register of Coded Character Sets to be used with Escape Sequences 006
// is ASCII 0x21 - 0x7E
// Space is ASCII 0x20, delete is ASCII 0x7F.
//
// The net result is all of 7-bit ASCII
internal IA5Encoding()
: base(0x00, 0x7F)
{
}
}
internal class VisibleStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41, Table 8.
// ISO International Register of Coded Character Sets to be used with Escape Sequences 006
// is ASCII 0x21 - 0x7E
// Space is ASCII 0x20.
internal VisibleStringEncoding()
: base(0x20, 0x7E)
{
}
}
internal class PrintableStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41.4
internal PrintableStringEncoding()
: base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?")
{
}
}
internal abstract class RestrictedAsciiStringEncoding : SpanBasedEncoding
{
private readonly bool[] _isAllowed;
protected RestrictedAsciiStringEncoding(byte minCharAllowed, byte maxCharAllowed)
{
Debug.Assert(minCharAllowed <= maxCharAllowed);
Debug.Assert(maxCharAllowed <= 0x7F);
bool[] isAllowed = new bool[0x80];
for (byte charCode = minCharAllowed; charCode <= maxCharAllowed; charCode++)
{
isAllowed[charCode] = true;
}
_isAllowed = isAllowed;
}
protected RestrictedAsciiStringEncoding(IEnumerable<char> allowedChars)
{
bool[] isAllowed = new bool[0x7F];
foreach (char c in allowedChars)
{
if (c >= isAllowed.Length)
{
throw new ArgumentOutOfRangeException(nameof(allowedChars));
}
Debug.Assert(isAllowed[c] == false);
isAllowed[c] = true;
}
_isAllowed = isAllowed;
}
public override int GetMaxByteCount(int charCount)
{
return charCount;
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount;
}
protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write)
{
if (chars.IsEmpty)
{
return 0;
}
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if ((uint)c >= (uint)_isAllowed.Length || !_isAllowed[c])
{
EncoderFallback.CreateFallbackBuffer().Fallback(c, i);
Debug.Fail("Fallback should have thrown");
throw new CryptographicException();
}
if (write)
{
bytes[i] = (byte)c;
}
}
return chars.Length;
}
protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write)
{
if (bytes.IsEmpty)
{
return 0;
}
for (int i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
if ((uint)b >= (uint)_isAllowed.Length || !_isAllowed[b])
{
DecoderFallback.CreateFallbackBuffer().Fallback(
new[] { b },
i);
Debug.Fail("Fallback should have thrown");
throw new CryptographicException();
}
if (write)
{
chars[i] = (char)b;
}
}
return bytes.Length;
}
}
/// <summary>
/// Big-Endian UCS-2 encoding (the same as UTF-16BE, but disallowing surrogate pairs to leave plane 0)
/// </summary>
// T-REC-X.690-201508 sec 8.23.8 says to see ISO/IEC 10646:2003 section 13.1.
// ISO/IEC 10646:2003 sec 13.1 says each character is represented by "two octets".
// ISO/IEC 10646:2003 sec 6.3 says that when serialized as octets to use big endian.
internal class BMPEncoding : SpanBasedEncoding
{
protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write)
{
if (chars.IsEmpty)
{
return 0;
}
int writeIdx = 0;
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (char.IsSurrogate(c))
{
EncoderFallback.CreateFallbackBuffer().Fallback(c, i);
Debug.Fail("Fallback should have thrown");
throw new CryptographicException();
}
ushort val16 = c;
if (write)
{
bytes[writeIdx + 1] = (byte)val16;
bytes[writeIdx] = (byte)(val16 >> 8);
}
writeIdx += 2;
}
return writeIdx;
}
protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write)
{
if (bytes.IsEmpty)
{
return 0;
}
if (bytes.Length % 2 != 0)
{
DecoderFallback.CreateFallbackBuffer().Fallback(
bytes.Slice(bytes.Length - 1).ToArray(),
bytes.Length - 1);
Debug.Fail("Fallback should have thrown");
throw new CryptographicException();
}
int writeIdx = 0;
for (int i = 0; i < bytes.Length; i += 2)
{
int val = bytes[i] << 8 | bytes[i + 1];
char c = (char)val;
if (char.IsSurrogate(c))
{
DecoderFallback.CreateFallbackBuffer().Fallback(
bytes.Slice(i, 2).ToArray(),
i);
Debug.Fail("Fallback should have thrown");
throw new CryptographicException();
}
if (write)
{
chars[writeIdx] = c;
}
writeIdx++;
}
return writeIdx;
}
public override int GetMaxByteCount(int charCount)
{
checked
{
return charCount * 2;
}
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount / 2;
}
}
internal class SetOfValueComparer : IComparer<ReadOnlyMemory<byte>>
{
internal static SetOfValueComparer Instance { get; } = new SetOfValueComparer();
public int Compare(ReadOnlyMemory<byte> x, ReadOnlyMemory<byte> y)
{
ReadOnlySpan<byte> xSpan = x.Span;
ReadOnlySpan<byte> ySpan = y.Span;
int min = Math.Min(x.Length, y.Length);
int diff;
for (int i = 0; i < min; i++)
{
int xVal = xSpan[i];
byte yVal = ySpan[i];
diff = xVal - yVal;
if (diff != 0)
{
return diff;
}
}
// The sorting rules (T-REC-X.690-201508 sec 11.6) say that the shorter one
// counts as if it are padded with as many 0x00s on the right as required for
// comparison.
//
// But, since a shorter definite value will have already had the length bytes
// compared, it was already different. And a shorter indefinite value will
// have hit end-of-contents, making it already different.
//
// This is here because the spec says it should be, but no values are known
// which will make diff != 0.
diff = x.Length - y.Length;
if (diff != 0)
{
return diff;
}
return 0;
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.ComponentModel;
namespace Umbraco.Cms.Core.Configuration.Models
{
/// <summary>
/// Typed configuration options for global settings.
/// </summary>
[UmbracoOptions(Constants.Configuration.ConfigGlobal)]
public class GlobalSettings
{
internal const string StaticReservedPaths = "~/app_plugins/,~/install/,~/mini-profiler-resources/,~/umbraco/,"; // must end with a comma!
internal const string StaticReservedUrls = "~/.well-known,"; // must end with a comma!
internal const string StaticTimeOut = "00:20:00";
internal const string StaticDefaultUILanguage = "en-US";
internal const bool StaticHideTopLevelNodeFromPath = true;
internal const bool StaticUseHttps = false;
internal const int StaticVersionCheckPeriod = 7;
internal const string StaticUmbracoPath = "~/umbraco";
internal const string StaticIconsPath = "~/umbraco/assets/icons";
internal const string StaticUmbracoCssPath = "~/css";
internal const string StaticUmbracoScriptsPath = "~/scripts";
internal const string StaticUmbracoMediaPath = "~/media";
internal const bool StaticInstallMissingDatabase = false;
internal const bool StaticDisableElectionForSingleServer = false;
internal const string StaticNoNodesViewPath = "~/umbraco/UmbracoWebsite/NoNodes.cshtml";
internal const string StaticSqlWriteLockTimeOut = "00:00:05";
internal const bool StaticSanitizeTinyMce = false;
internal const int StaticMainDomReleaseSignalPollingInterval = 2000;
/// <summary>
/// Gets or sets a value for the reserved URLs (must end with a comma).
/// </summary>
[DefaultValue(StaticReservedUrls)]
public string ReservedUrls { get; set; } = StaticReservedUrls;
/// <summary>
/// Gets or sets a value for the reserved paths (must end with a comma).
/// </summary>
[DefaultValue(StaticReservedPaths)]
public string ReservedPaths { get; set; } = StaticReservedPaths;
/// <summary>
/// Gets or sets a value for the back-office login timeout.
/// </summary>
[DefaultValue(StaticTimeOut)]
public TimeSpan TimeOut { get; set; } = TimeSpan.Parse(StaticTimeOut);
/// <summary>
/// Gets or sets a value for the default UI language.
/// </summary>
[DefaultValue(StaticDefaultUILanguage)]
public string DefaultUILanguage { get; set; } = StaticDefaultUILanguage;
/// <summary>
/// Gets or sets a value indicating whether to hide the top level node from the path.
/// </summary>
[DefaultValue(StaticHideTopLevelNodeFromPath)]
public bool HideTopLevelNodeFromPath { get; set; } = StaticHideTopLevelNodeFromPath;
/// <summary>
/// Gets or sets a value indicating whether HTTPS should be used.
/// </summary>
[DefaultValue(StaticUseHttps)]
public bool UseHttps { get; set; } = StaticUseHttps;
/// <summary>
/// Gets or sets a value for the version check period in days.
/// </summary>
[DefaultValue(StaticVersionCheckPeriod)]
public int VersionCheckPeriod { get; set; } = StaticVersionCheckPeriod;
/// <summary>
/// Gets or sets a value for the Umbraco back-office path.
/// </summary>
[DefaultValue(StaticUmbracoPath)]
public string UmbracoPath { get; set; } = StaticUmbracoPath;
/// <summary>
/// Gets or sets a value for the Umbraco icons path.
/// </summary>
/// <remarks>
/// TODO: Umbraco cannot be hard coded here that is what UmbracoPath is for
/// so this should not be a normal get set it has to have dynamic ability to return the correct
/// path given UmbracoPath if this hasn't been explicitly set.
/// </remarks>
[DefaultValue(StaticIconsPath)]
public string IconsPath { get; set; } = StaticIconsPath;
/// <summary>
/// Gets or sets a value for the Umbraco CSS path.
/// </summary>
[DefaultValue(StaticUmbracoCssPath)]
public string UmbracoCssPath { get; set; } = StaticUmbracoCssPath;
/// <summary>
/// Gets or sets a value for the Umbraco scripts path.
/// </summary>
[DefaultValue(StaticUmbracoScriptsPath)]
public string UmbracoScriptsPath { get; set; } = StaticUmbracoScriptsPath;
/// <summary>
/// Gets or sets a value for the Umbraco media request path.
/// </summary>
[DefaultValue(StaticUmbracoMediaPath)]
public string UmbracoMediaPath { get; set; } = StaticUmbracoMediaPath;
/// <summary>
/// Gets or sets a value for the physical Umbraco media root path (falls back to <see cref="UmbracoMediaPath" /> when empty).
/// </summary>
/// <remarks>
/// If the value is a virtual path, it's resolved relative to the webroot.
/// </remarks>
public string UmbracoMediaPhysicalRootPath { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to install the database when it is missing.
/// </summary>
[DefaultValue(StaticInstallMissingDatabase)]
public bool InstallMissingDatabase { get; set; } = StaticInstallMissingDatabase;
/// <summary>
/// Gets or sets a value indicating whether to disable the election for a single server.
/// </summary>
[DefaultValue(StaticDisableElectionForSingleServer)]
public bool DisableElectionForSingleServer { get; set; } = StaticDisableElectionForSingleServer;
/// <summary>
/// Gets or sets a value for the database factory server version.
/// </summary>
public string DatabaseFactoryServerVersion { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value for the main dom lock.
/// </summary>
public string MainDomLock { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value to discriminate MainDom boundaries.
/// <para>
/// Generally the default should suffice but useful for advanced scenarios e.g. azure deployment slot based zero downtime deployments.
/// </para>
/// </summary>
public string MainDomKeyDiscriminator { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the duration (in milliseconds) for which the MainDomLock release signal polling task should sleep.
/// </summary>
/// <remarks>
/// Doesn't apply to MainDomSemaphoreLock.
/// <para>
/// The default value is 2000ms.
/// </para>
/// </remarks>
[DefaultValue(StaticMainDomReleaseSignalPollingInterval)]
public int MainDomReleaseSignalPollingInterval { get; set; } = StaticMainDomReleaseSignalPollingInterval;
/// <summary>
/// Gets or sets the telemetry ID.
/// </summary>
public string Id { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value for the path to the no content view.
/// </summary>
[DefaultValue(StaticNoNodesViewPath)]
public string NoNodesViewPath { get; set; } = StaticNoNodesViewPath;
/// <summary>
/// Gets or sets a value for the database server registrar settings.
/// </summary>
public DatabaseServerRegistrarSettings DatabaseServerRegistrar { get; set; } = new DatabaseServerRegistrarSettings();
/// <summary>
/// Gets or sets a value for the database server messenger settings.
/// </summary>
public DatabaseServerMessengerSettings DatabaseServerMessenger { get; set; } = new DatabaseServerMessengerSettings();
/// <summary>
/// Gets or sets a value for the SMTP settings.
/// </summary>
public SmtpSettings Smtp { get; set; }
/// <summary>
/// Gets a value indicating whether SMTP is configured.
/// </summary>
public bool IsSmtpServerConfigured => !string.IsNullOrWhiteSpace(Smtp?.Host);
/// <summary>
/// Gets a value indicating whether there is a physical pickup directory configured.
/// </summary>
public bool IsPickupDirectoryLocationConfigured => !string.IsNullOrWhiteSpace(Smtp?.PickupDirectoryLocation);
/// <summary>
/// Gets or sets a value indicating whether TinyMCE scripting sanitization should be applied.
/// </summary>
[DefaultValue(StaticSanitizeTinyMce)]
public bool SanitizeTinyMce { get; set; } = StaticSanitizeTinyMce;
/// <summary>
/// An int value representing the time in milliseconds to lock the database for a write operation
/// </summary>
/// <remarks>
/// The default value is 5000 milliseconds.
/// </remarks>
[DefaultValue(StaticSqlWriteLockTimeOut)]
public TimeSpan SqlWriteLockTimeOut { get; set; } = TimeSpan.Parse(StaticSqlWriteLockTimeOut);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Reflection
{
[Serializable]
internal class MemberInfoSerializationHolder : ISerializable, IObjectReference
{
#region Staitc Public Members
public static void GetSerializationInfo(SerializationInfo info, String name, RuntimeType reflectedClass, String signature, MemberTypes type)
{
GetSerializationInfo(info, name, reflectedClass, signature, null, type, null);
}
public static void GetSerializationInfo(
SerializationInfo info,
String name,
RuntimeType reflectedClass,
String signature,
String signature2,
MemberTypes type,
Type[] genericArguments)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
String assemblyName = reflectedClass.Module.Assembly.FullName;
String typeName = reflectedClass.FullName;
info.SetType(typeof(MemberInfoSerializationHolder));
info.AddValue("Name", name, typeof(String));
info.AddValue("AssemblyName", assemblyName, typeof(String));
info.AddValue("ClassName", typeName, typeof(String));
info.AddValue("Signature", signature, typeof(String));
info.AddValue("Signature2", signature2, typeof(String));
info.AddValue("MemberType", (int)type);
info.AddValue("GenericArguments", genericArguments, typeof(Type[]));
}
#endregion
#region Private Data Members
private String m_memberName;
private RuntimeType m_reflectedType;
// m_signature stores the ToString() representation of the member which is sometimes ambiguous.
// Mulitple overloads of the same methods or properties can identical ToString().
// m_signature2 stores the SerializationToString() representation which should be unique for each member.
// It is only written and used by post 4.0 CLR versions.
private String m_signature;
private String m_signature2;
private MemberTypes m_memberType;
private SerializationInfo m_info;
#endregion
#region Constructor
internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
String assemblyName = info.GetString("AssemblyName");
String typeName = info.GetString("ClassName");
if (assemblyName == null || typeName == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
Assembly assem = FormatterServices.LoadAssemblyFromString(assemblyName);
m_reflectedType = assem.GetType(typeName, true, false) as RuntimeType;
m_memberName = info.GetString("Name");
m_signature = info.GetString("Signature");
// Only v4.0 and later generates and consumes Signature2
m_signature2 = (string)info.GetValueNoThrow("Signature2", typeof(string));
m_memberType = (MemberTypes)info.GetInt32("MemberType");
m_info = info;
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method));
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
public virtual Object GetRealObject(StreamingContext context)
{
if (m_memberName == null || m_reflectedType == null || m_memberType == 0)
throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState));
BindingFlags bindingFlags =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.OptionalParamBinding;
switch (m_memberType)
{
#region case MemberTypes.Field:
case MemberTypes.Field:
{
FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[];
if (fields.Length == 0)
throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
return fields[0];
}
#endregion
#region case MemberTypes.Event:
case MemberTypes.Event:
{
EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[];
if (events.Length == 0)
throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
return events[0];
}
#endregion
#region case MemberTypes.Property:
case MemberTypes.Property:
{
PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[];
if (properties.Length == 0)
throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
if (properties.Length == 1)
return properties[0];
if (properties.Length > 1)
{
for (int i = 0; i < properties.Length; i++)
{
if (m_signature2 != null)
{
if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2))
return properties[i];
}
else
{
if ((properties[i]).ToString().Equals(m_signature))
return properties[i];
}
}
}
throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
}
#endregion
#region case MemberTypes.Constructor:
case MemberTypes.Constructor:
{
if (m_signature == null)
throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[];
if (constructors.Length == 1)
return constructors[0];
if (constructors.Length > 1)
{
for (int i = 0; i < constructors.Length; i++)
{
if (m_signature2 != null)
{
if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2))
return constructors[i];
}
else
{
if (constructors[i].ToString().Equals(m_signature))
return constructors[i];
}
}
}
throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
}
#endregion
#region case MemberTypes.Method:
case MemberTypes.Method:
{
MethodInfo methodInfo = null;
if (m_signature == null)
throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[];
if (methods.Length == 1)
methodInfo = methods[0];
else if (methods.Length > 1)
{
for (int i = 0; i < methods.Length; i++)
{
if (m_signature2 != null)
{
if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2))
{
methodInfo = methods[i];
break;
}
}
else
{
if (methods[i].ToString().Equals(m_signature))
{
methodInfo = methods[i];
break;
}
}
// Handle generic methods specially since the signature match above probably won't work (the candidate
// method info hasn't been instantiated). If our target method is generic as well we can skip this.
if (genericArguments != null && methods[i].IsGenericMethod)
{
if (methods[i].GetGenericArguments().Length == genericArguments.Length)
{
MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments);
if (m_signature2 != null)
{
if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2))
{
methodInfo = candidateMethod;
break;
}
}
else
{
if (candidateMethod.ToString().Equals(m_signature))
{
methodInfo = candidateMethod;
break;
}
}
}
}
}
}
if (methodInfo == null)
throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
if (!methodInfo.IsGenericMethodDefinition)
return methodInfo;
if (genericArguments == null)
return methodInfo;
if (genericArguments[0] == null)
return null;
return methodInfo.MakeGenericMethod(genericArguments);
}
#endregion
default:
throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
}
}
#endregion
}
}
| |
using System;
using BigMath;
using NUnit.Framework;
using Raksha.Asn1.Nist;
using Raksha.Asn1.Sec;
using Raksha.Asn1.X9;
using Raksha.Math;
using Raksha.Math.EC;
using Raksha.Security;
using Raksha.Crypto;
using Raksha.Crypto.Agreement;
using Raksha.Crypto.Generators;
using Raksha.Crypto.Parameters;
using Raksha.Crypto.Signers;
using Raksha.Utilities;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Crypto
{
/**
* ECDSA tests are taken from X9.62.
*/
[TestFixture]
public class ECTest
: SimpleTest
{
/**
* X9.62 - 1998,<br/>
* J.3.1, Page 152, ECDSA over the field Fp<br/>
* an example with 192 bit prime
*/
[Test]
public void TestECDsa192bitPrime()
{
BigInteger r = new BigInteger("3342403536405981729393488334694600415596881826869351677613");
BigInteger s = new BigInteger("5735822328888155254683894997897571951568553642892029982342");
byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("6140507067065001063065065565667405560006161556565665656654"));
SecureRandom k = FixedSecureRandom.From(kData);
FpCurve curve = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDSA",
new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
parameters);
ParametersWithRandom param = new ParametersWithRandom(priKey, k);
ECDsaSigner ecdsa = new ECDsaSigner();
ecdsa.Init(true, param);
byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
BigInteger[] sig = ecdsa.GenerateSignature(message);
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDSA",
curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
parameters);
ecdsa.Init(false, pubKey);
if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
{
Fail("verification fails");
}
}
[Test]
public void TestDecode()
{
FpCurve curve = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECPoint p = curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"));
if (!p.X.ToBigInteger().Equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16)))
{
Fail("x uncompressed incorrectly");
}
if (!p.Y.ToBigInteger().Equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16)))
{
Fail("y uncompressed incorrectly");
}
byte[] encoding = p.GetEncoded();
if (!AreEqual(encoding, Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")))
{
Fail("point compressed incorrectly");
}
}
/**
* X9.62 - 1998,<br/>
* J.3.2, Page 155, ECDSA over the field Fp<br/>
* an example with 239 bit prime
*/
[Test]
public void TestECDsa239bitPrime()
{
BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");
byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));
SecureRandom k = FixedSecureRandom.From(kData);
FpCurve curve = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDSA",
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
parameters);
ECDsaSigner ecdsa = new ECDsaSigner();
ParametersWithRandom param = new ParametersWithRandom(priKey, k);
ecdsa.Init(true, param);
byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
BigInteger[] sig = ecdsa.GenerateSignature(message);
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDSA",
curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
parameters);
ecdsa.Init(false, pubKey);
if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* X9.62 - 1998,<br/>
* J.2.1, Page 100, ECDSA over the field F2m<br/>
* an example with 191 bit binary field
*/
[Test]
public void TestECDsa191bitBinary()
{
BigInteger r = new BigInteger("87194383164871543355722284926904419997237591535066528048");
BigInteger s = new BigInteger("308992691965804947361541664549085895292153777025772063598");
byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("1542725565216523985789236956265265265235675811949404040041"));
SecureRandom k = FixedSecureRandom.From(kData);
F2mCurve curve = new F2mCurve(
191, // m
9, //k
new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16), // a
new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("0436B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D765BE73433B3F95E332932E70EA245CA2418EA0EF98018FB")), // G
new BigInteger("1569275433846670190958947355803350458831205595451630533029"), // n
BigInteger.Two); // h
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDSA",
new BigInteger("1275552191113212300012030439187146164646146646466749494799"), // d
parameters);
ECDsaSigner ecdsa = new ECDsaSigner();
ParametersWithRandom param = new ParametersWithRandom(priKey, k);
ecdsa.Init(true, param);
byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
BigInteger[] sig = ecdsa.GenerateSignature(message);
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDSA",
curve.DecodePoint(Hex.Decode("045DE37E756BD55D72E3768CB396FFEB962614DEA4CE28A2E755C0E0E02F5FB132CAF416EF85B229BBB8E1352003125BA1")), // Q
parameters);
ecdsa.Init(false, pubKey);
if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* X9.62 - 1998,<br/>
* J.2.1, Page 100, ECDSA over the field F2m<br/>
* an example with 191 bit binary field
*/
[Test]
public void TestECDsa239bitBinary()
{
BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");
byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));
SecureRandom k = FixedSecureRandom.From(kData);
F2mCurve curve = new F2mCurve(
239, // m
36, //k
new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a
new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n
BigInteger.ValueOf(4)); // h
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDSA",
new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
parameters);
ECDsaSigner ecdsa = new ECDsaSigner();
ParametersWithRandom param = new ParametersWithRandom(priKey, k);
ecdsa.Init(true, param);
byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
BigInteger[] sig = ecdsa.GenerateSignature(message);
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDSA",
curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
parameters);
ecdsa.Init(false, pubKey);
if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
{
Fail("signature fails");
}
}
// L 4.1 X9.62 2005
[Test]
public void TestECDsaP224Sha224()
{
X9ECParameters p = NistNamedCurves.GetByName("P-224");
ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d
parameters);
SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601")));
byte[] M = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79");
ECDsaSigner dsa = new ECDsaSigner();
dsa.Init(true, new ParametersWithRandom(priKey, k));
BigInteger[] sig = dsa.GenerateSignature(M);
BigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742");
BigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978");
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")), // Q
parameters);
dsa.Init(false, pubKey);
if (!dsa.VerifySignature(M, sig[0], sig[1]))
{
Fail("signature fails");
}
}
[Test]
public void TestECDsaSecP224k1Sha256()
{
X9ECParameters p = SecNamedCurves.GetByName("secp224k1");
ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("BE6F6E91FE96840A6518B56F3FE21689903A64FA729057AB872A9F51", 16), // d
parameters);
SecureRandom k = FixedSecureRandom.From(Hex.Decode("00c39beac93db21c3266084429eb9b846b787c094f23a4de66447efbb3"));
byte[] M = Hex.Decode("E5D5A7ADF73C5476FAEE93A2C76CE94DC0557DB04CDC189504779117920B896D");
ECDsaSigner dsa = new ECDsaSigner();
dsa.Init(true, new ParametersWithRandom(priKey, k));
BigInteger[] sig = dsa.GenerateSignature(M);
BigInteger r = new BigInteger("8163E5941BED41DA441B33E653C632A55A110893133351E20CE7CB75", 16);
BigInteger s = new BigInteger("D12C3FC289DDD5F6890DCE26B65792C8C50E68BF551D617D47DF15A8", 16);
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
parameters.Curve.DecodePoint(Hex.Decode("04C5C9B38D3603FCCD6994CBB9594E152B658721E483669BB42728520F484B537647EC816E58A8284D3B89DFEDB173AFDC214ECA95A836FA7C")), // Q
parameters);
dsa.Init(false, pubKey);
if (!dsa.VerifySignature(M, sig[0], sig[1]))
{
Fail("signature fails");
}
}
// L4.2 X9.62 2005
[Test]
public void TestECDsaP256Sha256()
{
X9ECParameters p = NistNamedCurves.GetByName("P-256");
ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d
parameters);
SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335")));
byte[] M = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");
ECDsaSigner dsa = new ECDsaSigner();
dsa.Init(true, new ParametersWithRandom(priKey, k));
BigInteger[] sig = dsa.GenerateSignature(M);
BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384");
BigInteger s = new BigInteger("98506158880355671805367324764306888225238061309262649376965428126566081727535");
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
parameters.Curve.DecodePoint(Hex.Decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q
parameters);
dsa.Init(false, pubKey);
if (!dsa.VerifySignature(M, sig[0], sig[1]))
{
Fail("signature fails");
}
}
[Test]
public void TestECDsaP224OneByteOver()
{
X9ECParameters p = NistNamedCurves.GetByName("P-224");
ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d
parameters);
SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601")));
byte[] M = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79FF");
ECDsaSigner dsa = new ECDsaSigner();
dsa.Init(true, new ParametersWithRandom(priKey, k));
BigInteger[] sig = dsa.GenerateSignature(M);
BigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742");
BigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978");
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")), // Q
parameters);
dsa.Init(false, pubKey);
if (!dsa.VerifySignature(M, sig[0], sig[1]))
{
Fail("signature fails");
}
}
// L4.3 X9.62 2005
[Test]
public void TestECDsaP521Sha512()
{
X9ECParameters p = NistNamedCurves.GetByName("P-521");
ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("617573726813476282316253885608633222275541026607493641741273231656161177732180358888434629562647985511298272498852936680947729040673640492310550142822667389"), // d
parameters);
SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("6806532878215503520845109818432174847616958675335397773700324097584974639728725689481598054743894544060040710846048585856076812050552869216017728862957612913")));
byte[] M = Hex.Decode("6893B64BD3A9615C39C3E62DDD269C2BAAF1D85915526083183CE14C2E883B48B193607C1ED871852C9DF9C3147B574DC1526C55DE1FE263A676346A20028A66");
ECDsaSigner dsa = new ECDsaSigner();
dsa.Init(true, new ParametersWithRandom(priKey, k));
BigInteger[] sig = dsa.GenerateSignature(M);
BigInteger r = new BigInteger("1368926195812127407956140744722257403535864168182534321188553460365652865686040549247096155740756318290773648848859639978618869784291633651685766829574104630");
BigInteger s = new BigInteger("1624754720348883715608122151214003032398685415003935734485445999065609979304811509538477657407457976246218976767156629169821116579317401249024208611945405790");
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
parameters.Curve.DecodePoint(Hex.Decode("020145E221AB9F71C5FE740D8D2B94939A09E2816E2167A7D058125A06A80C014F553E8D6764B048FB6F2B687CEC72F39738F223D4CE6AFCBFF2E34774AA5D3C342CB3")), // Q
parameters);
dsa.Init(false, pubKey);
if (!dsa.VerifySignature(M, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* General test for long digest.
*/
[Test]
public void TestECDsa239bitBinaryAndLargeDigest()
{
BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
BigInteger s = new BigInteger("144940322424411242416373536877786566515839911620497068645600824084578597");
byte[] kData = BigIntegers.AsUnsignedByteArray(
new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));
SecureRandom k = FixedSecureRandom.From(kData);
F2mCurve curve = new F2mCurve(
239, // m
36, //k
new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a
new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(
Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n
BigInteger.ValueOf(4)); // h
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDSA",
new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
parameters);
ECDsaSigner ecdsa = new ECDsaSigner();
ParametersWithRandom param = new ParametersWithRandom(priKey, k);
ecdsa.Init(true, param);
byte[] message = new BigInteger("968236873715988614170569073515315707566766479517968236873715988614170569073515315707566766479517968236873715988614170569073515315707566766479517").ToByteArray();
BigInteger[] sig = ecdsa.GenerateSignature(message);
if (!r.Equals(sig[0]))
{
Fail("r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDSA",
curve.DecodePoint(
Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
parameters);
ecdsa.Init(false, pubKey);
if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* key generation test
*/
[Test]
public void TestECDsaKeyGenTest()
{
SecureRandom random = new SecureRandom();
FpCurve curve = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECKeyPairGenerator pGen = new ECKeyPairGenerator();
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
parameters,
random);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
ECDsaSigner ecdsa = new ECDsaSigner();
ecdsa.Init(true, param);
byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
BigInteger[] sig = ecdsa.GenerateSignature(message);
ecdsa.Init(false, pair.Public);
if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* Basic Key Agreement Test
*/
[Test]
public void TestECBasicAgreementTest()
{
SecureRandom random = new SecureRandom();
FpCurve curve = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECKeyPairGenerator pGen = new ECKeyPairGenerator();
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, random);
pGen.Init(genParam);
AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair();
AsymmetricCipherKeyPair p2 = pGen.GenerateKeyPair();
//
// two way
//
IBasicAgreement e1 = new ECDHBasicAgreement();
IBasicAgreement e2 = new ECDHBasicAgreement();
e1.Init(p1.Private);
e2.Init(p2.Private);
BigInteger k1 = e1.CalculateAgreement(p2.Public);
BigInteger k2 = e2.CalculateAgreement(p1.Public);
if (!k1.Equals(k2))
{
Fail("calculated agreement test failed");
}
//
// two way
//
e1 = new ECDHCBasicAgreement();
e2 = new ECDHCBasicAgreement();
e1.Init(p1.Private);
e2.Init(p2.Private);
k1 = e1.CalculateAgreement(p2.Public);
k2 = e2.CalculateAgreement(p1.Public);
if (!k1.Equals(k2))
{
Fail("calculated agreement test failed");
}
}
[Test]
public void TestECMqvTestVector1()
{
// Test Vector from GEC-2
X9ECParameters x9 = SecNamedCurves.GetByName("secp160r1");
ECDomainParameters p = new ECDomainParameters(
x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
AsymmetricCipherKeyPair U1 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("0251B4496FECC406ED0E75A24A3C03206251419DC0")), p),
new ECPrivateKeyParameters(
new BigInteger("AA374FFC3CE144E6B073307972CB6D57B2A4E982", 16), p));
AsymmetricCipherKeyPair U2 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("03D99CE4D8BF52FA20BD21A962C6556B0F71F4CA1F")), p),
new ECPrivateKeyParameters(
new BigInteger("149EC7EA3A220A887619B3F9E5B4CA51C7D1779C", 16), p));
AsymmetricCipherKeyPair V1 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("0349B41E0E9C0369C2328739D90F63D56707C6E5BC")), p),
new ECPrivateKeyParameters(
new BigInteger("45FB58A92A17AD4B15101C66E74F277E2B460866", 16), p));
AsymmetricCipherKeyPair V2 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("02706E5D6E1F640C6E9C804E75DBC14521B1E5F3B5")), p),
new ECPrivateKeyParameters(
new BigInteger("18C13FCED9EADF884F7C595C8CB565DEFD0CB41E", 16), p));
BigInteger x = calculateAgreement(U1, U2, V1, V2);
if (x == null
|| !x.Equals(new BigInteger("5A6955CEFDB4E43255FB7FCF718611E4DF8E05AC", 16)))
{
Fail("MQV Test Vector #1 agreement failed");
}
}
[Test]
public void TestECMqvTestVector2()
{
// Test Vector from GEC-2
X9ECParameters x9 = SecNamedCurves.GetByName("sect163k1");
ECDomainParameters p = new ECDomainParameters(
x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
AsymmetricCipherKeyPair U1 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("03037D529FA37E42195F10111127FFB2BB38644806BC")), p),
new ECPrivateKeyParameters(
new BigInteger("03A41434AA99C2EF40C8495B2ED9739CB2155A1E0D", 16), p));
AsymmetricCipherKeyPair U2 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("02015198E74BC2F1E5C9A62B80248DF0D62B9ADF8429")), p),
new ECPrivateKeyParameters(
new BigInteger("032FC4C61A8211E6A7C4B8B0C03CF35F7CF20DBD52", 16), p));
AsymmetricCipherKeyPair V1 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("03072783FAAB9549002B4F13140B88132D1C75B3886C")), p),
new ECPrivateKeyParameters(
new BigInteger("57E8A78E842BF4ACD5C315AA0569DB1703541D96", 16), p));
AsymmetricCipherKeyPair V2 = new AsymmetricCipherKeyPair(
new ECPublicKeyParameters(
p.Curve.DecodePoint(Hex.Decode("03067E3AEA3510D69E8EDD19CB2A703DDC6CF5E56E32")), p),
new ECPrivateKeyParameters(
new BigInteger("02BD198B83A667A8D908EA1E6F90FD5C6D695DE94F", 16), p));
BigInteger x = calculateAgreement(U1, U2, V1, V2);
if (x == null
|| !x.Equals(new BigInteger("038359FFD30C0D5FC1E6154F483B73D43E5CF2B503", 16)))
{
Fail("MQV Test Vector #2 agreement failed");
}
}
[Test]
public void TestECMqvRandom()
{
SecureRandom random = new SecureRandom();
FpCurve curve = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECKeyPairGenerator pGen = new ECKeyPairGenerator();
pGen.Init(new ECKeyGenerationParameters(parameters, random));
// Pre-established key pairs
AsymmetricCipherKeyPair U1 = pGen.GenerateKeyPair();
AsymmetricCipherKeyPair V1 = pGen.GenerateKeyPair();
// Ephemeral key pairs
AsymmetricCipherKeyPair U2 = pGen.GenerateKeyPair();
AsymmetricCipherKeyPair V2 = pGen.GenerateKeyPair();
BigInteger x = calculateAgreement(U1, U2, V1, V2);
if (x == null)
{
Fail("MQV Test Vector (random) agreement failed");
}
}
private static BigInteger calculateAgreement(
AsymmetricCipherKeyPair U1,
AsymmetricCipherKeyPair U2,
AsymmetricCipherKeyPair V1,
AsymmetricCipherKeyPair V2)
{
ECMqvBasicAgreement u = new ECMqvBasicAgreement();
u.Init(new MqvPrivateParameters(
(ECPrivateKeyParameters)U1.Private,
(ECPrivateKeyParameters)U2.Private,
(ECPublicKeyParameters)U2.Public));
BigInteger ux = u.CalculateAgreement(new MqvPublicParameters(
(ECPublicKeyParameters)V1.Public,
(ECPublicKeyParameters)V2.Public));
ECMqvBasicAgreement v = new ECMqvBasicAgreement();
v.Init(new MqvPrivateParameters(
(ECPrivateKeyParameters)V1.Private,
(ECPrivateKeyParameters)V2.Private,
(ECPublicKeyParameters)V2.Public));
BigInteger vx = v.CalculateAgreement(new MqvPublicParameters(
(ECPublicKeyParameters)U1.Public,
(ECPublicKeyParameters)U2.Public));
if (ux.Equals(vx))
return ux;
return null;
}
public override string Name
{
get { return "EC"; }
}
public override void PerformTest()
{
TestDecode();
TestECDsa192bitPrime();
TestECDsa239bitPrime();
TestECDsa191bitBinary();
TestECDsa239bitBinary();
TestECDsaKeyGenTest();
TestECBasicAgreementTest();
TestECDsaP224Sha224();
TestECDsaP224OneByteOver();
TestECDsaP256Sha256();
TestECDsaP521Sha512();
TestECDsaSecP224k1Sha256();
TestECDsa239bitBinaryAndLargeDigest();
TestECMqvTestVector1();
TestECMqvTestVector2();
TestECMqvRandom();
}
public static void Main(
string[] args)
{
RunTest(new ECTest());
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Tests
{
public partial class Int32Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new int();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
int i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFF, int.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((int)0x80000000), int.MinValue);
}
[Theory]
[InlineData(234, 234, 0)]
[InlineData(234, int.MinValue, 1)]
[InlineData(-234, int.MinValue, 1)]
[InlineData(int.MinValue, int.MinValue, 0)]
[InlineData(234, -123, 1)]
[InlineData(234, 0, 1)]
[InlineData(234, 123, 1)]
[InlineData(234, 456, -1)]
[InlineData(234, int.MaxValue, -1)]
[InlineData(-234, int.MaxValue, -1)]
[InlineData(int.MaxValue, int.MaxValue, 0)]
[InlineData(-234, -234, 0)]
[InlineData(-234, 234, -1)]
[InlineData(-234, -432, 1)]
[InlineData(234, null, 1)]
public void CompareTo_Other_ReturnsExpected(int i, object value, int expected)
{
if (value is int intValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(intValue)));
Assert.Equal(-expected, Math.Sign(intValue.CompareTo(i)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData((long)234)]
public void CompareTo_ObjectNotInt_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => 123.CompareTo(value));
}
[Theory]
[InlineData(789, 789, true)]
[InlineData(789, -789, false)]
[InlineData(789, 0, false)]
[InlineData(0, 0, true)]
[InlineData(-789, -789, true)]
[InlineData(-789, 789, false)]
[InlineData(789, null, false)]
[InlineData(789, "789", false)]
[InlineData(789, (long)789, false)]
public static void Equals(int i1, object obj, bool expected)
{
if (obj is int)
{
int i2 = (int)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsInt32()
{
Assert.Equal(TypeCode.Int32, 1.GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
foreach (string defaultSpecifier in new[] { "G", "G\0", "\0N222", "\0", "" })
{
yield return new object[] { int.MinValue, defaultSpecifier, defaultFormat, "-2147483648" };
yield return new object[] { -4567, defaultSpecifier, defaultFormat, "-4567" };
yield return new object[] { 0, defaultSpecifier, defaultFormat, "0" };
yield return new object[] { 4567, defaultSpecifier, defaultFormat, "4567" };
yield return new object[] { int.MaxValue, defaultSpecifier, defaultFormat, "2147483647" };
}
yield return new object[] { 4567, "D", defaultFormat, "4567" };
yield return new object[] { 4567, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { 4567, "D99\09", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { -4567, "D99\09", defaultFormat, "-000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { 0x2468, "x", defaultFormat, "2468" };
yield return new object[] { -0x2468, "x", defaultFormat, "ffffdb98" };
yield return new object[] { 2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { -2468, "N", customFormat, "#2*468~00" };
yield return new object[] { 2468, "N", customFormat, "2*468~00" };
yield return new object[] { 123, "E", customFormat, "1~230000E&002" };
yield return new object[] { 123, "F", customFormat, "123~00" };
yield return new object[] { 123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(int i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
int i = 123;
Assert.Throws<FormatException>(() => i.ToString("r")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("r", null)); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("R")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("R", null)); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo()
{
PositiveSign = "|",
NegativeSign = "|"
};
NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" };
NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" };
// None
yield return new object[] { "0", NumberStyles.None, null, 0 };
yield return new object[] { "0000000000000000000000000000000000000000000000000000000000", NumberStyles.None, null, 0 };
yield return new object[] { "0000000000000000000000000000000000000000000000000000000001", NumberStyles.None, null, 1 };
yield return new object[] { "2147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "02147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "00000000000000000000000000000000000000000000000002147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "123\0\0", NumberStyles.None, null, 123 };
// All lengths decimal
foreach (bool neg in new[] { false, true })
{
string s = neg ? "-" : "";
int result = 0;
for (int i = 1; i <= 10; i++)
{
result = result * 10 + (i % 10);
s += (i % 10).ToString();
yield return new object[] { s, NumberStyles.Integer, null, neg ? result * -1 : result };
}
}
// All lengths hexadecimal
{
string s = "";
int result = 0;
for (int i = 1; i <= 8; i++)
{
result = (result * 16) + (i % 16);
s += (i % 16).ToString("X");
yield return new object[] { s, NumberStyles.HexNumber, null, result };
}
}
// HexNumber
yield return new object[] { "123", NumberStyles.HexNumber, null, 0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "12", NumberStyles.HexNumber, null, 0x12 };
yield return new object[] { "80000000", NumberStyles.HexNumber, null, int.MinValue };
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, -1 };
// Currency
NumberFormatInfo currencyFormat = new NumberFormatInfo()
{
CurrencySymbol = "$",
CurrencyGroupSeparator = "|",
NumberGroupSeparator = "/"
};
yield return new object[] { "$1|000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$ 1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$(1000)", NumberStyles.Currency, currencyFormat, -1000};
yield return new object[] { "($1000)", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "$-1000", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "-$1000", NumberStyles.Currency, currencyFormat, -1000 };
NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" };
yield return new object[] { "100", NumberStyles.Currency, emptyCurrencyFormat, 100 };
// If CurrencySymbol and Negative are the same, NegativeSign is preferred
NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo()
{
NegativeSign = "|",
CurrencySymbol = "|"
};
yield return new object[] { "|1000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1000 };
// Any
yield return new object[] { "123", NumberStyles.Any, null, 123 };
// AllowLeadingSign
yield return new object[] { "-2147483648", NumberStyles.AllowLeadingSign, null, -2147483648 };
yield return new object[] { "-123", NumberStyles.AllowLeadingSign, null, -123 };
yield return new object[] { "+0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "-0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "+123", NumberStyles.AllowLeadingSign, null, 123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "|123", NumberStyles.AllowLeadingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyNegativeFormat, 100 };
// AllowTrailingSign
yield return new object[] { "123", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123+", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123-", NumberStyles.AllowTrailingSign, null, -123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "123|", NumberStyles.AllowTrailingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyNegativeFormat, 100 };
// AllowLeadingWhite and AllowTrailingWhite
yield return new object[] { " 123", NumberStyles.AllowLeadingWhite, null, 123 };
yield return new object[] { " 123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { "123 ", NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { "123 \0\0", NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 2147483647 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 2147483647 };
yield return new object[] { " -2147483648 ", NumberStyles.Integer, null, -2147483648 };
foreach (char c in new[] { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD })
{
string cs = c.ToString();
yield return new object[] { cs + cs + "123" + cs + cs, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
}
yield return new object[] { " 0 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 0 };
yield return new object[] { " 000000000 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 0 };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "1000", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|0|0|0", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|||", NumberStyles.AllowThousands, thousandsFormat, 1 };
NumberFormatInfo integerNumberSeparatorFormat = new NumberFormatInfo() { NumberGroupSeparator = "1" };
yield return new object[] { "1111", NumberStyles.AllowThousands, integerNumberSeparatorFormat, 1111 };
// AllowExponent
yield return new object[] { "1E2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E+2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1e2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E0", NumberStyles.AllowExponent, null, 1 };
yield return new object[] { "(1E2)", NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, -100 };
yield return new object[] { "-1E2", NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, -100 };
NumberFormatInfo negativeFormat = new NumberFormatInfo() { PositiveSign = "|" };
yield return new object[] { "1E|2", NumberStyles.AllowExponent, negativeFormat, 100 };
// AllowParentheses
yield return new object[] { "123", NumberStyles.AllowParentheses, null, 123 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, -123 };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "|" };
yield return new object[] { "67|", NumberStyles.AllowDecimalPoint, decimalFormat, 67 };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, 123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "1" }, 23123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "1" }, -23123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "123" }, 123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "123" }, -123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "12312" }, 3 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "12312" }, -3 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, int expected)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.True(int.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Equal(expected, int.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.True(int.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Equal(expected, int.Parse(value, provider));
}
// Full overloads
Assert.True(int.TryParse(value, style, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, provider));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
// String is null, empty or entirely whitespace
yield return new object[] { null, NumberStyles.Integer, null, typeof(ArgumentNullException) };
yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) };
// String contains is null, empty or enitrely whitespace.
foreach (NumberStyles style in new[] { NumberStyles.Integer, NumberStyles.HexNumber, NumberStyles.Any })
{
yield return new object[] { null, style, null, typeof(ArgumentNullException) };
yield return new object[] { "", style, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", style, null, typeof(FormatException) };
yield return new object[] { " \0\0", style, null, typeof(FormatException) };
}
// Leading or trailing chars for which char.IsWhiteSpace is true but that's not valid for leading/trailing whitespace
foreach (string c in new[] { "\x0085", "\x00A0", "\x1680", "\x2000", "\x2001", "\x2002", "\x2003", "\x2004", "\x2005", "\x2006", "\x2007", "\x2008", "\x2009", "\x200A", "\x2028", "\x2029", "\x202F", "\x205F", "\x3000" })
{
yield return new object[] { c + "123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "123" + c, NumberStyles.Integer, null, typeof(FormatException) };
}
// String contains garbage
foreach (NumberStyles style in new[] { NumberStyles.Integer, NumberStyles.HexNumber, NumberStyles.Any })
{
yield return new object[] { "Garbage", style, null, typeof(FormatException) };
yield return new object[] { "g", style, null, typeof(FormatException) };
yield return new object[] { "g1", style, null, typeof(FormatException) };
yield return new object[] { "1g", style, null, typeof(FormatException) };
yield return new object[] { "123g", style, null, typeof(FormatException) };
yield return new object[] { "g123", style, null, typeof(FormatException) };
yield return new object[] { "214748364g", style, null, typeof(FormatException) };
}
// String has leading zeros
yield return new object[] { "\0\0123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "\0\0123", NumberStyles.Any, null, typeof(FormatException) };
// String has internal zeros
yield return new object[] { "1\023", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1\023", NumberStyles.Any, null, typeof(FormatException) };
// String has trailing zeros but with whitespace after
yield return new object[] { "123\0\0 ", NumberStyles.Integer, null, typeof(FormatException) };
// Integer doesn't allow hex, exponents, paretheses, currency, thousands, decimal
yield return new object[] { "abc", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1E23", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "(123)", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("C0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("N0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 678.90.ToString("F2"), NumberStyles.Integer, null, typeof(FormatException) };
// HexNumber
yield return new object[] { "0xabc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "&habc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "G1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "g1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
// None doesn't allow hex or leading or trailing whitespace
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { "123 ", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) };
// AllowLeadingSign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+-123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-+123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "- 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+ 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
// AllowTrailingSign
yield return new object[] { "123-+", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123+-", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 -", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 +", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// Parentheses has priority over CurrencySymbol and PositiveSign
NumberFormatInfo currencyNegativeParenthesesFormat = new NumberFormatInfo()
{
CurrencySymbol = "(",
PositiveSign = "))"
};
yield return new object[] { "(100))", NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingSign, currencyNegativeParenthesesFormat, typeof(FormatException) };
// AllowTrailingSign and AllowLeadingSign
yield return new object[] { "+123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "+123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// AllowLeadingSign and AllowParentheses
yield return new object[] { "-(1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
yield return new object[] { "(-1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
// AllowLeadingWhite
yield return new object[] { "1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
yield return new object[] { " 1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
// AllowTrailingWhite
yield return new object[] { " 1 ", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
yield return new object[] { " 1", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "|||1", NumberStyles.AllowThousands, null, typeof(FormatException) };
// AllowExponent
yield return new object[] { "65E", NumberStyles.AllowExponent, null, typeof(FormatException) };
yield return new object[] { "65E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E+10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E-1", NumberStyles.AllowExponent, null, typeof(OverflowException) };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "." };
yield return new object[] { "67.9", NumberStyles.AllowDecimalPoint, decimalFormat, typeof(OverflowException) };
// Parsing integers doesn't allow NaN, PositiveInfinity or NegativeInfinity
NumberFormatInfo doubleFormat = new NumberFormatInfo()
{
NaNSymbol = "NaN",
PositiveInfinitySymbol = "Infinity",
NegativeInfinitySymbol = "-Infinity"
};
yield return new object[] { "NaN", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "-Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
// Only has a leading sign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { " +", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { " -", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "+ ", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "- ", NumberStyles.Integer, null, typeof(FormatException) };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, typeof(FormatException) };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "123" }, typeof(FormatException) };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "123" }, typeof(FormatException) };
// Decimals not in range of Int32
foreach (string s in new[]
{
"2147483648", // int.MaxValue + 1
"2147483650", // 10s digit incremented above int.MaxValue
"10000000000", // extra digit after int.MaxValue
"4294967296", // uint.MaxValue + 1
"4294967300", // 100s digit incremented above uint.MaxValue
"9223372036854775808", // long.MaxValue + 1
"9223372036854775810", // 10s digit incremented above long.MaxValue
"10000000000000000000", // extra digit after long.MaxValue
"18446744073709551616", // ulong.MaxValue + 1
"18446744073709551620", // 10s digit incremented above ulong.MaxValue
"100000000000000000000", // extra digit after ulong.MaxValue
"-2147483649", // int.MinValue - 1
"-2147483650", // 10s digit decremented below int.MinValue
"-10000000000", // extra digit after int.MinValue
"-9223372036854775809", // long.MinValue - 1
"-9223372036854775810", // 10s digit decremented below long.MinValue
"-10000000000000000000", // extra digit after long.MinValue
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000", // really big
"-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000" // really small
})
{
foreach (NumberStyles styles in new[] { NumberStyles.Any, NumberStyles.Integer })
{
yield return new object[] { s, styles, null, typeof(OverflowException) };
yield return new object[] { s + " ", styles, null, typeof(OverflowException) };
yield return new object[] { s + " " + "\0\0\0", styles, null, typeof(OverflowException) };
yield return new object[] { s + "g", styles, null, typeof(FormatException) };
yield return new object[] { s + "\0g", styles, null, typeof(FormatException) };
yield return new object[] { s + " g", styles, null, typeof(FormatException) };
}
}
// Hexadecimals not in range of Int32
foreach (string s in new[]
{
"100000000", // uint.MaxValue + 1
"FFFFFFFF0", // extra digit after uint.MaxValue
"10000000000000000", // ulong.MaxValue + 1
"FFFFFFFFFFFFFFFF0", // extra digit after ulong.MaxValue
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000" // really big
})
{
yield return new object[] { s, NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + " ", NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + " " + "\0\0", NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + "g", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { s + "\0g", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { s + " g", NumberStyles.HexNumber, null, typeof(FormatException) };
}
yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) };
yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) };
yield return new object[] { "2E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.False(int.TryParse(value, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Throws(exceptionType, () => int.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.False(int.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Throws(exceptionType, () => int.Parse(value, provider));
}
// Full overloads
Assert.False(int.TryParse(value, style, provider, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value, style, provider));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
int result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => int.TryParse("1", style, null, out result));
Assert.Equal(default(int), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => int.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => int.Parse("1", style, null));
}
[Theory]
[InlineData("N")]
[InlineData("F")]
public static void ToString_N_F_EmptyNumberGroup_Success(string specifier)
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.NumberGroupSizes = new int[0];
nfi.NumberGroupSeparator = ",";
Assert.Equal("1234", 1234.ToString($"{specifier}0", nfi));
}
[Fact]
public static void ToString_P_EmptyPercentGroup_Success()
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.PercentGroupSizes = new int[0];
nfi.PercentSymbol = "%";
Assert.Equal("123400 %", 1234.ToString("P0", nfi));
}
[Fact]
public static void ToString_C_EmptyPercentGroup_Success()
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.CurrencyGroupSizes = new int[0];
nfi.CurrencySymbol = "$";
Assert.Equal("$1234", 1234.ToString("C0", nfi));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32
{
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
/// <devdoc>
/// <para>
/// Provides a
/// set of global system events to callers. This
/// class cannot be inherited.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
public sealed class SystemEvents
{
// Almost all of our data is static. We keep a single instance of
// SystemEvents around so we can bind delegates to it.
// Non-static methods in this class will only be called through
// one of the delegates.
private static readonly object s_eventLockObject = new object();
private static readonly object s_procLockObject = new object();
private static volatile SystemEvents s_systemEvents;
private static volatile Thread s_windowThread;
private static volatile ManualResetEvent s_eventWindowReady;
private static Random s_randomTimerId = new Random();
private static volatile bool s_registeredSessionNotification = false;
private static volatile int s_domainQualifier;
private static volatile Interop.User32.WNDCLASS s_staticwndclass;
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
private static volatile IntPtr s_defWindowProc;
private static volatile string s_className = null;
// cross-thread marshaling
private static volatile Queue<Delegate> s_threadCallbackList; // list of Delegates
private static volatile int s_threadCallbackMessage = 0;
private static volatile ManualResetEvent s_eventThreadTerminated;
// Per-instance data that is isolated to the window thread.
private volatile IntPtr _windowHandle;
private Interop.User32.WndProc _windowProc;
private Interop.Kernel32.ConsoleCtrlHandlerRoutine _consoleHandler;
// The set of events we respond to.
private static readonly object s_onUserPreferenceChangingEvent = new object();
private static readonly object s_onUserPreferenceChangedEvent = new object();
private static readonly object s_onSessionEndingEvent = new object();
private static readonly object s_onSessionEndedEvent = new object();
private static readonly object s_onPowerModeChangedEvent = new object();
private static readonly object s_onLowMemoryEvent = new object();
private static readonly object s_onDisplaySettingsChangingEvent = new object();
private static readonly object s_onDisplaySettingsChangedEvent = new object();
private static readonly object s_onInstalledFontsChangedEvent = new object();
private static readonly object s_onTimeChangedEvent = new object();
private static readonly object s_onTimerElapsedEvent = new object();
private static readonly object s_onPaletteChangedEvent = new object();
private static readonly object s_onEventsThreadShutdownEvent = new object();
private static readonly object s_onSessionSwitchEvent = new object();
// Our list of handler information. This is a lookup of the above keys and objects that
// match a delegate with a SyncronizationContext so we can fire on the proper thread.
private static Dictionary<object, List<SystemEventInvokeInfo>> s_handlers;
/// <devdoc>
/// This class is static, there is no need to ever create it.
/// </devdoc>
private SystemEvents()
{
}
// stole from SystemInformation... if we get SystemInformation moved
// to somewhere that we can use it... rip this!
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
private static volatile IntPtr s_processWinStation = IntPtr.Zero;
private static volatile bool s_isUserInteractive = false;
private static bool UserInteractive
{
get
{
if (Environment.OSVersion.Platform == System.PlatformID.Win32NT)
{
IntPtr hwinsta = IntPtr.Zero;
hwinsta = Interop.User32.GetProcessWindowStation();
if (hwinsta != IntPtr.Zero && s_processWinStation != hwinsta)
{
s_isUserInteractive = true;
int lengthNeeded = 0;
Interop.User32.USEROBJECTFLAGS flags = new Interop.User32.USEROBJECTFLAGS();
if (Interop.User32.GetUserObjectInformationW(hwinsta, Interop.User32.UOI_FLAGS, flags, Marshal.SizeOf(flags), ref lengthNeeded))
{
if ((flags.dwFlags & Interop.User32.WSF_VISIBLE) == 0)
{
s_isUserInteractive = false;
}
}
s_processWinStation = hwinsta;
}
}
else
{
s_isUserInteractive = true;
}
return s_isUserInteractive;
}
}
/// <devdoc>
/// <para>Occurs when the display settings are changing.</para>
/// </devdoc>
public static event EventHandler DisplaySettingsChanging
{
add
{
AddEventHandler(s_onDisplaySettingsChangingEvent, value);
}
remove
{
RemoveEventHandler(s_onDisplaySettingsChangingEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user changes the display settings.</para>
/// </devdoc>
public static event EventHandler DisplaySettingsChanged
{
add
{
AddEventHandler(s_onDisplaySettingsChangedEvent, value);
}
remove
{
RemoveEventHandler(s_onDisplaySettingsChangedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs before the thread that listens for system events is terminated.
/// Delegates will be invoked on the events thread.</para>
/// </devdoc>
public static event EventHandler EventsThreadShutdown
{
// Really only here for GDI+ initialization and shut down
add
{
AddEventHandler(s_onEventsThreadShutdownEvent, value);
}
remove
{
RemoveEventHandler(s_onEventsThreadShutdownEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user adds fonts to or removes fonts from the system.</para>
/// </devdoc>
public static event EventHandler InstalledFontsChanged
{
add
{
AddEventHandler(s_onInstalledFontsChangedEvent, value);
}
remove
{
RemoveEventHandler(s_onInstalledFontsChangedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the system is running out of available RAM.</para>
/// </devdoc>
[Obsolete("This event has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static event EventHandler LowMemory
{
add
{
EnsureSystemEvents(true, true);
AddEventHandler(s_onLowMemoryEvent, value);
}
remove
{
RemoveEventHandler(s_onLowMemoryEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user switches to an application that uses a different
/// palette.</para>
/// </devdoc>
public static event EventHandler PaletteChanged
{
add
{
AddEventHandler(s_onPaletteChangedEvent, value);
}
remove
{
RemoveEventHandler(s_onPaletteChangedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user suspends or resumes the system.</para>
/// </devdoc>
public static event PowerModeChangedEventHandler PowerModeChanged
{
add
{
EnsureSystemEvents(true, true);
AddEventHandler(s_onPowerModeChangedEvent, value);
}
remove
{
RemoveEventHandler(s_onPowerModeChangedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user is logging off or shutting down the system.</para>
/// </devdoc>
public static event SessionEndedEventHandler SessionEnded
{
add
{
EnsureSystemEvents(true, false);
AddEventHandler(s_onSessionEndedEvent, value);
}
remove
{
RemoveEventHandler(s_onSessionEndedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user is trying to log off or shutdown the system.</para>
/// </devdoc>
public static event SessionEndingEventHandler SessionEnding
{
add
{
EnsureSystemEvents(true, false);
AddEventHandler(s_onSessionEndingEvent, value);
}
remove
{
RemoveEventHandler(s_onSessionEndingEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when a user session switches.</para>
/// </devdoc>
public static event SessionSwitchEventHandler SessionSwitch
{
add
{
EnsureSystemEvents(true, true);
EnsureRegisteredSessionNotification();
AddEventHandler(s_onSessionSwitchEvent, value);
}
remove
{
RemoveEventHandler(s_onSessionSwitchEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when the user changes the time on the system clock.</para>
/// </devdoc>
public static event EventHandler TimeChanged
{
add
{
EnsureSystemEvents(true, false);
AddEventHandler(s_onTimeChangedEvent, value);
}
remove
{
RemoveEventHandler(s_onTimeChangedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when a windows timer interval has expired.</para>
/// </devdoc>
public static event TimerElapsedEventHandler TimerElapsed
{
add
{
EnsureSystemEvents(true, false);
AddEventHandler(s_onTimerElapsedEvent, value);
}
remove
{
RemoveEventHandler(s_onTimerElapsedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when a user preference has changed.</para>
/// </devdoc>
public static event UserPreferenceChangedEventHandler UserPreferenceChanged
{
add
{
AddEventHandler(s_onUserPreferenceChangedEvent, value);
}
remove
{
RemoveEventHandler(s_onUserPreferenceChangedEvent, value);
}
}
/// <devdoc>
/// <para>Occurs when a user preference is changing.</para>
/// </devdoc>
public static event UserPreferenceChangingEventHandler UserPreferenceChanging
{
add
{
AddEventHandler(s_onUserPreferenceChangingEvent, value);
}
remove
{
RemoveEventHandler(s_onUserPreferenceChangingEvent, value);
}
}
private static void AddEventHandler(object key, Delegate value)
{
lock (s_eventLockObject)
{
if (s_handlers == null)
{
s_handlers = new Dictionary<object, List<SystemEventInvokeInfo>>();
EnsureSystemEvents(false, false);
}
List<SystemEventInvokeInfo> invokeItems;
if (!s_handlers.TryGetValue(key, out invokeItems))
{
invokeItems = new List<SystemEventInvokeInfo>();
s_handlers[key] = invokeItems;
}
else
{
invokeItems = s_handlers[key];
}
invokeItems.Add(new SystemEventInvokeInfo(value));
}
}
/// <devdoc>
/// Console handler we add in case we are a console application or a service.
/// Without this we will not get end session events.
/// </devdoc>
private bool ConsoleHandlerProc(int signalType)
{
switch (signalType)
{
case Interop.User32.CTRL_LOGOFF_EVENT:
OnSessionEnded((IntPtr)1, (IntPtr)Interop.User32.ENDSESSION_LOGOFF);
break;
case Interop.User32.CTRL_SHUTDOWN_EVENT:
OnSessionEnded((IntPtr)1, (IntPtr)0);
break;
}
return false;
}
private Interop.User32.WNDCLASS WndClass
{
get
{
if (s_staticwndclass == null)
{
const string classNameFormat = ".NET-BroadcastEventWindow.{0}.{1}";
IntPtr hInstance = Interop.Kernel32.GetModuleHandle(null);
s_className = string.Format(System.Globalization.CultureInfo.InvariantCulture,
classNameFormat,
Convert.ToString(AppDomain.CurrentDomain.GetHashCode(), 16),
s_domainQualifier);
Interop.User32.WNDCLASS tempwndclass = new Interop.User32.WNDCLASS();
tempwndclass.hbrBackground = (IntPtr)(Interop.User32.COLOR_WINDOW + 1);
tempwndclass.style = 0;
_windowProc = new Interop.User32.WndProc(this.WindowProc);
tempwndclass.lpszClassName = s_className;
tempwndclass.lpfnWndProc = _windowProc;
tempwndclass.hInstance = hInstance;
s_staticwndclass = tempwndclass;
}
return s_staticwndclass;
}
}
private IntPtr DefWndProc
{
get
{
if (s_defWindowProc == IntPtr.Zero)
{
s_defWindowProc = Interop.Kernel32.GetProcAddress(Interop.Kernel32.GetModuleHandle("user32.dll"), "DefWindowProcW");
}
return s_defWindowProc;
}
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Only called on a single thread")]
private void BumpQualifier()
{
s_staticwndclass = null;
s_domainQualifier++;
}
/// <include file='doc\SystemEvents.uex' path='docs/doc[@for="SystemEvents.CreateBroadcastWindow"]/*' />
/// <devdoc>
/// Goes through the work to register and create a window.
/// </devdoc>
private IntPtr CreateBroadcastWindow()
{
// Register the window class.
Interop.User32.WNDCLASS_I wndclassi = new Interop.User32.WNDCLASS_I();
IntPtr hInstance = Interop.Kernel32.GetModuleHandle(null);
if (!Interop.User32.GetClassInfoW(hInstance, WndClass.lpszClassName, wndclassi))
{
if (Interop.User32.RegisterClassW(WndClass) == 0)
{
_windowProc = null;
Debug.WriteLine("Unable to register broadcast window class: {0}", Marshal.GetLastWin32Error());
return IntPtr.Zero;
}
}
else
{
// lets double check the wndproc returned by getclassinfo for sentinel value defwndproc.
if (wndclassi.lpfnWndProc == DefWndProc)
{
// if we are in there, it means className belongs to an unloaded appdomain.
short atom = 0;
// try to unregister it.
if (0 != Interop.User32.UnregisterClassW(WndClass.lpszClassName, Interop.Kernel32.GetModuleHandle(null)))
{
atom = Interop.User32.RegisterClassW(WndClass);
}
if (atom == 0)
{
do
{
BumpQualifier();
atom = Interop.User32.RegisterClassW(WndClass);
} while (atom == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_CLASS_ALREADY_EXISTS);
}
}
}
// And create an instance of the window.
IntPtr hwnd = Interop.User32.CreateWindowExW(
0,
WndClass.lpszClassName,
WndClass.lpszClassName,
Interop.User32.WS_POPUP,
0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero,
hInstance, IntPtr.Zero);
return hwnd;
}
/// <internalonly/>
/// <devdoc>
/// <para>Creates a new window timer asociated with the
/// system events window.</para>
/// </devdoc>
public static IntPtr CreateTimer(int interval)
{
if (interval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgument, nameof(interval), interval.ToString(System.Threading.Thread.CurrentThread.CurrentCulture), "0"));
}
EnsureSystemEvents(true, true);
IntPtr timerId = Interop.User32.SendMessageW(new HandleRef(s_systemEvents, s_systemEvents._windowHandle),
Interop.User32.WM_CREATETIMER, (IntPtr)interval, IntPtr.Zero);
if (timerId == IntPtr.Zero)
{
throw new ExternalException(SR.ErrorCreateTimer);
}
return timerId;
}
private void Dispose()
{
if (_windowHandle != IntPtr.Zero)
{
if (s_registeredSessionNotification)
{
Interop.Wtsapi32.WTSUnRegisterSessionNotification(new HandleRef(s_systemEvents, s_systemEvents._windowHandle));
}
IntPtr handle = _windowHandle;
_windowHandle = IntPtr.Zero;
// we check IsWindow because Application may have rudely destroyed our broadcast window.
// if this were true, we want to unregister the class.
if (Interop.User32.IsWindow(handle) && DefWndProc != IntPtr.Zero)
{
// set our sentinel value that we will look for upon initialization to indicate
// the window class belongs to an unloaded appdomain and therefore should not be used.
if (IntPtr.Size == 4)
{
// In a 32-bit process we must call the non-'ptr' version of these APIs
Interop.User32.SetWindowLongW(handle, Interop.User32.GWL_WNDPROC, DefWndProc);
Interop.User32.SetClassLongW(handle, Interop.User32.GCL_WNDPROC, DefWndProc);
}
else
{
Interop.User32.SetWindowLongPtrW(handle, Interop.User32.GWL_WNDPROC, DefWndProc);
Interop.User32.SetClassLongPtrW(handle, Interop.User32.GCL_WNDPROC, DefWndProc);
}
}
// If DestroyWindow failed, it is because we're being
// shutdown from another thread. In this case, locate the
// DefWindowProc call in User32, set the window proc to call it,
// and post a WM_CLOSE. This will close the window from
// the correct thread without relying on managed code executing.
if (Interop.User32.IsWindow(handle) && !Interop.User32.DestroyWindow(handle))
{
Interop.User32.PostMessageW(handle, Interop.User32.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
else
{
IntPtr hInstance = Interop.Kernel32.GetModuleHandle(null);
Interop.User32.UnregisterClassW(s_className, hInstance);
}
}
if (_consoleHandler != null)
{
Interop.Kernel32.SetConsoleCtrlHandler(_consoleHandler, false);
_consoleHandler = null;
}
}
/// <devdoc>
/// Creates the static resources needed by
/// system events.
/// </devdoc>
private static void EnsureSystemEvents(bool requireHandle, bool throwOnRefusal)
{
// The secondary check here is to detect asp.net. Asp.net uses multiple
// app domains to field requests and we do not want to gobble up an
// additional thread per domain. So under this scenario SystemEvents
// becomes a nop.
if (s_systemEvents == null)
{
lock (s_procLockObject)
{
if (s_systemEvents == null)
{
if (Thread.GetDomain().GetData(".appDomain") != null)
{
if (throwOnRefusal)
{
throw new InvalidOperationException(SR.ErrorSystemEventsNotSupported);
}
return;
}
// If we are creating system events on a thread declared as STA, then
// just share the thread.
if (!UserInteractive || Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
SystemEvents systemEvents = new SystemEvents();
systemEvents.Initialize();
// ensure this is initialized last as that will force concurrent threads calling
// this method to block until after we've initialized.
s_systemEvents = systemEvents;
}
else
{
s_eventWindowReady = new ManualResetEvent(false);
SystemEvents systemEvents = new SystemEvents();
s_windowThread = new Thread(new ThreadStart(systemEvents.WindowThreadProc));
s_windowThread.IsBackground = true;
s_windowThread.Name = ".NET SystemEvents";
s_windowThread.Start();
s_eventWindowReady.WaitOne();
// ensure this is initialized last as that will force concurrent threads calling
// this method to block until after we've initialized.
s_systemEvents = systemEvents;
}
if (requireHandle && s_systemEvents._windowHandle == IntPtr.Zero)
{
// In theory, it's not the end of the world that
// we don't get system events. Unfortunately, the main reason windowHandle == 0
// is CreateWindowEx failed for mysterious reasons, and when that happens,
// subsequent (and more important) CreateWindowEx calls also fail.
throw new ExternalException(SR.ErrorCreateSystemEvents);
}
}
}
}
}
private static void EnsureRegisteredSessionNotification()
{
if (!s_registeredSessionNotification)
{
IntPtr retval = Interop.Kernel32.LoadLibrary(Interop.Libraries.Wtsapi32);
if (retval != IntPtr.Zero)
{
Interop.Wtsapi32.WTSRegisterSessionNotification(new HandleRef(s_systemEvents, s_systemEvents._windowHandle), Interop.Wtsapi32.NOTIFY_FOR_THIS_SESSION);
s_registeredSessionNotification = true;
Interop.Kernel32.FreeLibrary(retval);
}
}
}
private UserPreferenceCategory GetUserPreferenceCategory(int msg, IntPtr wParam, IntPtr lParam)
{
UserPreferenceCategory pref = UserPreferenceCategory.General;
if (msg == Interop.User32.WM_SETTINGCHANGE)
{
if (lParam != IntPtr.Zero && Marshal.PtrToStringUni(lParam).Equals("Policy"))
{
pref = UserPreferenceCategory.Policy;
}
else if (lParam != IntPtr.Zero && Marshal.PtrToStringUni(lParam).Equals("intl"))
{
pref = UserPreferenceCategory.Locale;
}
else
{
switch ((int)wParam)
{
case Interop.User32.SPI_SETACCESSTIMEOUT:
case Interop.User32.SPI_SETFILTERKEYS:
case Interop.User32.SPI_SETHIGHCONTRAST:
case Interop.User32.SPI_SETMOUSEKEYS:
case Interop.User32.SPI_SETSCREENREADER:
case Interop.User32.SPI_SETSERIALKEYS:
case Interop.User32.SPI_SETSHOWSOUNDS:
case Interop.User32.SPI_SETSOUNDSENTRY:
case Interop.User32.SPI_SETSTICKYKEYS:
case Interop.User32.SPI_SETTOGGLEKEYS:
pref = UserPreferenceCategory.Accessibility;
break;
case Interop.User32.SPI_SETDESKWALLPAPER:
case Interop.User32.SPI_SETFONTSMOOTHING:
case Interop.User32.SPI_SETCURSORS:
case Interop.User32.SPI_SETDESKPATTERN:
case Interop.User32.SPI_SETGRIDGRANULARITY:
case Interop.User32.SPI_SETWORKAREA:
pref = UserPreferenceCategory.Desktop;
break;
case Interop.User32.SPI_ICONHORIZONTALSPACING:
case Interop.User32.SPI_ICONVERTICALSPACING:
case Interop.User32.SPI_SETICONMETRICS:
case Interop.User32.SPI_SETICONS:
case Interop.User32.SPI_SETICONTITLELOGFONT:
case Interop.User32.SPI_SETICONTITLEWRAP:
pref = UserPreferenceCategory.Icon;
break;
case Interop.User32.SPI_SETDOUBLECLICKTIME:
case Interop.User32.SPI_SETDOUBLECLKHEIGHT:
case Interop.User32.SPI_SETDOUBLECLKWIDTH:
case Interop.User32.SPI_SETMOUSE:
case Interop.User32.SPI_SETMOUSEBUTTONSWAP:
case Interop.User32.SPI_SETMOUSEHOVERHEIGHT:
case Interop.User32.SPI_SETMOUSEHOVERTIME:
case Interop.User32.SPI_SETMOUSESPEED:
case Interop.User32.SPI_SETMOUSETRAILS:
case Interop.User32.SPI_SETSNAPTODEFBUTTON:
case Interop.User32.SPI_SETWHEELSCROLLLINES:
case Interop.User32.SPI_SETCURSORSHADOW:
case Interop.User32.SPI_SETHOTTRACKING:
case Interop.User32.SPI_SETTOOLTIPANIMATION:
case Interop.User32.SPI_SETTOOLTIPFADE:
pref = UserPreferenceCategory.Mouse;
break;
case Interop.User32.SPI_SETKEYBOARDDELAY:
case Interop.User32.SPI_SETKEYBOARDPREF:
case Interop.User32.SPI_SETKEYBOARDSPEED:
case Interop.User32.SPI_SETLANGTOGGLE:
pref = UserPreferenceCategory.Keyboard;
break;
case Interop.User32.SPI_SETMENUDROPALIGNMENT:
case Interop.User32.SPI_SETMENUFADE:
case Interop.User32.SPI_SETMENUSHOWDELAY:
case Interop.User32.SPI_SETMENUANIMATION:
case Interop.User32.SPI_SETSELECTIONFADE:
pref = UserPreferenceCategory.Menu;
break;
case Interop.User32.SPI_SETLOWPOWERACTIVE:
case Interop.User32.SPI_SETLOWPOWERTIMEOUT:
case Interop.User32.SPI_SETPOWEROFFACTIVE:
case Interop.User32.SPI_SETPOWEROFFTIMEOUT:
pref = UserPreferenceCategory.Power;
break;
case Interop.User32.SPI_SETSCREENSAVEACTIVE:
case Interop.User32.SPI_SETSCREENSAVERRUNNING:
case Interop.User32.SPI_SETSCREENSAVETIMEOUT:
pref = UserPreferenceCategory.Screensaver;
break;
case Interop.User32.SPI_SETKEYBOARDCUES:
case Interop.User32.SPI_SETCOMBOBOXANIMATION:
case Interop.User32.SPI_SETLISTBOXSMOOTHSCROLLING:
case Interop.User32.SPI_SETGRADIENTCAPTIONS:
case Interop.User32.SPI_SETUIEFFECTS:
case Interop.User32.SPI_SETACTIVEWINDOWTRACKING:
case Interop.User32.SPI_SETACTIVEWNDTRKZORDER:
case Interop.User32.SPI_SETACTIVEWNDTRKTIMEOUT:
case Interop.User32.SPI_SETANIMATION:
case Interop.User32.SPI_SETBORDER:
case Interop.User32.SPI_SETCARETWIDTH:
case Interop.User32.SPI_SETDRAGFULLWINDOWS:
case Interop.User32.SPI_SETDRAGHEIGHT:
case Interop.User32.SPI_SETDRAGWIDTH:
case Interop.User32.SPI_SETFOREGROUNDFLASHCOUNT:
case Interop.User32.SPI_SETFOREGROUNDLOCKTIMEOUT:
case Interop.User32.SPI_SETMINIMIZEDMETRICS:
case Interop.User32.SPI_SETNONCLIENTMETRICS:
case Interop.User32.SPI_SETSHOWIMEUI:
pref = UserPreferenceCategory.Window;
break;
}
}
}
else if (msg == Interop.User32.WM_SYSCOLORCHANGE)
{
pref = UserPreferenceCategory.Color;
}
else
{
Debug.Fail("Unrecognized message passed to UserPreferenceCategory");
}
return pref;
}
private void Initialize()
{
_consoleHandler = new Interop.Kernel32.ConsoleCtrlHandlerRoutine(ConsoleHandlerProc);
if (!Interop.Kernel32.SetConsoleCtrlHandler(_consoleHandler, true))
{
Debug.Fail("Failed to install console handler.");
_consoleHandler = null;
}
_windowHandle = CreateBroadcastWindow();
Debug.WriteLineIf(_windowHandle == IntPtr.Zero, "CreateBroadcastWindow failed");
AppDomain.CurrentDomain.ProcessExit += new EventHandler(SystemEvents.Shutdown);
AppDomain.CurrentDomain.DomainUnload += new EventHandler(SystemEvents.Shutdown);
}
/// <devdoc>
/// Called on the control's owning thread to perform the actual callback.
/// This empties this control's callback queue, propagating any excpetions
/// back as needed.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void InvokeMarshaledCallbacks()
{
Debug.Assert(s_threadCallbackList != null, "Invoking marshaled callbacks before there are any");
Delegate current = null;
lock (s_threadCallbackList)
{
if (s_threadCallbackList.Count > 0)
{
current = (Delegate)s_threadCallbackList.Dequeue();
}
}
// Now invoke on all the queued items.
while (current != null)
{
try
{
// Optimize a common case of using EventHandler. This allows us to invoke
// early bound, which is a bit more efficient.
EventHandler c = current as EventHandler;
if (c != null)
{
c(null, EventArgs.Empty);
}
else
{
current.DynamicInvoke(Array.Empty<object>());
}
}
catch (Exception t)
{
Debug.Fail("SystemEvents marshaled callback failed:" + t);
}
lock (s_threadCallbackList)
{
if (s_threadCallbackList.Count > 0)
{
current = (Delegate)s_threadCallbackList.Dequeue();
}
else
{
current = null;
}
}
}
}
/// <devdoc>
/// Executes the given delegate asynchronously on the thread that listens for system events. Similar to Control.BeginInvoke().
/// </devdoc>
public static void InvokeOnEventsThread(Delegate method)
{
// This method is really only here for GDI+ initialization/shutdown
EnsureSystemEvents(true, true);
#if DEBUG
int pid;
int thread = Interop.User32.GetWindowThreadProcessId(new HandleRef(s_systemEvents, s_systemEvents._windowHandle), out pid);
Debug.Assert(s_windowThread == null || thread != Interop.Kernel32.GetCurrentThreadId(), "Don't call MarshaledInvoke on the system events thread");
#endif
if (s_threadCallbackList == null)
{
lock (s_eventLockObject)
{
if (s_threadCallbackList == null)
{
s_threadCallbackMessage = Interop.User32.RegisterWindowMessageW("SystemEventsThreadCallbackMessage");
s_threadCallbackList = new Queue<Delegate>();
}
}
}
Debug.Assert(s_threadCallbackMessage != 0, "threadCallbackList initialized but threadCallbackMessage not?");
lock (s_threadCallbackList)
{
s_threadCallbackList.Enqueue(method);
}
Interop.User32.PostMessageW(new HandleRef(s_systemEvents, s_systemEvents._windowHandle), s_threadCallbackMessage, IntPtr.Zero, IntPtr.Zero);
}
/// <internalonly/>
/// <devdoc>
/// <para>Kills the timer specified by the given id.</para>
/// </devdoc>
public static void KillTimer(IntPtr timerId)
{
EnsureSystemEvents(true, true);
if (s_systemEvents._windowHandle != IntPtr.Zero)
{
int res = (int)Interop.User32.SendMessageW(new HandleRef(s_systemEvents, s_systemEvents._windowHandle),
Interop.User32.WM_KILLTIMER, timerId, IntPtr.Zero);
if (res == 0)
throw new ExternalException(SR.ErrorKillTimer);
}
}
/// <devdoc>
/// Callback that handles the create timer
/// user message.
/// </devdoc>
private IntPtr OnCreateTimer(IntPtr wParam)
{
IntPtr timerId = (IntPtr)s_randomTimerId.Next();
IntPtr res = Interop.User32.SetTimer(_windowHandle, timerId, (int)wParam, IntPtr.Zero);
return (res == IntPtr.Zero ? IntPtr.Zero : timerId);
}
/// <devdoc>
/// Handler that raises the DisplaySettings changing event
/// </devdoc>
private void OnDisplaySettingsChanging()
{
RaiseEvent(s_onDisplaySettingsChangingEvent, this, EventArgs.Empty);
}
/// <devdoc>
/// Handler that raises the DisplaySettings changed event
/// </devdoc>
private void OnDisplaySettingsChanged()
{
RaiseEvent(s_onDisplaySettingsChangedEvent, this, EventArgs.Empty);
}
/// <devdoc>
/// Handler for any event that fires a standard EventHandler delegate.
/// </devdoc>
private void OnGenericEvent(object eventKey)
{
RaiseEvent(eventKey, this, EventArgs.Empty);
}
private void OnShutdown(object eventKey)
{
RaiseEvent(false, eventKey, this, EventArgs.Empty);
}
/// <devdoc>
/// Callback that handles the KillTimer
/// user message.
/// </devdoc>
private bool OnKillTimer(IntPtr wParam)
{
bool res = Interop.User32.KillTimer(_windowHandle, wParam);
return res;
}
/// <devdoc>
/// Handler for WM_POWERBROADCAST.
/// </devdoc>
private void OnPowerModeChanged(IntPtr wParam)
{
PowerModes mode;
switch ((int)wParam)
{
case Interop.User32.PBT_APMSUSPEND:
case Interop.User32.PBT_APMSTANDBY:
mode = PowerModes.Suspend;
break;
case Interop.User32.PBT_APMRESUMECRITICAL:
case Interop.User32.PBT_APMRESUMESUSPEND:
case Interop.User32.PBT_APMRESUMESTANDBY:
mode = PowerModes.Resume;
break;
case Interop.User32.PBT_APMBATTERYLOW:
case Interop.User32.PBT_APMPOWERSTATUSCHANGE:
case Interop.User32.PBT_APMOEMEVENT:
mode = PowerModes.StatusChange;
break;
default:
return;
}
RaiseEvent(s_onPowerModeChangedEvent, this, new PowerModeChangedEventArgs(mode));
}
/// <devdoc>
/// Handler for WM_ENDSESSION.
/// </devdoc>
private void OnSessionEnded(IntPtr wParam, IntPtr lParam)
{
// wParam will be nonzero if the session is actually ending. If
// it was canceled then we do not want to raise the event.
if (wParam != (IntPtr)0)
{
SessionEndReasons reason = SessionEndReasons.SystemShutdown;
if (((unchecked((int)(long)lParam)) & Interop.User32.ENDSESSION_LOGOFF) != 0)
{
reason = SessionEndReasons.Logoff;
}
SessionEndedEventArgs endEvt = new SessionEndedEventArgs(reason);
RaiseEvent(s_onSessionEndedEvent, this, endEvt);
}
}
/// <devdoc>
/// Handler for WM_QUERYENDSESSION.
/// </devdoc>
private int OnSessionEnding(IntPtr lParam)
{
int endOk = 1;
SessionEndReasons reason = SessionEndReasons.SystemShutdown;
// Casting to (int) is bad if we're 64-bit; casting to (long) is ok whether we're 64- or 32-bit.
if ((((long)lParam) & Interop.User32.ENDSESSION_LOGOFF) != 0)
{
reason = SessionEndReasons.Logoff;
}
SessionEndingEventArgs endEvt = new SessionEndingEventArgs(reason);
RaiseEvent(s_onSessionEndingEvent, this, endEvt);
endOk = (endEvt.Cancel ? 0 : 1);
return endOk;
}
private void OnSessionSwitch(int wParam)
{
SessionSwitchEventArgs switchEventArgs = new SessionSwitchEventArgs((SessionSwitchReason)wParam);
RaiseEvent(s_onSessionSwitchEvent, this, switchEventArgs);
}
/// <devdoc>
/// Handler for WM_THEMECHANGED
/// Whidbey note: Before Whidbey, we used to fire UserPreferenceChanged with category
/// set to Window. In Whidbey, we support visual styles and need a new category Theme
/// since Window is too general. We fire UserPreferenceChanged with this category, but
/// for backward compat, we also fire it with category set to Window.
/// </devdoc>
private void OnThemeChanged()
{
// we need to fire a changing event handler for Themes.
// note that it needs to be documented that accessing theme information during the changing event is forbidden.
RaiseEvent(s_onUserPreferenceChangingEvent, this, new UserPreferenceChangingEventArgs(UserPreferenceCategory.VisualStyle));
UserPreferenceCategory pref = UserPreferenceCategory.Window;
RaiseEvent(s_onUserPreferenceChangedEvent, this, new UserPreferenceChangedEventArgs(pref));
pref = UserPreferenceCategory.VisualStyle;
RaiseEvent(s_onUserPreferenceChangedEvent, this, new UserPreferenceChangedEventArgs(pref));
}
/// <devdoc>
/// Handler for WM_SETTINGCHANGE and WM_SYSCOLORCHANGE.
/// </devdoc>
private void OnUserPreferenceChanged(int msg, IntPtr wParam, IntPtr lParam)
{
UserPreferenceCategory pref = GetUserPreferenceCategory(msg, wParam, lParam);
RaiseEvent(s_onUserPreferenceChangedEvent, this, new UserPreferenceChangedEventArgs(pref));
}
private void OnUserPreferenceChanging(int msg, IntPtr wParam, IntPtr lParam)
{
UserPreferenceCategory pref = GetUserPreferenceCategory(msg, wParam, lParam);
RaiseEvent(s_onUserPreferenceChangingEvent, this, new UserPreferenceChangingEventArgs(pref));
}
/// <devdoc>
/// Handler for WM_TIMER.
/// </devdoc>
private void OnTimerElapsed(IntPtr wParam)
{
RaiseEvent(s_onTimerElapsedEvent, this, new TimerElapsedEventArgs(wParam));
}
private static void RaiseEvent(object key, params object[] args)
{
RaiseEvent(true, key, args);
}
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void RaiseEvent(bool checkFinalization, object key, params object[] args)
{
// If the AppDomain's unloading, we shouldn't fire SystemEvents other than Shutdown.
if (checkFinalization && AppDomain.CurrentDomain.IsFinalizingForUnload())
{
return;
}
SystemEventInvokeInfo[] invokeItemArray = null;
lock (s_eventLockObject)
{
if (s_handlers != null && s_handlers.ContainsKey(key))
{
List<SystemEventInvokeInfo> invokeItems = s_handlers[key];
// clone the list so we don't have this type locked and cause
// a deadlock if someone tries to modify handlers during an invoke.
if (invokeItems != null)
{
invokeItemArray = invokeItems.ToArray();
}
}
}
if (invokeItemArray != null)
{
for (int i = 0; i < invokeItemArray.Length; i++)
{
try
{
SystemEventInvokeInfo info = invokeItemArray[i];
info.Invoke(checkFinalization, args);
invokeItemArray[i] = null; // clear it if it's valid
}
catch (Exception)
{
// Eat exceptions (Everett compat)
}
}
// clean out any that are dead.
lock (s_eventLockObject)
{
List<SystemEventInvokeInfo> invokeItems = null;
for (int i = 0; i < invokeItemArray.Length; i++)
{
SystemEventInvokeInfo info = invokeItemArray[i];
if (info != null)
{
if (invokeItems == null)
{
if (!s_handlers.TryGetValue(key, out invokeItems))
{
// weird. just to be safe.
return;
}
}
invokeItems.Remove(info);
}
}
}
}
}
private static void RemoveEventHandler(object key, Delegate value)
{
lock (s_eventLockObject)
{
if (s_handlers != null && s_handlers.ContainsKey(key))
{
List<SystemEventInvokeInfo> invokeItems = (List<SystemEventInvokeInfo>)s_handlers[key];
invokeItems.Remove(new SystemEventInvokeInfo(value));
}
}
}
private static void Shutdown()
{
if (s_systemEvents != null && s_systemEvents._windowHandle != IntPtr.Zero)
{
lock (s_procLockObject)
{
if (s_systemEvents != null)
{
// If we are using system events from another thread, request that it terminate
if (s_windowThread != null)
{
s_eventThreadTerminated = new ManualResetEvent(false);
#if DEBUG
int pid;
int thread = Interop.User32.GetWindowThreadProcessId(new HandleRef(s_systemEvents, s_systemEvents._windowHandle), out pid);
Debug.Assert(thread != Interop.Kernel32.GetCurrentThreadId(), "Don't call Shutdown on the system events thread");
#endif
Interop.User32.PostMessageW(new HandleRef(s_systemEvents, s_systemEvents._windowHandle), Interop.User32.WM_QUIT, IntPtr.Zero, IntPtr.Zero);
s_eventThreadTerminated.WaitOne();
s_windowThread.Join(); // avoids an AppDomainUnloaded exception on our background thread.
}
else
{
s_systemEvents.Dispose();
s_systemEvents = null;
}
}
}
}
}
[PrePrepareMethod]
private static void Shutdown(object sender, EventArgs e)
{
Shutdown();
}
/// <devdoc>
/// A standard Win32 window proc for our broadcast window.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private IntPtr WindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
{
switch (msg)
{
case Interop.User32.WM_SETTINGCHANGE:
string newString;
IntPtr newStringPtr = lParam;
if (lParam != IntPtr.Zero)
{
newString = Marshal.PtrToStringUni(lParam);
if (newString != null)
{
newStringPtr = Marshal.StringToHGlobalUni(newString);
}
}
Interop.User32.PostMessageW(_windowHandle, Interop.User32.WM_REFLECT + msg, wParam, newStringPtr);
break;
case Interop.User32.WM_WTSSESSION_CHANGE:
OnSessionSwitch((int)wParam);
break;
case Interop.User32.WM_SYSCOLORCHANGE:
case Interop.User32.WM_COMPACTING:
case Interop.User32.WM_DISPLAYCHANGE:
case Interop.User32.WM_FONTCHANGE:
case Interop.User32.WM_PALETTECHANGED:
case Interop.User32.WM_TIMECHANGE:
case Interop.User32.WM_TIMER:
case Interop.User32.WM_THEMECHANGED:
Interop.User32.PostMessageW(_windowHandle, Interop.User32.WM_REFLECT + msg, wParam, lParam);
break;
case Interop.User32.WM_CREATETIMER:
return OnCreateTimer(wParam);
case Interop.User32.WM_KILLTIMER:
return (IntPtr)(OnKillTimer(wParam) ? 1 : 0);
case Interop.User32.WM_REFLECT + Interop.User32.WM_SETTINGCHANGE:
try
{
OnUserPreferenceChanging(msg - Interop.User32.WM_REFLECT, wParam, lParam);
OnUserPreferenceChanged(msg - Interop.User32.WM_REFLECT, wParam, lParam);
}
finally
{
try
{
if (lParam != IntPtr.Zero)
{
Marshal.FreeHGlobal(lParam);
}
}
catch (Exception e)
{
Debug.Assert(false, "Exception occurred while freeing memory: " + e.ToString());
}
}
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_SYSCOLORCHANGE:
OnUserPreferenceChanging(msg - Interop.User32.WM_REFLECT, wParam, lParam);
OnUserPreferenceChanged(msg - Interop.User32.WM_REFLECT, wParam, lParam);
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_THEMECHANGED:
OnThemeChanged();
break;
case Interop.User32.WM_QUERYENDSESSION:
return (IntPtr)OnSessionEnding(lParam);
case Interop.User32.WM_ENDSESSION:
OnSessionEnded(wParam, lParam);
break;
case Interop.User32.WM_POWERBROADCAST:
OnPowerModeChanged(wParam);
break;
// WM_HIBERNATE on WinCE
case Interop.User32.WM_REFLECT + Interop.User32.WM_COMPACTING:
OnGenericEvent(s_onLowMemoryEvent);
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_DISPLAYCHANGE:
OnDisplaySettingsChanging();
OnDisplaySettingsChanged();
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_FONTCHANGE:
OnGenericEvent(s_onInstalledFontsChangedEvent);
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_PALETTECHANGED:
OnGenericEvent(s_onPaletteChangedEvent);
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_TIMECHANGE:
OnGenericEvent(s_onTimeChangedEvent);
break;
case Interop.User32.WM_REFLECT + Interop.User32.WM_TIMER:
OnTimerElapsed(wParam);
break;
default:
// If we received a thread execute message, then execute it.
if (msg == s_threadCallbackMessage && msg != 0)
{
InvokeMarshaledCallbacks();
return IntPtr.Zero;
}
break;
}
return Interop.User32.DefWindowProcW(hWnd, msg, wParam, lParam);
}
/// <devdoc>
/// This is the method that runs our window thread. This method
/// creates a window and spins up a message loop. The window
/// is made visible with a size of 0, 0, so that it will trap
/// global broadcast messages.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void WindowThreadProc()
{
try
{
Initialize();
s_eventWindowReady.Set();
if (_windowHandle != IntPtr.Zero)
{
Interop.User32.MSG msg = new Interop.User32.MSG();
bool keepRunning = true;
// Blocking on a GetMessage() call prevents the EE from being able to unwind
// this thread properly (e.g. during AppDomainUnload). So, we use PeekMessage()
// and sleep so we always block in managed code instead.
while (keepRunning)
{
int ret = Interop.User32.MsgWaitForMultipleObjectsEx(0, IntPtr.Zero, 100, Interop.User32.QS_ALLINPUT, Interop.User32.MWMO_INPUTAVAILABLE);
if (ret == Interop.User32.WAIT_TIMEOUT)
{
Thread.Sleep(1);
}
else
{
while (Interop.User32.PeekMessageW(ref msg, IntPtr.Zero, 0, 0, Interop.User32.PM_REMOVE))
{
if (msg.message == Interop.User32.WM_QUIT)
{
keepRunning = false;
break;
}
Interop.User32.TranslateMessage(ref msg);
Interop.User32.DispatchMessageW(ref msg);
}
}
}
}
OnShutdown(s_onEventsThreadShutdownEvent);
}
catch (Exception e)
{
// In case something very very wrong happend during the creation action.
// This will unblock the calling thread.
s_eventWindowReady.Set();
if (!((e is ThreadInterruptedException) || (e is ThreadAbortException)))
{
Debug.Fail("Unexpected thread exception in system events window thread proc", e.ToString());
}
}
Dispose();
if (s_eventThreadTerminated != null)
{
s_eventThreadTerminated.Set();
}
}
// A class that helps fire events on the right thread.
private class SystemEventInvokeInfo
{
private SynchronizationContext _syncContext; // the context that we'll use to fire against.
private Delegate _delegate; // the delegate we'll fire. This is a weak ref so we don't hold object in memory.
public SystemEventInvokeInfo(Delegate d)
{
_delegate = d;
_syncContext = AsyncOperationManager.SynchronizationContext;
}
// fire the given event with the given params.
public void Invoke(bool checkFinalization, params object[] args)
{
try
{
// If we didn't get call back invoke directly.
if (_syncContext == null)
{
InvokeCallback(args);
}
else
{
// otherwise tell the context to do it for us.
_syncContext.Send(new SendOrPostCallback(InvokeCallback), args);
}
}
catch (InvalidAsynchronousStateException)
{
// if the synch context is invalid -- do the invoke directly for app compat.
// If the app's shutting down, don't fire the event (unless it's shutdown).
if (!checkFinalization || !AppDomain.CurrentDomain.IsFinalizingForUnload())
{
InvokeCallback(args);
}
}
}
// our delegate method that the SyncContext will call on.
private void InvokeCallback(object arg)
{
_delegate.DynamicInvoke((object[])arg);
}
public override bool Equals(object other)
{
SystemEventInvokeInfo otherInvoke = other as SystemEventInvokeInfo;
if (otherInvoke == null)
{
return false;
}
return otherInvoke._delegate.Equals(_delegate);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using Patterns.Logging;
namespace SocketHttpListener.Net
{
sealed class HttpConnection
{
static AsyncCallback onread_cb = new AsyncCallback(OnRead);
const int BufferSize = 8192;
Socket sock;
Stream stream;
EndPointListener epl;
MemoryStream ms;
byte[] buffer;
HttpListenerContext context;
StringBuilder current_line;
ListenerPrefix prefix;
RequestStream i_stream;
ResponseStream o_stream;
bool chunked;
int reuses;
bool context_bound;
bool secure;
int s_timeout = 300000; // 90k ms for first request, 15k ms from then on
Timer timer;
IPEndPoint local_ep;
HttpListener last_listener;
int[] client_cert_errors;
X509Certificate cert;
SslStream ssl_stream;
private ILogger _logger;
public HttpConnection(ILogger logger, Socket sock, EndPointListener epl, bool secure, X509Certificate cert)
{
_logger = logger;
this.sock = sock;
this.epl = epl;
this.secure = secure;
this.cert = cert;
if (secure == false)
{
stream = new NetworkStream(sock, false);
}
else
{
//ssl_stream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
//{
// if (c == null)
// return true;
// var c2 = c as X509Certificate2;
// if (c2 == null)
// c2 = new X509Certificate2(c.GetRawCertData());
// client_cert = c2;
// client_cert_errors = new int[] { (int)e };
// return true;
//});
//stream = ssl_stream.AuthenticatedStream;
ssl_stream = new SslStream(new NetworkStream(sock, false), false);
ssl_stream.AuthenticateAsServer(cert);
stream = ssl_stream;
}
timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
Init();
}
public Stream Stream
{
get
{
return stream;
}
}
internal int[] ClientCertificateErrors
{
get { return client_cert_errors; }
}
void Init()
{
if (ssl_stream != null)
{
//ssl_stream.AuthenticateAsServer(client_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
}
context_bound = false;
i_stream = null;
o_stream = null;
prefix = null;
chunked = false;
ms = new MemoryStream();
position = 0;
input_state = InputState.RequestLine;
line_state = LineState.None;
context = new HttpListenerContext(this, _logger);
}
public bool IsClosed
{
get { return (sock == null); }
}
public int Reuses
{
get { return reuses; }
}
public IPEndPoint LocalEndPoint
{
get
{
if (local_ep != null)
return local_ep;
local_ep = (IPEndPoint)sock.LocalEndPoint;
return local_ep;
}
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)sock.RemoteEndPoint; }
}
public bool IsSecure
{
get { return secure; }
}
public ListenerPrefix Prefix
{
get { return prefix; }
set { prefix = value; }
}
void OnTimeout(object unused)
{
//_logger.Debug("HttpConnection keep alive timer fired. ConnectionId: {0}.", _connectionId);
CloseSocket();
Unbind();
}
public void BeginReadRequest()
{
if (buffer == null)
buffer = new byte[BufferSize];
try
{
//if (reuses == 1)
// s_timeout = 15000;
timer.Change(s_timeout, Timeout.Infinite);
stream.BeginRead(buffer, 0, BufferSize, onread_cb, this);
}
catch
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
CloseSocket();
Unbind();
}
}
public RequestStream GetRequestStream(bool chunked, long contentlength)
{
if (i_stream == null)
{
byte[] buffer = ms.GetBuffer();
int length = (int)ms.Length;
ms = null;
if (chunked)
{
this.chunked = true;
//context.Response.SendChunked = true;
i_stream = new ChunkedInputStream(context, stream, buffer, position, length - position);
}
else {
i_stream = new RequestStream(stream, buffer, position, length - position, contentlength);
}
}
return i_stream;
}
public ResponseStream GetResponseStream()
{
// TODO: can we get this stream before reading the input?
if (o_stream == null)
{
HttpListener listener = context.Listener;
if (listener == null)
return new ResponseStream(stream, context.Response, true);
o_stream = new ResponseStream(stream, context.Response, listener.IgnoreWriteExceptions);
}
return o_stream;
}
static void OnRead(IAsyncResult ares)
{
HttpConnection cnc = (HttpConnection)ares.AsyncState;
cnc.OnReadInternal(ares);
}
void OnReadInternal(IAsyncResult ares)
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
int nread = -1;
try
{
nread = stream.EndRead(ares);
ms.Write(buffer, 0, nread);
if (ms.Length > 32768)
{
SendError("Bad request", 400);
Close(true);
return;
}
}
catch (Exception ex)
{
OnReadInternalException(ms, ex);
return;
}
if (nread == 0)
{
//if (ms.Length > 0)
// SendError (); // Why bother?
CloseSocket();
Unbind();
return;
}
if (ProcessInput(ms))
{
if (!context.HaveError)
context.Request.FinishInitialization();
if (context.HaveError)
{
SendError();
Close(true);
return;
}
if (!epl.BindContext(context))
{
SendError("Invalid host", 400);
Close(true);
return;
}
HttpListener listener = context.Listener;
if (last_listener != listener)
{
RemoveConnection();
listener.AddConnection(this);
last_listener = listener;
}
context_bound = true;
listener.RegisterContext(context);
return;
}
try
{
stream.BeginRead(buffer, 0, BufferSize, onread_cb, this);
}
catch (IOException ex)
{
OnReadInternalException(ms, ex);
}
}
private void OnReadInternalException(MemoryStream ms, Exception ex)
{
//_logger.ErrorException("Error in HttpConnection.OnReadInternal", ex);
if (ms != null && ms.Length > 0)
SendError();
if (sock != null)
{
CloseSocket();
Unbind();
}
}
void RemoveConnection()
{
if (last_listener == null)
epl.RemoveConnection(this);
else
last_listener.RemoveConnection(this);
}
enum InputState
{
RequestLine,
Headers
}
enum LineState
{
None,
CR,
LF
}
InputState input_state = InputState.RequestLine;
LineState line_state = LineState.None;
int position;
// true -> done processing
// false -> need more input
bool ProcessInput(MemoryStream ms)
{
byte[] buffer = ms.GetBuffer();
int len = (int)ms.Length;
int used = 0;
string line;
while (true)
{
if (context.HaveError)
return true;
if (position >= len)
break;
try
{
line = ReadLine(buffer, position, len - position, ref used);
position += used;
}
catch
{
context.ErrorMessage = "Bad request";
context.ErrorStatus = 400;
return true;
}
if (line == null)
break;
if (line == "")
{
if (input_state == InputState.RequestLine)
continue;
current_line = null;
ms = null;
return true;
}
if (input_state == InputState.RequestLine)
{
context.Request.SetRequestLine(line);
input_state = InputState.Headers;
}
else
{
try
{
context.Request.AddHeader(line);
}
catch (Exception e)
{
context.ErrorMessage = e.Message;
context.ErrorStatus = 400;
return true;
}
}
}
if (used == len)
{
ms.SetLength(0);
position = 0;
}
return false;
}
string ReadLine(byte[] buffer, int offset, int len, ref int used)
{
if (current_line == null)
current_line = new StringBuilder(128);
int last = offset + len;
used = 0;
for (int i = offset; i < last && line_state != LineState.LF; i++)
{
used++;
byte b = buffer[i];
if (b == 13)
{
line_state = LineState.CR;
}
else if (b == 10)
{
line_state = LineState.LF;
}
else {
current_line.Append((char)b);
}
}
string result = null;
if (line_state == LineState.LF)
{
line_state = LineState.None;
result = current_line.ToString();
current_line.Length = 0;
}
return result;
}
public void SendError(string msg, int status)
{
try
{
HttpListenerResponse response = context.Response;
response.StatusCode = status;
response.ContentType = "text/html";
string description = HttpListenerResponse.GetStatusDescription(status);
string str;
if (msg != null)
str = String.Format("<h1>{0} ({1})</h1>", description, msg);
else
str = String.Format("<h1>{0}</h1>", description);
byte[] error = context.Response.ContentEncoding.GetBytes(str);
response.Close(error, false);
}
catch
{
// response was already closed
}
}
public void SendError()
{
SendError(context.ErrorMessage, context.ErrorStatus);
}
void Unbind()
{
if (context_bound)
{
epl.UnbindContext(context);
context_bound = false;
}
}
public void Close()
{
Close(false);
}
private void CloseSocket()
{
if (sock == null)
return;
try
{
sock.Close();
}
catch
{
}
finally
{
sock = null;
}
RemoveConnection();
}
internal void Close(bool force_close)
{
if (sock != null)
{
if (!context.Request.IsWebSocketRequest || force_close)
{
Stream st = GetResponseStream();
if (st != null)
st.Close();
o_stream = null;
}
}
if (sock != null)
{
force_close |= !context.Request.KeepAlive;
if (!force_close)
force_close = (context.Response.Headers["connection"] == "close");
/*
if (!force_close) {
// bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
// status_code == 413 || status_code == 414 || status_code == 500 ||
// status_code == 503);
force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
}
*/
if (!force_close && context.Request.FlushInput())
{
if (chunked && context.Response.ForceCloseChunked == false)
{
// Don't close. Keep working.
reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
Socket s = sock;
sock = null;
try
{
if (s != null)
s.Shutdown(SocketShutdown.Both);
}
catch
{
}
finally
{
if (s != null)
s.Close();
}
Unbind();
RemoveConnection();
return;
}
}
}
}
| |
//
// System.Web.UI.WebControls.Parameter
//
// Authors:
// Ben Maurer (bmaurer@users.sourceforge.net)
// Sanjay Gupta (gsanjay@novell.com)
//
// (C) 2003 Ben Maurer
// (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.
//
#if NET_2_0
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.ComponentModel;
namespace System.Web.UI.WebControls {
[DefaultPropertyAttribute ("DefaultValue")]
public class Parameter : ICloneable, IStateManager {
public Parameter () : base ()
{
}
protected Parameter (Parameter original)
{
this.DefaultValue = original.DefaultValue;
this.Direction = original.Direction;
this.ConvertEmptyStringToNull = original.ConvertEmptyStringToNull;
this.Type = original.Type;
this.Name = original.Name;
}
public Parameter (string name)
{
this.Name = name;
}
public Parameter(string name, TypeCode type) : this (name)
{
this.Type = type;
}
public Parameter (string name, TypeCode type, string defaultValue) : this (name, type)
{
this.DefaultValue = defaultValue;
}
protected virtual Parameter Clone ()
{
return new Parameter (this);
}
protected void OnParameterChanged ()
{
if (_owner != null)
_owner.CallOnParameterChanged ();
}
protected virtual void LoadViewState (object savedState)
{
ViewState.LoadViewState (savedState);
}
protected virtual object SaveViewState ()
{
return ViewState.SaveViewState ();
}
protected virtual void TrackViewState ()
{
isTrackingViewState = true;
if (viewState != null)
viewState.TrackViewState ();
}
object ICloneable.Clone ()
{
return this.Clone ();
}
void IStateManager.LoadViewState (object savedState)
{
this.LoadViewState (savedState);
}
object IStateManager.SaveViewState ()
{
return this.SaveViewState ();
}
void IStateManager.TrackViewState ()
{
this.TrackViewState ();
}
bool IStateManager.IsTrackingViewState {
get { return this.IsTrackingViewState; }
}
public override string ToString ()
{
return Name;
}
[WebCategoryAttribute ("Parameter"), DefaultValueAttribute (""),
WebSysDescriptionAttribute ("Default value to be used in case value is null.") ]
public string DefaultValue {
get {
return ViewState ["DefaultValue"] as string;
}
set {
if (DefaultValue != value) {
ViewState ["DefaultValue"] = value;
OnParameterChanged ();
}
}
}
[WebCategoryAttribute ("Parameter"), DefaultValueAttribute ("Input"),
WebSysDescriptionAttribute ("Parameter's direction.")]
public ParameterDirection Direction
{
get {
object o = ViewState ["Direction"];
if (o != null)
return (ParameterDirection) o;
return ParameterDirection.Input;
}
set {
if (Direction != value) {
ViewState ["Direction"] = value;
OnParameterChanged ();
}
}
}
[WebCategoryAttribute ("Parameter"), DefaultValueAttribute (""),
WebSysDescriptionAttribute ("Parameter's name.")]
public string Name
{
get {
string s = ViewState ["Name"] as string;
if (s != null)
return s;
return "";
}
set {
if (Name != value) {
ViewState ["Name"] = value;
OnParameterChanged ();
}
}
}
[WebCategoryAttribute ("Parameter"), DefaultValueAttribute (true),
WebSysDescriptionAttribute ("Checks whether an empty string is treated as a null value.")]
public bool ConvertEmptyStringToNull
{
get {
object o = ViewState["ConvertEmptyStringToNull"];
if (o != null)
return (bool) o;
return true;
}
set {
if (ConvertEmptyStringToNull != value) {
ViewState["ConvertEmptyStringToNull"] = value;
OnParameterChanged ();
}
}
}
[DefaultValueAttribute (TypeCode.Object)]
[WebCategoryAttribute ("Parameter"),
WebSysDescriptionAttribute("Represents type of the parameter.")]
public TypeCode Type
{
get {
object o = ViewState ["Type"];
if (o != null)
return (TypeCode) o;
return TypeCode.Object;
}
set {
if (Type != value) {
ViewState ["Type"] = value;
OnParameterChanged ();
}
}
}
StateBag viewState;
[BrowsableAttribute (false),
DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
protected StateBag ViewState {
get {
if (viewState == null) {
viewState = new StateBag ();
if (IsTrackingViewState)
viewState.TrackViewState ();
}
return viewState;
}
}
bool isTrackingViewState = false;
protected bool IsTrackingViewState {
get { return isTrackingViewState; }
}
protected virtual object Evaluate (HttpContext context, Control control)
{
return this.DefaultValue;
}
internal object GetValue (HttpContext context, Control control)
{
object oldValue = ViewState ["ParameterValue"];
object newValue = ConvertValue (Evaluate (context, control));
if (newValue == null)
newValue = ConvertValue (DefaultValue);
if (!object.Equals (oldValue, newValue)) {
ViewState ["ParameterValue"] = newValue;
OnParameterChanged ();
}
return newValue;
}
object ConvertValue (object val)
{
if (val == null) return null;
if (ConvertEmptyStringToNull && val.Equals (string.Empty))
return null;
return Convert.ChangeType (val, Type);
}
protected internal virtual void SetDirty()
{
ViewState.SetDirty ();
}
private ParameterCollection _owner;
internal void SetOwnerCollection (ParameterCollection own)
{
_owner = own;
}
}
}
#endif
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.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
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Versioning;
using FluentMigrator.Runner.VersionTableInfo;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Conventions;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using JetBrains.Annotations;
namespace FluentMigrator.Runner
{
public class VersionLoader : IVersionLoader
{
[NotNull]
private readonly IMigrationProcessor _processor;
private readonly IConventionSet _conventionSet;
private bool _versionSchemaMigrationAlreadyRun;
private bool _versionMigrationAlreadyRun;
private bool _versionUniqueMigrationAlreadyRun;
private bool _versionDescriptionMigrationAlreadyRun;
private IVersionInfo _versionInfo;
private IMigrationRunnerConventions Conventions { get; set; }
[CanBeNull]
[Obsolete]
protected IAssemblyCollection Assemblies { get; set; }
public IVersionTableMetaData VersionTableMetaData { get; }
[NotNull]
public IMigrationRunner Runner { get; set; }
public VersionSchemaMigration VersionSchemaMigration { get; }
public IMigration VersionMigration { get; }
public IMigration VersionUniqueMigration { get; }
public IMigration VersionDescriptionMigration { get; }
[Obsolete]
internal VersionLoader(
[NotNull] IMigrationRunner runner,
[NotNull] Assembly assembly,
[NotNull] IConventionSet conventionSet,
[NotNull] IMigrationRunnerConventions conventions,
[NotNull] IRunnerContext runnerContext)
: this(runner, new SingleAssembly(assembly), conventionSet, conventions, runnerContext)
{
}
[Obsolete]
internal VersionLoader(IMigrationRunner runner, IAssemblyCollection assemblies,
[NotNull] IConventionSet conventionSet,
[NotNull] IMigrationRunnerConventions conventions,
[NotNull] IRunnerContext runnerContext,
[CanBeNull] IVersionTableMetaData versionTableMetaData = null)
{
_conventionSet = conventionSet;
_processor = runner.Processor;
Runner = runner;
Assemblies = assemblies;
Conventions = conventions;
VersionTableMetaData = versionTableMetaData ?? CreateVersionTableMetaData(runnerContext);
VersionMigration = new VersionMigration(VersionTableMetaData);
VersionSchemaMigration = new VersionSchemaMigration(VersionTableMetaData);
VersionUniqueMigration = new VersionUniqueMigration(VersionTableMetaData);
VersionDescriptionMigration = new VersionDescriptionMigration(VersionTableMetaData);
VersionTableMetaData.ApplicationContext = runnerContext.ApplicationContext;
LoadVersionInfo();
}
public VersionLoader(
[NotNull] IProcessorAccessor processorAccessor,
[NotNull] IConventionSet conventionSet,
[NotNull] IMigrationRunnerConventions conventions,
[NotNull] IVersionTableMetaData versionTableMetaData,
[NotNull] IMigrationRunner runner)
{
_conventionSet = conventionSet;
_processor = processorAccessor.Processor;
Runner = runner;
Conventions = conventions;
VersionTableMetaData = versionTableMetaData;
VersionMigration = new VersionMigration(VersionTableMetaData);
VersionSchemaMigration = new VersionSchemaMigration(VersionTableMetaData);
VersionUniqueMigration = new VersionUniqueMigration(VersionTableMetaData);
VersionDescriptionMigration = new VersionDescriptionMigration(VersionTableMetaData);
LoadVersionInfo();
}
public void UpdateVersionInfo(long version)
{
UpdateVersionInfo(version, null);
}
public void UpdateVersionInfo(long version, string description)
{
var dataExpression = new InsertDataExpression();
dataExpression.Rows.Add(CreateVersionInfoInsertionData(version, description));
dataExpression.TableName = VersionTableMetaData.TableName;
dataExpression.SchemaName = VersionTableMetaData.SchemaName;
dataExpression.ExecuteWith(_processor);
}
[NotNull]
public IVersionTableMetaData GetVersionTableMetaData()
{
return VersionTableMetaData;
}
protected virtual InsertionDataDefinition CreateVersionInfoInsertionData(long version, string description)
{
return new InsertionDataDefinition
{
new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version),
new KeyValuePair<string, object>(VersionTableMetaData.AppliedOnColumnName, DateTime.UtcNow),
new KeyValuePair<string, object>(VersionTableMetaData.DescriptionColumnName, description),
};
}
public IVersionInfo VersionInfo
{
get => _versionInfo;
set => _versionInfo = value ?? throw new ArgumentException("Cannot set VersionInfo to null");
}
public bool AlreadyCreatedVersionSchema => string.IsNullOrEmpty(VersionTableMetaData.SchemaName) ||
_processor.SchemaExists(VersionTableMetaData.SchemaName);
public bool AlreadyCreatedVersionTable => _processor.TableExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName);
public bool AlreadyMadeVersionUnique => _processor.ColumnExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName, VersionTableMetaData.AppliedOnColumnName);
public bool AlreadyMadeVersionDescription => _processor.ColumnExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName, VersionTableMetaData.DescriptionColumnName);
public bool OwnsVersionSchema => VersionTableMetaData.OwnsSchema;
public void LoadVersionInfo()
{
if (!AlreadyCreatedVersionSchema && !_versionSchemaMigrationAlreadyRun)
{
Runner.Up(VersionSchemaMigration);
_versionSchemaMigrationAlreadyRun = true;
}
if (!AlreadyCreatedVersionTable && !_versionMigrationAlreadyRun)
{
Runner.Up(VersionMigration);
_versionMigrationAlreadyRun = true;
}
if (!AlreadyMadeVersionUnique && !_versionUniqueMigrationAlreadyRun)
{
Runner.Up(VersionUniqueMigration);
_versionUniqueMigrationAlreadyRun = true;
}
if (!AlreadyMadeVersionDescription && !_versionDescriptionMigrationAlreadyRun)
{
Runner.Up(VersionDescriptionMigration);
_versionDescriptionMigrationAlreadyRun = true;
}
_versionInfo = new VersionInfo();
if (!AlreadyCreatedVersionTable) return;
var dataSet = _processor.ReadTableData(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName);
foreach (DataRow row in dataSet.Tables[0].Rows)
{
_versionInfo.AddAppliedMigration(long.Parse(row[VersionTableMetaData.ColumnName].ToString()));
}
}
public void RemoveVersionTable()
{
var expression = new DeleteTableExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName };
expression.ExecuteWith(_processor);
if (OwnsVersionSchema && !string.IsNullOrEmpty(VersionTableMetaData.SchemaName))
{
var schemaExpression = new DeleteSchemaExpression { SchemaName = VersionTableMetaData.SchemaName };
schemaExpression.ExecuteWith(_processor);
}
}
public void DeleteVersion(long version)
{
var expression = new DeleteDataExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName };
expression.Rows.Add(new DeletionDataDefinition
{
new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version)
});
expression.ExecuteWith(_processor);
}
[Obsolete]
[NotNull]
private IVersionTableMetaData CreateVersionTableMetaData(IRunnerContext runnerContext)
{
var type = Assemblies?.Assemblies.GetVersionTableMetaDataType(Conventions, runnerContext)
?? typeof(DefaultVersionTableMetaData);
var instance = (IVersionTableMetaData) Activator.CreateInstance(type);
if (instance is ISchemaExpression schemaExpression)
{
_conventionSet.SchemaConvention?.Apply(schemaExpression);
}
return instance;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using OrleansAWSUtils.Streams;
using AWSUtils.Tests.StorageTests;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
using OrleansAWSUtils.Storage;
using Orleans.Configuration;
using Orleans.Internal;
namespace AWSUtils.Tests.Streaming
{
[TestCategory("AWS"), TestCategory("SQS")]
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class SQSAdapterTests : IAsyncLifetime
{
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture fixture;
private const int NumBatches = 20;
private const int NumMessagesPerBatch = 20;
private readonly string clusterId;
public static readonly string SQS_STREAM_PROVIDER_NAME = "SQSAdapterTests";
private static readonly SafeRandom Random = new SafeRandom();
public SQSAdapterTests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
if (!AWSTestConstants.IsSqsAvailable)
{
throw new SkipException("Empty connection string");
}
this.output = output;
this.fixture = fixture;
this.clusterId = MakeClusterId();
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
if (!string.IsNullOrWhiteSpace(AWSTestConstants.DefaultSQSConnectionString))
{
await SQSStreamProviderUtils.DeleteAllUsedQueues(
SQS_STREAM_PROVIDER_NAME,
this.clusterId,
AWSTestConstants.DefaultSQSConnectionString,
NullLoggerFactory.Instance);
}
}
[SkippableFact]
public async Task SendAndReceiveFromSQS()
{
var options = new SqsOptions
{
ConnectionString = AWSTestConstants.DefaultSQSConnectionString,
};
var adapterFactory = new SQSAdapterFactory(SQS_STREAM_PROVIDER_NAME, options, new HashRingStreamQueueMapperOptions(), new SimpleQueueCacheOptions(), null, Options.Create(new ClusterOptions()), null, null);
adapterFactory.Init();
await SendAndReceiveFromQueueAdapter(adapterFactory);
}
private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory)
{
IQueueAdapter adapter = await adapterFactory.CreateAdapter();
IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache();
// Create receiver per queue
IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper();
Dictionary<QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver);
Dictionary<QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache);
await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5))));
// test using 2 streams
Guid streamId1 = Guid.NewGuid();
Guid streamId2 = Guid.NewGuid();
int receivedBatches = 0;
var streamsPerQueue = new ConcurrentDictionary<QueueId, HashSet<IStreamIdentity>>();
// reader threads (at most 2 active queues because only two streams)
var work = new List<Task>();
foreach (KeyValuePair<QueueId, IQueueAdapterReceiver> receiverKvp in receivers)
{
QueueId queueId = receiverKvp.Key;
var receiver = receiverKvp.Value;
var qCache = caches[queueId];
Task task = Task.Factory.StartNew(() =>
{
while (receivedBatches < NumBatches)
{
var messages = receiver.GetQueueMessagesAsync(SQSStorage.MAX_NUMBER_OF_MESSAGE_TO_PEAK).Result.ToArray();
if (!messages.Any())
{
continue;
}
foreach (var message in messages.Cast<SQSBatchContainer>())
{
streamsPerQueue.AddOrUpdate(queueId,
id => new HashSet<IStreamIdentity> { new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()) },
(id, set) =>
{
set.Add(new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()));
return set;
});
output.WriteLine("Queue {0} received message on stream {1}", queueId,
message.StreamGuid);
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<int>().Count()); // "Half the events were ints"
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<string>().Count()); // "Half the events were strings"
}
Interlocked.Add(ref receivedBatches, messages.Length);
qCache.AddToCache(messages);
}
});
work.Add(task);
}
// send events
List<object> events = CreateEvents(NumMessagesPerBatch);
work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches)
.Select(i => i % 2 == 0 ? streamId1 : streamId2)
.ToList()
.ForEach(streamId =>
adapter.QueueMessageBatchAsync(streamId, streamId.ToString(),
events.Take(NumMessagesPerBatch).ToArray(), null, RequestContextExtensions.Export(this.fixture.SerializationManager)).Wait())));
await Task.WhenAll(work);
// Make sure we got back everything we sent
Assert.Equal(NumBatches, receivedBatches);
// check to see if all the events are in the cache and we can enumerate through them
StreamSequenceToken firstInCache = new EventSequenceTokenV2(0);
foreach (KeyValuePair<QueueId, HashSet<IStreamIdentity>> kvp in streamsPerQueue)
{
var receiver = receivers[kvp.Key];
var qCache = caches[kvp.Key];
foreach (IStreamIdentity streamGuid in kvp.Value)
{
// read all messages in cache for stream
IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache);
int messageCount = 0;
StreamSequenceToken tenthInCache = null;
StreamSequenceToken lastToken = firstInCache;
while (cursor.MoveNext())
{
Exception ex;
messageCount++;
IBatchContainer batch = cursor.GetCurrent(out ex);
output.WriteLine("Token: {0}", batch.SequenceToken);
Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}");
lastToken = batch.SequenceToken;
if (messageCount == 10)
{
tenthInCache = batch.SequenceToken;
}
}
output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
Assert.Equal(NumBatches / 2, messageCount);
Assert.NotNull(tenthInCache);
// read all messages from the 10th
cursor = qCache.GetCacheCursor(streamGuid, tenthInCache);
messageCount = 0;
while (cursor.MoveNext())
{
messageCount++;
}
output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1)
Assert.Equal(expected, messageCount);
}
}
}
private List<object> CreateEvents(int count)
{
return Enumerable.Range(0, count).Select(i =>
{
if (i % 2 == 0)
{
return Random.Next(int.MaxValue) as object;
}
return Random.Next(int.MaxValue).ToString(CultureInfo.InvariantCulture);
}).ToList();
}
internal static string MakeClusterId()
{
const string DeploymentIdFormat = "cluster-{0}";
string now = DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff");
return String.Format(DeploymentIdFormat, now);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Hard coded images referenced from C++ code
//------------------------------------------------------------------------------
// editor/SelectHandle.png
// editor/DefaultHandle.png
// editor/LockedHandle.png
//------------------------------------------------------------------------------
// Functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Mission Editor
//------------------------------------------------------------------------------
function Editor::create()
{
// Not much to do here, build it and they will come...
// Only one thing... the editor is a gui control which
// expect the Canvas to exist, so it must be constructed
// before the editor.
new EditManager(Editor)
{
profile = "GuiContentProfile";
horizSizing = "right";
vertSizing = "top";
position = "0 0";
extent = "640 480";
minExtent = "8 8";
visible = "1";
setFirstResponder = "0";
modal = "1";
helpTag = "0";
open = false;
};
}
function Editor::getUndoManager(%this)
{
if ( !isObject( %this.undoManager ) )
{
/// This is the global undo manager used by all
/// of the mission editor sub-editors.
%this.undoManager = new UndoManager( EUndoManager )
{
numLevels = 200;
};
}
return %this.undoManager;
}
function Editor::setUndoManager(%this, %undoMgr)
{
%this.undoManager = %undoMgr;
}
function Editor::onAdd(%this)
{
// Ignore Replicated fxStatic Instances.
EWorldEditor.ignoreObjClass("fxShapeReplicatedStatic");
}
function Editor::checkActiveLoadDone()
{
if(isObject(EditorGui) && EditorGui.loadingMission)
{
Canvas.setContent(EditorGui);
EditorGui.loadingMission = false;
return true;
}
return false;
}
//------------------------------------------------------------------------------
function toggleEditor(%make)
{
if (Canvas.isFullscreen())
{
MessageBoxOK("Windowed Mode Required", "Please switch to windowed mode to access the Mission Editor.");
return;
}
if (%make)
{
%timerId = startPrecisionTimer();
if( $InGuiEditor )
GuiEdit();
if( !$missionRunning )
{
// Flag saying, when level is chosen, launch it with the editor open.
//ChooseLevelDlg.launchInEditor = true;
//Canvas.pushDialog( ChooseLevelDlg );
// TODO: Handle this here.
}
else
{
pushInstantGroup();
if ( !isObject( Editor ) )
{
Editor::create();
$MissionCleanupGroup.add( Editor );
$MissionCleanupGroup.add( Editor.getUndoManager() );
}
if( EditorIsActive() )
{
if (theLevelInfo.type $= "DemoScene")
{
commandToServer('dropPlayerAtCamera');
Editor.close("SceneGui");
}
else
{
Editor.close("PlayGui");
}
}
else
{
if ( !$GuiEditorBtnPressed )
{
canvas.pushDialog( EditorLoadingGui );
canvas.repaint();
}
else
{
$GuiEditorBtnPressed = false;
}
Editor.open();
// Cancel the scheduled event to prevent
// the level from cycling after it's duration
// has elapsed.
cancel($Game::Schedule);
if (theLevelInfo.type $= "DemoScene")
commandToServer('dropCameraAtPlayer', true);
canvas.popDialog(EditorLoadingGui);
}
popInstantGroup();
}
%elapsed = stopPrecisionTimer( %timerId );
warn( "Time spent in toggleEditor() : " @ %elapsed / 1000.0 @ " s" );
}
}
//------------------------------------------------------------------------------
// The editor action maps are defined in editor.bind.cs
GlobalActionMap.bind(keyboard, "f11", toggleEditor);
// The scenario:
// The editor is open and the user closes the level by any way other than
// the file menu ( exit level ), eg. typing disconnect() in the console.
//
// The problem:
// Editor::close() is not called in this scenario which means onEditorDisable
// is not called on objects which hook into it and also gEditingMission will no
// longer be valid.
//
// The solution:
// Override the stock disconnect() function which is in game scripts from here
// in tools so we avoid putting our code in there.
//
// Disclaimer:
// If you think of a better way to do this feel free. The thing which could
// be dangerous about this is that no one will ever realize this code overriding
// a fairly standard and core game script from a somewhat random location.
// If it 'did' have unforscene sideeffects who would ever find it?
package EditorDisconnectOverride
{
function disconnect()
{
if ( isObject( Editor ) && Editor.isEditorEnabled() )
{
if (isObject( MainMenuGui ))
Editor.close("MainMenuGui");
}
Parent::disconnect();
}
};
activatePackage( EditorDisconnectOverride );
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Rendering.Utilities;
using Avalonia.Utilities;
using Avalonia.Visuals.Media.Imaging;
using SkiaSharp;
namespace Avalonia.Skia
{
/// <summary>
/// Skia based drawing context.
/// </summary>
public class DrawingContextImpl : IDrawingContextImpl
{
private readonly IDisposable[] _disposables;
private readonly Vector _dpi;
private readonly Stack<PaintWrapper> _maskStack = new Stack<PaintWrapper>();
private readonly Stack<double> _opacityStack = new Stack<double>();
private readonly Matrix? _postTransform;
private readonly IVisualBrushRenderer _visualBrushRenderer;
private double _currentOpacity = 1.0f;
private readonly bool _canTextUseLcdRendering;
private Matrix _currentTransform;
private GRContext _grContext;
/// <summary>
/// Context create info.
/// </summary>
public struct CreateInfo
{
/// <summary>
/// Canvas to draw to.
/// </summary>
public SKCanvas Canvas;
/// <summary>
/// Dpi of drawings.
/// </summary>
public Vector Dpi;
/// <summary>
/// Visual brush renderer.
/// </summary>
public IVisualBrushRenderer VisualBrushRenderer;
/// <summary>
/// Render text without Lcd rendering.
/// </summary>
public bool DisableTextLcdRendering;
/// <summary>
/// GPU-accelerated context (optional)
/// </summary>
public GRContext GrContext;
}
/// <summary>
/// Create new drawing context.
/// </summary>
/// <param name="createInfo">Create info.</param>
/// <param name="disposables">Array of elements to dispose after drawing has finished.</param>
public DrawingContextImpl(CreateInfo createInfo, params IDisposable[] disposables)
{
_dpi = createInfo.Dpi;
_visualBrushRenderer = createInfo.VisualBrushRenderer;
_disposables = disposables;
_canTextUseLcdRendering = !createInfo.DisableTextLcdRendering;
_grContext = createInfo.GrContext;
Canvas = createInfo.Canvas;
if (Canvas == null)
{
throw new ArgumentException("Invalid create info - no Canvas provided", nameof(createInfo));
}
if (!_dpi.NearlyEquals(SkiaPlatform.DefaultDpi))
{
_postTransform =
Matrix.CreateScale(_dpi.X / SkiaPlatform.DefaultDpi.X, _dpi.Y / SkiaPlatform.DefaultDpi.Y);
}
Transform = Matrix.Identity;
}
/// <summary>
/// Skia canvas.
/// </summary>
public SKCanvas Canvas { get; }
/// <inheritdoc />
public void Clear(Color color)
{
Canvas.Clear(color.ToSKColor());
}
/// <inheritdoc />
public void DrawImage(IRef<IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode)
{
var drawableImage = (IDrawableBitmapImpl)source.Item;
var s = sourceRect.ToSKRect();
var d = destRect.ToSKRect();
using (var paint =
new SKPaint
{
Color = new SKColor(255, 255, 255, (byte)(255 * opacity * _currentOpacity))
})
{
paint.FilterQuality = GetInterpolationMode(bitmapInterpolationMode);
drawableImage.Draw(this, s, d, paint);
}
}
private static SKFilterQuality GetInterpolationMode(BitmapInterpolationMode interpolationMode)
{
switch (interpolationMode)
{
case BitmapInterpolationMode.LowQuality:
return SKFilterQuality.Low;
case BitmapInterpolationMode.MediumQuality:
return SKFilterQuality.Medium;
case BitmapInterpolationMode.HighQuality:
return SKFilterQuality.High;
case BitmapInterpolationMode.Default:
return SKFilterQuality.None;
default:
throw new ArgumentOutOfRangeException(nameof(interpolationMode), interpolationMode, null);
}
}
/// <inheritdoc />
public void DrawImage(IRef<IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect)
{
PushOpacityMask(opacityMask, opacityMaskRect);
DrawImage(source, 1, new Rect(0, 0, source.Item.PixelSize.Width, source.Item.PixelSize.Height), destRect, BitmapInterpolationMode.Default);
PopOpacityMask();
}
/// <inheritdoc />
public void DrawLine(Pen pen, Point p1, Point p2)
{
using (var paint = CreatePaint(pen, new Size(Math.Abs(p2.X - p1.X), Math.Abs(p2.Y - p1.Y))))
{
Canvas.DrawLine((float) p1.X, (float) p1.Y, (float) p2.X, (float) p2.Y, paint.Paint);
}
}
/// <inheritdoc />
public void DrawGeometry(IBrush brush, Pen pen, IGeometryImpl geometry)
{
var impl = (GeometryImpl) geometry;
var size = geometry.Bounds.Size;
using (var fill = brush != null ? CreatePaint(brush, size) : default(PaintWrapper))
using (var stroke = pen?.Brush != null ? CreatePaint(pen, size) : default(PaintWrapper))
{
if (fill.Paint != null)
{
Canvas.DrawPath(impl.EffectivePath, fill.Paint);
}
if (stroke.Paint != null)
{
Canvas.DrawPath(impl.EffectivePath, stroke.Paint);
}
}
}
/// <inheritdoc />
public void DrawRectangle(Pen pen, Rect rect, float cornerRadius = 0)
{
using (var paint = CreatePaint(pen, rect.Size))
{
var rc = rect.ToSKRect();
if (Math.Abs(cornerRadius) < float.Epsilon)
{
Canvas.DrawRect(rc, paint.Paint);
}
else
{
Canvas.DrawRoundRect(rc, cornerRadius, cornerRadius, paint.Paint);
}
}
}
/// <inheritdoc />
public void FillRectangle(IBrush brush, Rect rect, float cornerRadius = 0)
{
using (var paint = CreatePaint(brush, rect.Size))
{
var rc = rect.ToSKRect();
if (Math.Abs(cornerRadius) < float.Epsilon)
{
Canvas.DrawRect(rc, paint.Paint);
}
else
{
Canvas.DrawRoundRect(rc, cornerRadius, cornerRadius, paint.Paint);
}
}
}
/// <inheritdoc />
public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text)
{
using (var paint = CreatePaint(foreground, text.Size))
{
var textImpl = (FormattedTextImpl) text;
textImpl.Draw(this, Canvas, origin.ToSKPoint(), paint, _canTextUseLcdRendering);
}
}
/// <inheritdoc />
public IRenderTargetBitmapImpl CreateLayer(Size size)
{
return CreateRenderTarget(size);
}
/// <inheritdoc />
public void PushClip(Rect clip)
{
Canvas.Save();
Canvas.ClipRect(clip.ToSKRect());
}
/// <inheritdoc />
public void PopClip()
{
Canvas.Restore();
}
/// <inheritdoc />
public void PushOpacity(double opacity)
{
_opacityStack.Push(_currentOpacity);
_currentOpacity *= opacity;
}
/// <inheritdoc />
public void PopOpacity()
{
_currentOpacity = _opacityStack.Pop();
}
/// <inheritdoc />
public virtual void Dispose()
{
if (_disposables == null)
{
return;
}
foreach (var disposable in _disposables)
{
disposable?.Dispose();
}
}
/// <inheritdoc />
public void PushGeometryClip(IGeometryImpl clip)
{
Canvas.Save();
Canvas.ClipPath(((GeometryImpl)clip).EffectivePath);
}
/// <inheritdoc />
public void PopGeometryClip()
{
Canvas.Restore();
}
/// <inheritdoc />
public void PushOpacityMask(IBrush mask, Rect bounds)
{
// TODO: This should be disposed
var paint = new SKPaint();
Canvas.SaveLayer(paint);
_maskStack.Push(CreatePaint(mask, bounds.Size));
}
/// <inheritdoc />
public void PopOpacityMask()
{
using (var paint = new SKPaint { BlendMode = SKBlendMode.DstIn })
{
Canvas.SaveLayer(paint);
using (var paintWrapper = _maskStack.Pop())
{
Canvas.DrawPaint(paintWrapper.Paint);
}
Canvas.Restore();
}
Canvas.Restore();
}
/// <inheritdoc />
public Matrix Transform
{
get { return _currentTransform; }
set
{
if (_currentTransform == value)
return;
_currentTransform = value;
var transform = value;
if (_postTransform.HasValue)
{
transform *= _postTransform.Value;
}
Canvas.SetMatrix(transform.ToSKMatrix());
}
}
/// <summary>
/// Configure paint wrapper for using gradient brush.
/// </summary>
/// <param name="paintWrapper">Paint wrapper.</param>
/// <param name="targetSize">Target size.</param>
/// <param name="gradientBrush">Gradient brush.</param>
private void ConfigureGradientBrush(ref PaintWrapper paintWrapper, Size targetSize, IGradientBrush gradientBrush)
{
var tileMode = gradientBrush.SpreadMethod.ToSKShaderTileMode();
var stopColors = gradientBrush.GradientStops.Select(s => s.Color.ToSKColor()).ToArray();
var stopOffsets = gradientBrush.GradientStops.Select(s => (float)s.Offset).ToArray();
switch (gradientBrush)
{
case ILinearGradientBrush linearGradient:
{
var start = linearGradient.StartPoint.ToPixels(targetSize).ToSKPoint();
var end = linearGradient.EndPoint.ToPixels(targetSize).ToSKPoint();
// would be nice to cache these shaders possibly?
using (var shader =
SKShader.CreateLinearGradient(start, end, stopColors, stopOffsets, tileMode))
{
paintWrapper.Paint.Shader = shader;
}
break;
}
case IRadialGradientBrush radialGradient:
{
var center = radialGradient.Center.ToPixels(targetSize).ToSKPoint();
var radius = (float)(radialGradient.Radius * targetSize.Width);
// TODO: There is no SetAlpha in SkiaSharp
//paint.setAlpha(128);
// would be nice to cache these shaders possibly?
using (var shader =
SKShader.CreateRadialGradient(center, radius, stopColors, stopOffsets, tileMode))
{
paintWrapper.Paint.Shader = shader;
}
break;
}
}
}
/// <summary>
/// Configure paint wrapper for using tile brush.
/// </summary>
/// <param name="paintWrapper">Paint wrapper.</param>
/// <param name="targetSize">Target size.</param>
/// <param name="tileBrush">Tile brush to use.</param>
/// <param name="tileBrushImage">Tile brush image.</param>
private void ConfigureTileBrush(ref PaintWrapper paintWrapper, Size targetSize, ITileBrush tileBrush, IDrawableBitmapImpl tileBrushImage)
{
var calc = new TileBrushCalculator(tileBrush, tileBrushImage.PixelSize.ToSize(_dpi), targetSize);
var intermediate = CreateRenderTarget(calc.IntermediateSize);
paintWrapper.AddDisposable(intermediate);
using (var context = intermediate.CreateDrawingContext(null))
{
var sourceRect = new Rect(tileBrushImage.PixelSize.ToSize(96));
var targetRect = new Rect(tileBrushImage.PixelSize.ToSize(_dpi));
context.Clear(Colors.Transparent);
context.PushClip(calc.IntermediateClip);
context.Transform = calc.IntermediateTransform;
context.DrawImage(
RefCountable.CreateUnownedNotClonable(tileBrushImage),
1,
sourceRect,
targetRect,
tileBrush.BitmapInterpolationMode);
context.PopClip();
}
var tileTransform =
tileBrush.TileMode != TileMode.None
? SKMatrix.MakeTranslation(-(float)calc.DestinationRect.X, -(float)calc.DestinationRect.Y)
: SKMatrix.MakeIdentity();
SKShaderTileMode tileX =
tileBrush.TileMode == TileMode.None
? SKShaderTileMode.Clamp
: tileBrush.TileMode == TileMode.FlipX || tileBrush.TileMode == TileMode.FlipXY
? SKShaderTileMode.Mirror
: SKShaderTileMode.Repeat;
SKShaderTileMode tileY =
tileBrush.TileMode == TileMode.None
? SKShaderTileMode.Clamp
: tileBrush.TileMode == TileMode.FlipY || tileBrush.TileMode == TileMode.FlipXY
? SKShaderTileMode.Mirror
: SKShaderTileMode.Repeat;
var image = intermediate.SnapshotImage();
paintWrapper.AddDisposable(image);
var paintTransform = default(SKMatrix);
SKMatrix.Concat(
ref paintTransform,
tileTransform,
SKMatrix.MakeScale((float)(96.0 / _dpi.X), (float)(96.0 / _dpi.Y)));
using (var shader = image.ToShader(tileX, tileY, paintTransform))
{
paintWrapper.Paint.Shader = shader;
}
}
/// <summary>
/// Configure paint wrapper to use visual brush.
/// </summary>
/// <param name="paintWrapper">Paint wrapper.</param>
/// <param name="visualBrush">Visual brush.</param>
/// <param name="visualBrushRenderer">Visual brush renderer.</param>
/// <param name="tileBrushImage">Tile brush image.</param>
private void ConfigureVisualBrush(ref PaintWrapper paintWrapper, IVisualBrush visualBrush, IVisualBrushRenderer visualBrushRenderer, ref IDrawableBitmapImpl tileBrushImage)
{
if (_visualBrushRenderer == null)
{
throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl.");
}
var intermediateSize = visualBrushRenderer.GetRenderTargetSize(visualBrush);
if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1)
{
var intermediate = CreateRenderTarget(intermediateSize);
using (var ctx = intermediate.CreateDrawingContext(visualBrushRenderer))
{
ctx.Clear(Colors.Transparent);
visualBrushRenderer.RenderVisualBrush(ctx, visualBrush);
}
tileBrushImage = intermediate;
paintWrapper.AddDisposable(tileBrushImage);
}
}
/// <summary>
/// Creates paint wrapper for given brush.
/// </summary>
/// <param name="brush">Source brush.</param>
/// <param name="targetSize">Target size.</param>
/// <returns>Paint wrapper for given brush.</returns>
internal PaintWrapper CreatePaint(IBrush brush, Size targetSize)
{
var paint = new SKPaint
{
IsStroke = false,
IsAntialias = true
};
var paintWrapper = new PaintWrapper(paint);
double opacity = brush.Opacity * _currentOpacity;
if (brush is ISolidColorBrush solid)
{
paint.Color = new SKColor(solid.Color.R, solid.Color.G, solid.Color.B, (byte) (solid.Color.A * opacity));
return paintWrapper;
}
paint.Color = new SKColor(255, 255, 255, (byte) (255 * opacity));
if (brush is IGradientBrush gradient)
{
ConfigureGradientBrush(ref paintWrapper, targetSize, gradient);
return paintWrapper;
}
var tileBrush = brush as ITileBrush;
var visualBrush = brush as IVisualBrush;
var tileBrushImage = default(IDrawableBitmapImpl);
if (visualBrush != null)
{
ConfigureVisualBrush(ref paintWrapper, visualBrush, _visualBrushRenderer, ref tileBrushImage);
}
else
{
tileBrushImage = (IDrawableBitmapImpl)(tileBrush as IImageBrush)?.Source?.PlatformImpl.Item;
}
if (tileBrush != null && tileBrushImage != null)
{
ConfigureTileBrush(ref paintWrapper, targetSize, tileBrush, tileBrushImage);
}
else
{
paint.Color = new SKColor(255, 255, 255, 0);
}
return paintWrapper;
}
/// <summary>
/// Creates paint wrapper for given pen.
/// </summary>
/// <param name="pen">Source pen.</param>
/// <param name="targetSize">Target size.</param>
/// <returns></returns>
private PaintWrapper CreatePaint(Pen pen, Size targetSize)
{
var rv = CreatePaint(pen.Brush, targetSize);
var paint = rv.Paint;
paint.IsStroke = true;
paint.StrokeWidth = (float) pen.Thickness;
// Need to modify dashes due to Skia modifying their lengths
// https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/dots
// TODO: Still something is off, dashes are now present, but don't look the same as D2D ones.
float dashLengthModifier;
float gapLengthModifier;
switch (pen.StartLineCap)
{
case PenLineCap.Round:
paint.StrokeCap = SKStrokeCap.Round;
dashLengthModifier = -paint.StrokeWidth;
gapLengthModifier = paint.StrokeWidth;
break;
case PenLineCap.Square:
paint.StrokeCap = SKStrokeCap.Square;
dashLengthModifier = -paint.StrokeWidth;
gapLengthModifier = paint.StrokeWidth;
break;
default:
paint.StrokeCap = SKStrokeCap.Butt;
dashLengthModifier = 0.0f;
gapLengthModifier = 0.0f;
break;
}
switch (pen.LineJoin)
{
case PenLineJoin.Miter:
paint.StrokeJoin = SKStrokeJoin.Miter;
break;
case PenLineJoin.Round:
paint.StrokeJoin = SKStrokeJoin.Round;
break;
default:
paint.StrokeJoin = SKStrokeJoin.Bevel;
break;
}
paint.StrokeMiter = (float) pen.MiterLimit;
if (pen.DashStyle?.Dashes != null && pen.DashStyle.Dashes.Count > 0)
{
var srcDashes = pen.DashStyle.Dashes;
var dashesArray = new float[srcDashes.Count];
for (var i = 0; i < srcDashes.Count; ++i)
{
var lengthModifier = i % 2 == 0 ? dashLengthModifier : gapLengthModifier;
// Avalonia dash lengths are relative, but Skia takes absolute sizes - need to scale
dashesArray[i] = (float) srcDashes[i] * paint.StrokeWidth + lengthModifier;
}
var pe = SKPathEffect.CreateDash(dashesArray, (float) pen.DashStyle.Offset);
paint.PathEffect = pe;
rv.AddDisposable(pe);
}
return rv;
}
/// <summary>
/// Create new render target compatible with this drawing context.
/// </summary>
/// <param name="size">The size of the render target in DIPs.</param>
/// <param name="format">Pixel format.</param>
/// <returns></returns>
private SurfaceRenderTarget CreateRenderTarget(Size size, PixelFormat? format = null)
{
var pixelSize = PixelSize.FromSize(size, _dpi);
var createInfo = new SurfaceRenderTarget.CreateInfo
{
Width = pixelSize.Width,
Height = pixelSize.Height,
Dpi = _dpi,
Format = format,
DisableTextLcdRendering = !_canTextUseLcdRendering,
GrContext = _grContext
};
return new SurfaceRenderTarget(createInfo);
}
/// <summary>
/// Skia cached paint state.
/// </summary>
private struct PaintState : IDisposable
{
private readonly SKColor _color;
private readonly SKShader _shader;
private readonly SKPaint _paint;
public PaintState(SKPaint paint, SKColor color, SKShader shader)
{
_paint = paint;
_color = color;
_shader = shader;
}
/// <inheritdoc />
public void Dispose()
{
_paint.Color = _color;
_paint.Shader = _shader;
}
}
/// <summary>
/// Skia paint wrapper.
/// </summary>
internal struct PaintWrapper : IDisposable
{
//We are saving memory allocations there
public readonly SKPaint Paint;
private IDisposable _disposable1;
private IDisposable _disposable2;
private IDisposable _disposable3;
public PaintWrapper(SKPaint paint)
{
Paint = paint;
_disposable1 = null;
_disposable2 = null;
_disposable3 = null;
}
public IDisposable ApplyTo(SKPaint paint)
{
var state = new PaintState(paint, paint.Color, paint.Shader);
paint.Color = Paint.Color;
paint.Shader = Paint.Shader;
return state;
}
/// <summary>
/// Add new disposable to a wrapper.
/// </summary>
/// <param name="disposable">Disposable to add.</param>
public void AddDisposable(IDisposable disposable)
{
if (_disposable1 == null)
{
_disposable1 = disposable;
}
else if (_disposable2 == null)
{
_disposable2 = disposable;
}
else if (_disposable3 == null)
{
_disposable3 = disposable;
}
else
{
Debug.Assert(false);
// ReSharper disable once HeuristicUnreachableCode
throw new InvalidOperationException(
"PaintWrapper disposable object limit reached. You need to add extra struct fields to support more disposables.");
}
}
/// <inheritdoc />
public void Dispose()
{
Paint?.Dispose();
_disposable1?.Dispose();
_disposable2?.Dispose();
_disposable3?.Dispose();
}
}
}
}
| |
// 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 TestLibrary;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.ILGeneration.Tests
{
public class ILGeneratorEmit1
{
[Fact]
public void PosTest1()
{
string name = "Assembly1";
AssemblyName asmname = new AssemblyName(name);
AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public);
MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { });
int expectedRet = 1;
// generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit()
ILGenerator ilgen = mbuild.GetILGenerator();
ilgen.Emit(OpCodes.Ldc_I4, expectedRet);
ilgen.Emit(OpCodes.Ret);
// create the type where this method is in
Type tp = tb.CreateTypeInfo().AsType();
MethodInfo mi = tp.GetMethod("meth1");
TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public);
MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { });
// generate code for the method which will be invoking the first method
ILGenerator ilgen2 = mbuild2.GetILGenerator();
ilgen2.Emit(OpCodes.Newobj, tp.GetConstructor(new Type[] { }));
ilgen2.Emit(OpCodes.Call, mi);
ilgen2.Emit(OpCodes.Ret);
// create the type whose method will be invoking the MethodInfo method
Type tp2 = tb2.CreateTypeInfo().AsType();
MethodInfo md = tp2.GetMethod("meth2");
// meth2 should invoke meth1 which should return value from meth1
int ret = (int)md.Invoke(null, null);
Assert.Equal(ret, expectedRet);
}
[Fact]
public void PosTest2()
{
string name = "Assembly1";
AssemblyName asmname = new AssemblyName(name);
AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public);
MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { });
int expectedRet = 12;
// generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit()
ILGenerator ilgen = mbuild.GetILGenerator();
ilgen.Emit(OpCodes.Ldc_I4, expectedRet);
ilgen.Emit(OpCodes.Ret);
// create the type where this method is in
Type tp = tb.CreateTypeInfo().AsType();
MethodInfo mi = tp.GetMethod("meth1");
TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public);
MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public, typeof(int), new Type[] { });
// generate code for the method which will be invoking the first method
ILGenerator ilgen2 = mbuild2.GetILGenerator();
ilgen2.Emit(OpCodes.Newobj, tp.GetConstructor(new Type[] { }));
ilgen2.Emit(OpCodes.Callvirt, mi);
ilgen2.Emit(OpCodes.Ret);
// create the type whose method will be invoking the MethodInfo method
Type tp2 = tb2.CreateTypeInfo().AsType();
MethodInfo md = tp2.GetMethod("meth2");
// meth2 should invoke meth1 which should return value 'methodRet'
int ret = (int)md.Invoke(Activator.CreateInstance(tp2), null);
Assert.Equal(ret, expectedRet);
}
[Fact]
public void PosTest3()
{
string name = "Assembly1";
AssemblyName asmname = new AssemblyName(name);
AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public);
MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { });
mbuild.DefineGenericParameters(new string[] { "T" });
int expectedRet = 101;
// generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit()
ILGenerator ilgen = mbuild.GetILGenerator();
ilgen.Emit(OpCodes.Ldc_I4, expectedRet);
ilgen.Emit(OpCodes.Ret);
// create the type where this method is in
Type tp = tb.CreateTypeInfo().AsType();
MethodInfo mi = tp.GetMethod("meth1");
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(int));
TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public);
MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { });
// generate code for the method which will be invoking the first method
ILGenerator ilgen2 = mbuild2.GetILGenerator();
ilgen2.Emit(OpCodes.Newobj, tp.GetConstructor(new Type[] { }));
ilgen2.Emit(OpCodes.Callvirt, miConstructed);
ilgen2.Emit(OpCodes.Ret);
// create the type whose method will be invoking the MethodInfo method
Type tp2 = tb2.CreateTypeInfo().AsType();
MethodInfo md = tp2.GetMethod("meth2");
// meth2 should invoke meth1 which should return value 'methodRet'
int ret = (int)md.Invoke(null, null);
Assert.Equal(ret, expectedRet);
}
[Fact]
public void PosTest4()
{
string name = "Assembly1";
AssemblyName asmname = new AssemblyName(name);
// create a dynamic assembly & module
AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public);
tb.DefineGenericParameters(new string[] { "T" });
MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(long), new Type[] { });
long expectedRet = 500000;
// generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit()
ILGenerator ilgen = mbuild.GetILGenerator();
ilgen.Emit(OpCodes.Ldc_I8, expectedRet);
ilgen.Emit(OpCodes.Ret);
// create the type where this method is in
Type tp = tb.CreateTypeInfo().AsType();
Type tpConstructed = tp.MakeGenericType(typeof(int));
MethodInfo mi = tpConstructed.GetMethod("meth1");
TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public);
MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static,
typeof(long), new Type[] { });
// generate code for the method which will be invoking the first method
ILGenerator ilgen2 = mbuild2.GetILGenerator();
ilgen2.Emit(OpCodes.Newobj, tpConstructed.GetConstructor(new Type[] { }));
ilgen2.Emit(OpCodes.Callvirt, mi);
ilgen2.Emit(OpCodes.Ret);
// create the type whose method will be invoking the MethodInfo method
Type tp2 = tb2.CreateTypeInfo().AsType();
MethodInfo md = tp2.GetMethod("meth2");
// meth2 should invoke meth1 which should return value 'methodRet'
long ret = (long)md.Invoke(null, null);
Assert.Equal(ret, expectedRet);
}
[Fact]
public void PosTest5()
{
string name = "Assembly1";
AssemblyName asmname = new AssemblyName(name);
// create a dynamic assembly & module
AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public);
tb.DefineGenericParameters(new string[] { "T" });
MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { });
mbuild.DefineGenericParameters(new string[] { "U" });
int expectedRet = 1;
// generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit()
ILGenerator ilgen = mbuild.GetILGenerator();
ilgen.Emit(OpCodes.Ldc_I4, expectedRet);
ilgen.Emit(OpCodes.Ret);
// create the type where this method is in
Type tp = tb.CreateTypeInfo().AsType();
Type tpConstructed = tp.MakeGenericType(typeof(int));
MethodInfo mi = tpConstructed.GetMethod("meth1");
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(string));
TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public);
MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static,
typeof(int), new Type[] { });
// generate code for the method which will be invoking the first method
ILGenerator ilgen2 = mbuild2.GetILGenerator();
ilgen2.Emit(OpCodes.Newobj, tpConstructed.GetConstructor(new Type[] { }));
ilgen2.Emit(OpCodes.Callvirt, miConstructed);
ilgen2.Emit(OpCodes.Ret);
// create the type whose method will be invoking the MethodInfo method
Type tp2 = tb2.CreateTypeInfo().AsType();
MethodInfo md = tp2.GetMethod("meth2");
// meth2 should invoke meth1 which should return value 'methodRet'
int ret = (int)md.Invoke(null, null);
Assert.Equal(ret, expectedRet);
}
[Fact]
public void NegTest()
{
string name = "Assembly1";
AssemblyName asmname = new AssemblyName();
asmname.Name = name;
AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
MethodBuilder methbuild = modbuild.DefineGlobalMethod("method1", MethodAttributes.Public | MethodAttributes.Static, typeof(Type), new Type[] { });
ILGenerator ilgen = methbuild.GetILGenerator();
MethodInfo mi = null;
Assert.Throws<ArgumentNullException>(() => { ilgen.Emit(OpCodes.Call, mi); });
}
}
}
| |
// 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 System.Threading.Tasks;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class GetEnumeratorTests
{
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void GetEnumerator_Unordered(Labeled<ParallelQuery<int>> labeled, int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
IEnumerator<int> enumerator = labeled.Item.GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
seen.Add(current);
Assert.Equal(current, enumerator.Current);
}
seen.AssertComplete();
if (labeled.ToString().StartsWith("Enumerable.Range") || labeled.ToString().StartsWith("Partitioner"))
{
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
else
{
enumerator.Reset();
seen = new IntegerRangeSet(0, count);
while (enumerator.MoveNext())
{
Assert.True(seen.Add(enumerator.Current));
}
seen.AssertComplete();
}
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))]
public static void GetEnumerator_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GetEnumerator_Unordered(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void GetEnumerator(Labeled<ParallelQuery<int>> labeled, int count)
{
int seen = 0;
IEnumerator<int> enumerator = labeled.Item.GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
Assert.Equal(seen++, current);
Assert.Equal(current, enumerator.Current);
}
Assert.Equal(count, seen);
if (labeled.ToString().StartsWith("Enumerable.Range") || labeled.ToString().StartsWith("Partitioner"))
{
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
else
{
enumerator.Reset();
seen = 0;
while (enumerator.MoveNext())
{
Assert.Equal(seen++, enumerator.Current);
}
Assert.Equal(count, seen);
}
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(Sources))]
public static void GetEnumerator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GetEnumerator(labeled, count);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 128 }, MemberType = typeof(UnorderedSources))]
[MemberData(nameof(Sources.Ranges), new[] { 128 }, MemberType = typeof(Sources))]
public static void GetEnumerator_OperationCanceledException(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource source = new CancellationTokenSource();
int countdown = 4;
Action cancel = () => { if (Interlocked.Decrement(ref countdown) == 0) source.Cancel(); };
OperationCanceledException oce = Assert.Throws<OperationCanceledException>(() => { foreach (var i in labeled.Item.WithCancellation(source.Token)) cancel(); });
Assert.Equal(source.Token, oce.CancellationToken);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
[MemberData(nameof(Sources.Ranges), new[] { 1 }, MemberType = typeof(Sources))]
public static void GetEnumerator_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Throws<OperationCanceledException>(() => { foreach (var i in labeled.Item.WithCancellation(new CancellationToken(canceled: true))) { throw new ShouldNotBeInvokedException(); }; });
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void GetEnumerator_MoveNextAfterQueryOpeningFailsIsIllegal(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item.Select<int, int>(x => { throw new DeliberateTestException(); }).OrderBy(x => x);
IEnumerator<int> enumerator = query.GetEnumerator();
//moveNext will cause queryOpening to fail (no element generated)
Functions.AssertThrowsWrapped<DeliberateTestException>(() => enumerator.MoveNext());
//moveNext after queryOpening failed
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 16 }, MemberType = typeof(UnorderedSources))]
[MemberData(nameof(Sources.Ranges), new[] { 16 }, MemberType = typeof(Sources))]
public static void GetEnumerator_CurrentBeforeMoveNext(Labeled<ParallelQuery<int>> labeled, int count)
{
IEnumerator<int> enumerator = labeled.Item.GetEnumerator();
if (labeled.ToString().StartsWith("Partitioner")
|| labeled.ToString().StartsWith("Array"))
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
else
{
Assert.InRange(enumerator.Current, 0, count);
}
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void GetEnumerator_MoveNextAfterEnd(Labeled<ParallelQuery<int>> labeled, int count)
{
IEnumerator<int> enumerator = labeled.Item.GetEnumerator();
while (enumerator.MoveNext())
{
count--;
}
Assert.Equal(0, count);
Assert.False(enumerator.MoveNext());
}
[Fact]
public static void GetEnumerator_LargeQuery_PauseAfterOpening()
{
using (IEnumerator<int> e = Enumerable.Range(0, 8192).AsParallel().SkipWhile(i => true).GetEnumerator())
{
e.MoveNext();
Task.Delay(100).Wait(); // verify nothing goes haywire when the internal buffer is allowed to fill
while (e.MoveNext()) ;
Assert.False(e.MoveNext());
}
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2 }, MemberType = typeof(UnorderedSources))]
public static void GetEnumerator_DisposeBeforeFirstMoveNext(Labeled<ParallelQuery<int>> labeled, int count)
{
IEnumerator<int> e = labeled.Item.Select(i => i).GetEnumerator();
e.Dispose();
Assert.Throws<ObjectDisposedException>(() => e.MoveNext());
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1, 2 }, MemberType = typeof(UnorderedSources))]
public static void GetEnumerator_DisposeAfterMoveNext(Labeled<ParallelQuery<int>> labeled, int count)
{
IEnumerator<int> e = labeled.Item.Select(i => i).GetEnumerator();
e.MoveNext();
e.Dispose();
Assert.Throws<ObjectDisposedException>(() => e.MoveNext());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void GetEnumerator_DisposeAsynchronously(bool synchronousMerge)
{
IEnumerable<int> effectivelyInfiniteSource = Enumerable.Range(0, int.MaxValue);
var query = effectivelyInfiniteSource.AsParallel().Select(i => i);
if (synchronousMerge)
{
query = query.WithMergeOptions(ParallelMergeOptions.FullyBuffered);
}
IEnumerator<int> enumerator = query.GetEnumerator();
Task.Delay(10).ContinueWith(_ => enumerator.Dispose(),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Exception e = Assert.ThrowsAny<Exception>(() =>
{
for (int i = 0; i < int.MaxValue; i++)
enumerator.MoveNext();
});
Assert.True(
e is OperationCanceledException || // if the dispose happens to occur during the opening of the query, after the sync dispose check
e is ObjectDisposedException, // all other cases
$"Expected an OCE or ODE, got {e.GetType()}");
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Cms.Core.PropertyEditors;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
[TestFixture]
public class NestedContentPropertyComponentTests
{
[Test]
public void Invalid_Json()
{
var component = new NestedContentPropertyHandler();
Assert.DoesNotThrow(() => component.CreateNestedContentKeys("this is not json", true));
}
[Test]
public void No_Nesting()
{
Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
var json = @"[
{""key"":""04a6dba8-813c-4144-8aca-86a3f24ebf08"",""name"":""Item 1"",""ncContentTypeAlias"":""nested"",""text"":""woot""},
{""key"":""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"",""name"":""Item 2"",""ncContentTypeAlias"":""nested"",""text"":""zoot""}
]";
var expected = json
.Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString())
.Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString());
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, false, GuidFactory);
Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString());
}
[Test]
public void One_Level_Nesting_Unescaped()
{
Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
var json = @"[{
""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""list"",
""text"": ""zoot"",
""subItems"": [{
""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""fbde4288-8382-4e13-8933-ed9c160de050"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""text"",
""text"": ""zoot""
}
]
}
]";
var expected = json
.Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString())
.Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString())
.Replace("dccf550c-3a05-469e-95e1-a8f560f788c2", guids[2].ToString())
.Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString());
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, false, GuidFactory);
Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString());
}
[Test]
public void One_Level_Nesting_Escaped()
{
Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
// we need to ensure the escaped json is consistent with how it will be re-escaped after parsing
// and this is how to do that, the result will also include quotes around it.
var subJsonEscaped = JsonConvert.ToString(JsonConvert.DeserializeObject(@"[{
""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""fbde4288-8382-4e13-8933-ed9c160de050"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""text"",
""text"": ""zoot""
}
]").ToString());
var json = @"[{
""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""list"",
""text"": ""zoot"",
""subItems"":" + subJsonEscaped + @"
}
]";
var expected = json
.Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString())
.Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString())
.Replace("dccf550c-3a05-469e-95e1-a8f560f788c2", guids[2].ToString())
.Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString());
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, false, GuidFactory);
Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString());
}
[Test]
public void Nested_In_Complex_Editor_Escaped()
{
Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
// we need to ensure the escaped json is consistent with how it will be re-escaped after parsing
// and this is how to do that, the result will also include quotes around it.
var subJsonEscaped = JsonConvert.ToString(JsonConvert.DeserializeObject(@"[{
""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""fbde4288-8382-4e13-8933-ed9c160de050"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""text"",
""text"": ""zoot""
}
]").ToString());
// Complex editor such as the grid
var complexEditorJsonEscaped = @"{
""name"": ""1 column layout"",
""sections"": [
{
""grid"": ""12"",
""rows"": [
{
""name"": ""Article"",
""id"": ""b4f6f651-0de3-ef46-e66a-464f4aaa9c57"",
""areas"": [
{
""grid"": ""4"",
""controls"": [
{
""value"": ""I am quote"",
""editor"": {
""alias"": ""quote"",
""view"": ""textstring""
},
""styles"": null,
""config"": null
}],
""styles"": null,
""config"": null
},
{
""grid"": ""8"",
""controls"": [
{
""value"": ""Header"",
""editor"": {
""alias"": ""headline"",
""view"": ""textstring""
},
""styles"": null,
""config"": null
},
{
""value"": " + subJsonEscaped + @",
""editor"": {
""alias"": ""madeUpNestedContent"",
""view"": ""madeUpNestedContentInGrid""
},
""styles"": null,
""config"": null
}],
""styles"": null,
""config"": null
}],
""styles"": null,
""config"": null
}]
}]
}";
var json = @"[{
""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""list"",
""text"": ""zoot"",
""subItems"":" + complexEditorJsonEscaped + @"
}
]";
var expected = json
.Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString())
.Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString())
.Replace("dccf550c-3a05-469e-95e1-a8f560f788c2", guids[2].ToString())
.Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString());
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, false, GuidFactory);
Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString());
}
[Test]
public void No_Nesting_Generates_Keys_For_Missing_Items()
{
Guid[] guids = new[] { Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
var json = @"[
{""key"":""04a6dba8-813c-4144-8aca-86a3f24ebf08"",""name"":""Item 1 my key wont change"",""ncContentTypeAlias"":""nested"",""text"":""woot""},
{""name"":""Item 2 was copied and has no key prop"",""ncContentTypeAlias"":""nested"",""text"":""zoot""}
]";
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, true, GuidFactory);
// Ensure the new GUID is put in a key into the JSON
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[0].ToString()));
// Ensure that the original key is NOT changed/modified & still exists
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains("04a6dba8-813c-4144-8aca-86a3f24ebf08"));
}
[Test]
public void One_Level_Nesting_Escaped_Generates_Keys_For_Missing_Items()
{
Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
// we need to ensure the escaped json is consistent with how it will be re-escaped after parsing
// and this is how to do that, the result will also include quotes around it.
var subJsonEscaped = JsonConvert.ToString(JsonConvert.DeserializeObject(@"[{
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""name"": ""Nested Item 2 was copied and has no key"",
""ncContentTypeAlias"": ""text"",
""text"": ""zoot""
}
]").ToString());
var json = @"[{
""name"": ""Item 1 was copied and has no key"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"",
""name"": ""Item 2"",
""ncContentTypeAlias"": ""list"",
""text"": ""zoot"",
""subItems"":" + subJsonEscaped + @"
}
]";
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, true, GuidFactory);
// Ensure the new GUID is put in a key into the JSON for each item
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[0].ToString()));
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[1].ToString()));
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[2].ToString()));
}
[Test]
public void Nested_In_Complex_Editor_Escaped_Generates_Keys_For_Missing_Items()
{
Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid() };
var guidCounter = 0;
Guid GuidFactory() => guids[guidCounter++];
// we need to ensure the escaped json is consistent with how it will be re-escaped after parsing
// and this is how to do that, the result will also include quotes around it.
var subJsonEscaped = JsonConvert.ToString(JsonConvert.DeserializeObject(@"[{
""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""name"": ""Nested Item 2 was copied and has no key"",
""ncContentTypeAlias"": ""text"",
""text"": ""zoot""
}
]").ToString());
// Complex editor such as the grid
var complexEditorJsonEscaped = @"{
""name"": ""1 column layout"",
""sections"": [
{
""grid"": ""12"",
""rows"": [
{
""name"": ""Article"",
""id"": ""b4f6f651-0de3-ef46-e66a-464f4aaa9c57"",
""areas"": [
{
""grid"": ""4"",
""controls"": [
{
""value"": ""I am quote"",
""editor"": {
""alias"": ""quote"",
""view"": ""textstring""
},
""styles"": null,
""config"": null
}],
""styles"": null,
""config"": null
},
{
""grid"": ""8"",
""controls"": [
{
""value"": ""Header"",
""editor"": {
""alias"": ""headline"",
""view"": ""textstring""
},
""styles"": null,
""config"": null
},
{
""value"": " + subJsonEscaped + @",
""editor"": {
""alias"": ""madeUpNestedContent"",
""view"": ""madeUpNestedContentInGrid""
},
""styles"": null,
""config"": null
}],
""styles"": null,
""config"": null
}],
""styles"": null,
""config"": null
}]
}]
}";
var json = @"[{
""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"",
""name"": ""Item 1"",
""ncContentTypeAlias"": ""text"",
""text"": ""woot""
}, {
""name"": ""Item 2 was copied and has no key"",
""ncContentTypeAlias"": ""list"",
""text"": ""zoot"",
""subItems"":" + complexEditorJsonEscaped + @"
}
]";
var component = new NestedContentPropertyHandler();
var result = component.CreateNestedContentKeys(json, true, GuidFactory);
// Ensure the new GUID is put in a key into the JSON for each item
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[0].ToString()));
Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[1].ToString()));
}
}
}
| |
/*
* DictionaryBase.cs - Implementation of the
* "System.Collections.DictionaryBase" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Collections
{
#if !ECMA_COMPAT
using System;
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
{
// Internal state.
private Hashtable table;
// Constructor.
protected DictionaryBase()
{
table = new Hashtable();
}
// Implement the IDictionary interface.
void IDictionary.Add(Object key, Object value)
{
OnValidate(key, value);
OnInsert(key, value);
table.Add(key, value);
try
{
OnInsertComplete(key, value);
}
catch(Exception)
{
table.Remove(key);
throw;
}
}
public void Clear()
{
OnClear();
table.Clear();
OnClearComplete();
}
bool IDictionary.Contains(Object key)
{
return table.Contains(key);
}
public IDictionaryEnumerator GetEnumerator()
{
return ((IDictionary)table).GetEnumerator();
}
void IDictionary.Remove(Object key)
{
Object value = table[key];
OnValidate(key, value);
OnRemove(key, value);
table.Remove(key);
try
{
OnRemoveComplete(key, value);
}
catch(Exception)
{
table[key] = value;
throw;
}
}
bool IDictionary.IsFixedSize
{
get
{
return table.IsFixedSize;
}
}
bool IDictionary.IsReadOnly
{
get
{
return table.IsReadOnly;
}
}
Object IDictionary.this[Object key]
{
get
{
Object value = table[key];
OnGet(key, value);
return value;
}
set
{
Object oldValue = table[key];
OnSet(key, oldValue, value);
table[key] = value;
try
{
OnSetComplete(key, oldValue, value);
}
catch(Exception)
{
table[key] = oldValue;
throw;
}
}
}
ICollection IDictionary.Keys
{
get
{
return table.Keys;
}
}
ICollection IDictionary.Values
{
get
{
return table.Values;
}
}
// Implement the ICollection interface.
public void CopyTo(Array array, int index)
{
table.CopyTo(array, index);
}
public int Count
{
get
{
return table.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return table.IsSynchronized;
}
}
Object ICollection.SyncRoot
{
get
{
return table.SyncRoot;
}
}
// Implement the IEnumerable interface.
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)table).GetEnumerator();
}
// Get the inner hash table that is being used by this dictionary base.
protected Hashtable InnerHashtable
{
get
{
return table;
}
}
// Get this dictionary base, represented as an IDictionary.
protected IDictionary Dictionary
{
get
{
return this;
}
}
// Dictionary control methods.
protected virtual void OnClear() {}
protected virtual void OnClearComplete() {}
protected virtual Object OnGet(Object key, Object currentValue)
{
return currentValue;
}
protected virtual void OnInsert(Object key, Object value) {}
protected virtual void OnInsertComplete(Object key, Object value) {}
protected virtual void OnRemove(Object key, Object value) {}
protected virtual void OnRemoveComplete(Object key, Object value) {}
protected virtual void OnSet
(Object key, Object oldValue, Object newValue) {}
protected virtual void OnSetComplete
(Object key, Object oldValue, Object newValue) {}
protected virtual void OnValidate(Object key, Object value) {}
}; // class DictionaryBase
#endif // !ECMA_COMPAT
}; // namespace System.Collections
| |
using System;
using System.Linq;
using System.Threading;
using CIAPI.DTO;
using CIAPI.RecordedTests.Infrastructure;
using CIAPI.Rpc;
using NUnit.Framework;
namespace CIAPI.RecordedTests
{
[TestFixture, MocumentModeOverride(MocumentMode.Play),Category("APIBUG")]
public class MarketFixture : CIAPIRecordingFixtureBase
{
[Test]
public void CanGetMarketTags()
{
var rpcClient = BuildRpcClient();
//Markets are grouped into a collection of tags.
//You can get a list of available tags from TagLookup
var tagResponse = rpcClient.Market.TagLookup();
Assert.IsTrue(tagResponse.Tags.Length > 0, "No tags have been defined for your user's account operator");
Console.WriteLine(tagResponse.ToStringWithValues());
/* Gives something like:
* MarketInformationTagLookupResponseDTO:
Tags=ApiPrimaryMarketTagDTO:
Children=ApiMarketTagDTO:
MarketTagId=8 Name=FX Majors Type=2
ApiMarketTagDTO:
MarketTagId=9 Name=FX Minors Type=2
ApiMarketTagDTO:
MarketTagId=14 Name=Euro Crosses Type=2
ApiMarketTagDTO:
MarketTagId=15 Name=Sterling Crosses Type=2
MarketTagId=7 Name=Currencies Type=1
ApiPrimaryMarketTagDTO:
Children=ApiMarketTagDTO:
MarketTagId=17 Name=Popular Type=2
MarketTagId=16 Name=FX Type=1
*/
}
[Test]
public void CanSearchWithTags()
{
var rpcClient = BuildRpcClient();
var tagResponse = rpcClient.Market.TagLookup();
Assert.IsTrue(tagResponse.Tags.Length > 0, "No tags have been defined for your user's account operator");
//Once you have a tag, you can search for all markets associated with that tag
int tagId = tagResponse.Tags.First(t => t.Name.Contains("FX")).MarketTagId;
var allMarketsInTag = rpcClient.Market.SearchWithTags("", tagId, true, true, true, true, true, true, 100, false);
Console.WriteLine(allMarketsInTag.ToStringWithValues());
/* Gives something like:
* MarketInformationSearchWithTagsResponseDTO:
Markets=ApiMarketDTO:
MarketId=400481134 Name=EUR/USD
ApiMarketDTO:
MarketId=400481136 Name=GBP/AUD
ApiMarketDTO:
MarketId=400481139 Name=GBP/JPY
ApiMarketDTO:
MarketId=400481142 Name=GBP/USD
Tags=ApiMarketTagDTO:
MarketTagId=8 Name=FX Majors Type=2
ApiMarketTagDTO:
MarketTagId=9 Name=FX Minors Type=2
ApiMarketTagDTO:
MarketTagId=14 Name=Euro Crosses Type=2
ApiMarketTagDTO:
MarketTagId=15 Name=Sterling Crosses Type=2
*/
//Or, you can search for all markets in that tag that start with a specific string
var allMarketsInTagContainingGBP = rpcClient.Market.SearchWithTags("GBP", tagId, true, true, true, true, true, true, 100, false);
Console.WriteLine(allMarketsInTagContainingGBP.ToStringWithValues());
/* Gives something like:
* MarketInformationSearchWithTagsResponseDTO:
Markets=ApiMarketDTO:
MarketId=400481136 Name=GBP/AUD
ApiMarketDTO:
MarketId=400481139 Name=GBP/JPY
ApiMarketDTO:
MarketId=400481142 Name=GBP/USD
*/
}
[Test]
public void CanListMarketInformation()
{
var rpcClient = BuildRpcClient();
var marketList = GetAvailableCFDMarkets(rpcClient);
var response = rpcClient.Market.ListMarketInformation(
new ListMarketInformationRequestDTO
{
MarketIds = marketList.ToList().Select(m => m.MarketId).ToArray()
}
);
Assert.AreEqual(marketList.Length, response.MarketInformation.Length);
rpcClient.LogOut();
}
[Test]
public void ListMarketInformationSearchQueryIsValidated()
{
var rpcClient = BuildRpcClient();
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, "/", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, "\\", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, @"\", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, @"GBP \ USD", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, @"GBP \\ USD", 100, false);
var gate = new AutoResetEvent(false);
rpcClient.Market.BeginListMarketInformationSearch(false, true, true, false, false, true, @"\", 100, false, ar =>
{
var response = rpcClient.Market.EndListMarketInformationSearch(ar);
gate.Set();
}, null);
if (!gate.WaitOne(10000))
{
throw new TimeoutException();
}
rpcClient.LogOut();
}
[Test]
public void CanListMarketInformationSearch()
{
var rpcClient = BuildRpcClient();
var response = rpcClient.Market.ListMarketInformationSearch(false, true, false, true, false, true, "GBP", 10, false);
Assert.Greater(response.MarketInformation.Length, 1);
rpcClient.LogOut();
}
/// <summary>
/// Test showing issue #167 - https://github.com/cityindex/CIAPI.CS/issues/167 -
/// has stopped occuring
/// </summary>
[Test, Ignore("Long running")]
public void MultipleRequestsToCanGetMarketInformationShouldNotThrowAnyExceptions()
{
var rpcClient = BuildRpcClient();
for (var i = 0; i < 100; i++)
{
var response = rpcClient.Market.GetMarketInformation("154303");
Assert.That(response.MarketInformation.Name.Length, Is.GreaterThan(1));
Thread.Sleep(1100);
}
rpcClient.LogOut();
}
//
[Test]
public void CanGetMarketInformationWithPathChar()
{
var rpcClient = BuildRpcClient();
var account = rpcClient.AccountInformation.GetClientAndTradingAccount();
var response = rpcClient.SpreadMarkets.ListSpreadMarkets("GBP/CAD", null, account.ClientAccountId, 19, false);
Assert.That(response.Markets.Length, Is.GreaterThan(1));
rpcClient.LogOut();
}
[Test]
public void CanGetMarketInformation()
{
var rpcClient = BuildRpcClient();
var marketList = GetAvailableCFDMarkets(rpcClient);
var response = rpcClient.Market.GetMarketInformation(marketList[0].MarketId.ToString());
string stringWithValues = response.MarketInformation.ToStringWithValues();
Console.WriteLine(stringWithValues);
/* Returns data like the following (2012/04/27)
ApiMarketInformationDTO:
MarketId=154291 Name=GBP/AUD (per 0.0001) CFD MarginFactor=1.00000000 MinMarginFactor=NULL
MaxMarginFactor=NULL MarginFactorUnits=26 MinDistance=0.00 WebMinSize=1.00000000
MaxSize=2200.00000000 Market24H=True PriceDecimalPlaces=5 DefaultQuoteLength=180 TradeOnWeb=True
LimitUp=False LimitDown=False LongPositionOnly=False CloseOnly=False MarketEod=
PriceTolerance=10.00000000 ConvertPriceToPipsMultiplier=10000 MarketSettingsTypeId=2
MarketSettingsType=CFD MobileShortName=GBP/AUD CentralClearingType=No
CentralClearingTypeDescription=None MarketCurrencyId=1 PhoneMinSize=5.00000000
DailyFinancingAppliedAtUtc=26/04/2012 21:00:00 NextMarketEodTimeUtc=26/04/2012 21:00:00
TradingStartTimeUtc=NULL TradingEndTimeUtc=NULL
MarketPricingTimes=ApiTradingDayTimesDTO:
DayOfWeek=1 StartTimeUtc=26/04/2012 11:00:00 +00:00 EndTimeUtc=NULL
ApiTradingDayTimesDTO:
DayOfWeek=5 StartTimeUtc=NULL EndTimeUtc=28/04/2012 00:15:00 +00:00
MarketBreakTimes=
MarketSpreads=ApiMarketSpreadDTO:
SpreadTimeUtc=NULL Spread=0.00067000 SpreadUnits=27
GuaranteedOrderPremium=8.00 GuaranteedOrderPremiumUnits=1 GuaranteedOrderMinDistance=75.00 GuaranteedOrderMinDistanceUnits=27
*/
Assert.That(response.MarketInformation.Name.Length, Is.GreaterThan(1));
rpcClient.LogOut();
}
[Test]
public void CanSaveMarketInformation()
{
var rpcClient = BuildRpcClient();
var clientAccount = rpcClient.AccountInformation.GetClientAndTradingAccount();
var marketList = GetAvailableCFDMarkets(rpcClient);
var tolerances = new[]
{
new ApiMarketInformationSaveDTO
{
MarketId = marketList[0].MarketId,
PriceTolerance = 10
}
};
var saveMarketInfoRespnse = rpcClient.Market.SaveMarketInformation(new SaveMarketInformationRequestDTO()
{
MarketInformation = tolerances,
TradingAccountId = clientAccount.CFDAccount.TradingAccountId
});
// ApiSaveMarketInformationResponseDTO is devoid of properties, nothing to check as long as the call succeeds
}
public static ApiMarketInformationDTO[] GetAvailableCFDMarkets(Client rpcClient)
{
var marketList = rpcClient.Market.ListMarketInformationSearch(false, true, false, true, false, true, "GBP", 10, false);
Assert.That(marketList.MarketInformation.Length, Is.GreaterThanOrEqualTo(1), "There should be at least 1 CFD market availbe");
return marketList.MarketInformation;
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Web.UI.WebControls;
using ImageButton=Rainbow.Framework.Web.UI.WebControls.ImageButton;
using Rainbow.Framework.Providers.RainbowRoleProvider;
using System.Collections.Generic;
namespace Rainbow.Content.Web.Modules
{
public partial class SecurityCheck : PortalModuleControl
{
protected ImageButton RoleDeleteBtn;
protected DataSet dsModules;
protected DataView myDataView;
protected string sortField;
protected string sortDirection;
/// <summary>
/// Admin Module
/// </summary>
/// <value></value>
public override bool AdminModule
{
get { return true; }
}
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
// If this is the first visit to the page, bind the role data to the DropDownList
if (Page.IsPostBack == false)
{
BindRoles();
sortField = "PageName";
sortDirection = "ASC";
ViewState["SORTFIELD"] = sortField;
ViewState["SORTDIRECTION"] = sortDirection;
}
else
{
sortField = (string) ViewState["SORTFIELD"];
sortDirection = (string) ViewState["SORTDIRECTION"];
}
}
/// <summary>
/// Default constructor
/// </summary>
public SecurityCheck()
{
}
/// <summary>
/// Guid
/// </summary>
/// <value></value>
public override Guid GuidID
{
get { return new Guid("{8F74C9C4-543A-48fa-AB73-1C07D219899A}"); }
}
#region Web Form Designer generated code
/// <summary>
/// Raises the Init event.
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.btnSearch.Click += new EventHandler(this.btnSearch_Click);
this.dgModules.PageIndexChanged += new DataGridPageChangedEventHandler(this.dgModules_PageIndexChanged);
this.dgModules.SortCommand += new DataGridSortCommandEventHandler(this.dgModules_SortCommand);
this.Load += new EventHandler(this.Page_Load);
base.OnInit(e);
}
#endregion
# region Install / Uninstall Implementation
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
// Don't do Anything
}
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
// Don't do Anything
}
#endregion
/// <summary>
/// Handles the Click event of the btnSearch control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void btnSearch_Click(object sender, EventArgs e)
{
BindData();
BindGrid();
}
/// <summary>
/// Handles the PageIndexChanged event of the dgModules control.
/// </summary>
/// <param name="source">The source of the event.</param>
/// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridPageChangedEventArgs"/> instance containing the event data.</param>
private void dgModules_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
dgModules.CurrentPageIndex = e.NewPageIndex;
BindData();
BindGrid();
}
/// <summary>
/// Handles the SortCommand event of the dgModules control.
/// </summary>
/// <param name="source">The source of the event.</param>
/// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridSortCommandEventArgs"/> instance containing the event data.</param>
private void dgModules_SortCommand(object source, DataGridSortCommandEventArgs e)
{
if (sortField == e.SortExpression && sortDirection == "ASC")
sortDirection = "DESC";
else
sortDirection = "ASC";
ViewState["SORTFIELD"] = e.SortExpression;
ViewState["SORTDIRECTION"] = sortDirection;
BindData();
BindGrid();
}
/// <summary>
/// This method is used to bind the list of
/// security roles for this portal to an asp:dropdownlist server control
/// </summary>
private void BindRoles()
{
// Get the portal's roles from the database
Rainbow.Framework.Users.Data.UsersDB users = new Rainbow.Framework.Users.Data.UsersDB();
IList<RainbowRole> roles = users.GetPortalRoles(portalSettings.PortalAlias);
ddlRoles.DataSource = roles;
ddlRoles.DataBind();
ListItem noAdminItem = new ListItem();
noAdminItem.Text = General.GetString("SECURITYCHECK_NOADMIN", "No Admin");
noAdminItem.Value = "-1";
ddlRoles.Items.Add(noAdminItem);
}
/// <summary>
/// The BindData method on this User Control is used to obtain a DataSet of Modules'security information
/// from the rb_Modules table
/// </summary>
private void BindData()
{
StringBuilder select = new StringBuilder(string.Empty, 2048);
if (ddlRoles.SelectedValue == "-1")
{
// Search for all non Admin roles
select.Append("SELECT ModuleID, TabName, ModuleTitle, FriendlyName, IsAdmin = \n");
select.Append("Case Admin\n");
select.Append("When 1 Then 'X'\n");
select.Append("Else ' '\n");
select.Append("End,\n");
select.Append("CanView = \n");
select.Append("Case AuthorizedViewRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanEdit = \n");
select.Append("Case AuthorizedEditRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanAdd = \n");
select.Append("Case AuthorizedAddRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanDelete = \n");
select.Append("Case AuthorizedDeleteRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanProperties = \n");
select.Append("Case AuthorizedPropertiesRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanMove = \n");
select.Append("Case AuthorizedMoveModuleRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanDeleteModule = \n");
select.Append("Case AuthorizedDeleteModuleRoles\n");
select.Append("When 'Admins' then ' '\n");
select.Append("When 'Admins;' then ' '\n");
select.Append("Else 'X'\n");
select.Append("End\n");
select.Append("from rb_Modules\n");
select.Append("Inner Join rb_Tabs on rb_Modules.TabID = rb_Tabs.TabID and PortalID=" +
PortalID.ToString() + "\n");
select.Append(
"Inner Join rb_ModuleDefinitions on rb_Modules.ModuleDefID = rb_ModuleDefinitions.ModuleDefID\n");
select.Append(
"Inner Join rb_GeneralModuleDefinitions on rb_ModuleDefinitions.GeneralModDefID = rb_GeneralModuleDefinitions.GeneralModDefID\n");
}
else
{
// Search for a specific Role
string roleName = ddlRoles.SelectedItem.Text;
select.Append("SELECT ModuleID, TabName, ModuleTitle, FriendlyName, IsAdmin = \n");
select.Append("Case Admin\n");
select.Append("When 1 Then 'X'\n");
select.Append("Else ' '\n");
select.Append("End,\n");
select.Append("CanView = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedViewRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanEdit = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedEditRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanAdd = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedAddRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanDelete = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedDeleteRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanProperties = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedPropertiesRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanMove = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedMoveModuleRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End,\n");
select.Append("CanDeleteModule = \n");
select.Append("Case PATINDEX('%" + roleName +
"%', Replace(Replace(Replace(AuthorizedDeleteModuleRoles, 'Authenticated Users', '" +
roleName + "'), 'Unauthenticated Users', '" +
roleName + "'), 'All Users', '" + roleName + "'))\n");
select.Append("When 0 then ' '\n");
select.Append("Else 'X'\n");
select.Append("End\n");
select.Append("from rb_Modules\n");
select.Append("Inner Join rb_Tabs on rb_Modules.TabID = rb_Tabs.TabID and PortalID=" +
PortalID.ToString() + "\n");
select.Append(
"Inner Join rb_ModuleDefinitions on rb_Modules.ModuleDefID = rb_ModuleDefinitions.ModuleDefID\n");
select.Append(
"Inner Join rb_GeneralModuleDefinitions on rb_ModuleDefinitions.GeneralModDefID = rb_GeneralModuleDefinitions.GeneralModDefID\n");
}
if (chkAdmin.Checked)
{
select.Append("Where Admin = 1\n");
}
select.Append("order by TabName");
string selectSQL = select.ToString();
SqlConnection sqlConnection = Config.SqlConnectionString;
SqlDataAdapter sqlCommand = new SqlDataAdapter(selectSQL, sqlConnection);
try
{
sqlConnection.Open();
dsModules = new DataSet();
sqlCommand.Fill(dsModules);
sqlConnection.Close();
}
catch (Exception e)
{
Rainbow.Framework.ErrorHandler.Publish(Rainbow.Framework.LogLevel.Error,
"Error in Search: " + e.ToString() + " " + select.ToString(), e);
throw new Exception("Error in Search selection.");
}
myDataView = new DataView();
myDataView = dsModules.Tables[0].DefaultView;
}
/// <summary>
/// Binds the grid.
/// </summary>
private void BindGrid()
{
myDataView.Sort = sortField + " " + sortDirection;
dgModules.DataSource = myDataView;
dgModules.DataBind();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace CodeRuse.Email.Client.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F01Level1Coll (editable root list).<br/>
/// This is a generated base class of <see cref="F01Level1Coll"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="F02Level1"/> objects.
/// </remarks>
[Serializable]
public partial class F01Level1Coll : BusinessListBase<F01Level1Coll, F02Level1>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="F02Level1"/> item from the collection.
/// </summary>
/// <param name="level_1_ID">The Level_1_ID of the item to be removed.</param>
public void Remove(int level_1_ID)
{
foreach (var f02Level1 in this)
{
if (f02Level1.Level_1_ID == level_1_ID)
{
Remove(f02Level1);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="F02Level1"/> item is in the collection.
/// </summary>
/// <param name="level_1_ID">The Level_1_ID of the item to search for.</param>
/// <returns><c>true</c> if the F02Level1 is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int level_1_ID)
{
foreach (var f02Level1 in this)
{
if (f02Level1.Level_1_ID == level_1_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="F02Level1"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="level_1_ID">The Level_1_ID of the item to search for.</param>
/// <returns><c>true</c> if the F02Level1 is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int level_1_ID)
{
foreach (var f02Level1 in this.DeletedList)
{
if (f02Level1.Level_1_ID == level_1_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="F02Level1"/> item of the <see cref="F01Level1Coll"/> collection, based on item key properties.
/// </summary>
/// <param name="level_1_ID">The Level_1_ID.</param>
/// <returns>A <see cref="F02Level1"/> object.</returns>
public F02Level1 FindF02Level1ByParentProperties(int level_1_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Level_1_ID.Equals(level_1_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F01Level1Coll"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="F01Level1Coll"/> collection.</returns>
public static F01Level1Coll NewF01Level1Coll()
{
return DataPortal.Create<F01Level1Coll>();
}
/// <summary>
/// Factory method. Loads a <see cref="F01Level1Coll"/> object.
/// </summary>
/// <returns>A reference to the fetched <see cref="F01Level1Coll"/> object.</returns>
public static F01Level1Coll GetF01Level1Coll()
{
return DataPortal.Fetch<F01Level1Coll>();
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F01Level1Coll"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private F01Level1Coll()
{
// Prevent direct creation
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="F01Level1Coll"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetF01Level1Coll", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
if (this.Count > 0)
this[0].FetchChildren(dr);
}
}
/// <summary>
/// Loads all <see cref="F01Level1Coll"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(F02Level1.GetF02Level1(dr));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F01Level1Coll"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
base.Child_Update();
}
}
#endregion
#region Pseudo Events
/// <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);
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Sink.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Dispatch.MessageQueues;
using Akka.Pattern;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Implementation.Stages;
using Reactive.Streams;
// ReSharper disable UnusedMember.Global
namespace Akka.Streams.Dsl
{
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> is a set of stream processing steps that has one open input.
/// Can be used as a <see cref="ISubscriber{T}"/>
/// </summary>
public sealed class Sink<TIn, TMat> : IGraph<SinkShape<TIn>, TMat>
{
public Sink(IModule module)
{
Module = module;
}
public SinkShape<TIn> Shape => (SinkShape<TIn>)Module.Shape;
public IModule Module { get; }
/// <summary>
/// Transform this <see cref="Sink"/> by applying a function to each *incoming* upstream element before
/// it is passed to the <see cref="Sink"/>
///
/// Backpressures when original <see cref="Sink"/> backpressures
///
/// Cancels when original <see cref="Sink"/> backpressures
/// </summary>
public Sink<TIn2, TMat> ContraMap<TIn2>(Func<TIn2, TIn> function)
=> Flow.FromFunction(function).ToMaterialized(this, Keep.Right);
/// <summary>
/// Connect this <see cref="Sink{TIn,TMat}"/> to a <see cref="Source{T,TMat}"/> and run it. The returned value is the materialized value
/// of the <see cref="Source{T,TMat}"/>, e.g. the <see cref="ISubscriber{T}"/>.
/// </summary>
public TMat2 RunWith<TMat2>(IGraph<SourceShape<TIn>, TMat2> source, IMaterializer materializer)
=> Source.FromGraph(source).To(this).Run(materializer);
/// <summary>
/// Transform only the materialized value of this Sink, leaving all other properties as they were.
/// </summary>
public Sink<TIn, TMat2> MapMaterializedValue<TMat2>(Func<TMat, TMat2> fn)
=> new Sink<TIn, TMat2>(Module.TransformMaterializedValue(fn));
/// <summary>
/// Change the attributes of this <see cref="IGraph{TShape}"/> to the given ones
/// and seal the list of attributes. This means that further calls will not be able
/// to remove these attributes, but instead add new ones. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.WithAttributes(Attributes attributes)
=> WithAttributes(attributes);
/// <summary>
/// Change the attributes of this <see cref="Sink{TIn,TMat}"/> to the given ones
/// and seal the list of attributes. This means that further calls will not be able
/// to remove these attributes, but instead add new ones. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
public Sink<TIn, TMat> WithAttributes(Attributes attributes)
=> new Sink<TIn, TMat>(Module.WithAttributes(attributes));
/// <summary>
/// Add the given attributes to this <see cref="IGraph{TShape}"/>.
/// Further calls to <see cref="WithAttributes"/>
/// will not remove these attributes. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.AddAttributes(Attributes attributes)
=> AddAttributes(attributes);
/// <summary>
/// Add the given attributes to this <see cref="Sink{TIn,TMat}"/>.
/// Further calls to <see cref="WithAttributes"/>
/// will not remove these attributes. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
public Sink<TIn, TMat> AddAttributes(Attributes attributes)
=> WithAttributes(Module.Attributes.And(attributes));
/// <summary>
/// Add a name attribute to this Sink.
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.Named(string name) => Named(name);
/// <summary>
/// Add a name attribute to this Sink.
/// </summary>
public Sink<TIn, TMat> Named(string name) => AddAttributes(Attributes.CreateName(name));
/// <summary>
/// Put an asynchronous boundary around this Sink.
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.Async() => Async();
/// <summary>
/// Put an asynchronous boundary around this Sink.
/// </summary>
public Sink<TIn, TMat> Async() => AddAttributes(new Attributes(Attributes.AsyncBoundary.Instance));
public override string ToString() => $"Sink({Shape}, {Module})";
}
public static class Sink
{
public static SinkShape<T> Shape<T>(string name) => new SinkShape<T>(new Inlet<T>(name + ".in"));
/// <summary>
/// A graph with the shape of a sink logically is a sink, this method makes
/// it so also in type.
/// </summary>
public static Sink<TIn, TMat> Wrap<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> graph)
=> graph is Sink<TIn, TMat>
? (Sink<TIn, TMat>) graph
: new Sink<TIn, TMat>(graph.Module);
/// <summary>
/// Helper to create <see cref="Sink{TIn, TMat}"/> from <see cref="ISubscriber{TIn}"/>.
/// </summary>
public static Sink<TIn, object> Create<TIn>(ISubscriber<TIn> subscriber)
=> new Sink<TIn, object>(new SubscriberSink<TIn>(subscriber, DefaultAttributes.SubscriberSink, Shape<TIn>("SubscriberSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the first value received.
/// If the stream completes before signaling at least a single element, the Task will be failed with a <see cref="NoSuchElementException"/>.
/// If the stream signals an error before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
public static Sink<TIn, Task<TIn>> First<TIn>()
=> FromGraph(new FirstOrDefault<TIn>(throwOnDefault: true))
.WithAttributes(DefaultAttributes.FirstOrDefaultSink)
.MapMaterializedValue(e =>
{
if (!e.IsFaulted && e.IsCompleted && e.Result == null)
throw new InvalidOperationException("Sink.First materialized on an empty stream");
return e;
});
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the first value received.
/// If the stream completes before signaling at least a single element, the Task will return default value.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
public static Sink<TIn, Task<TIn>> FirstOrDefault<TIn>()
=> FromGraph(new FirstOrDefault<TIn>()).WithAttributes(DefaultAttributes.FirstOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the last value received.
/// If the stream completes before signaling at least a single element, the Task will be failed with a <see cref="NoSuchElementException"/>.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
public static Sink<TIn, Task<TIn>> Last<TIn>()
=> FromGraph(new LastOrDefault<TIn>(throwOnDefault: true)).WithAttributes(DefaultAttributes.LastOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the last value received.
/// If the stream completes before signaling at least a single element, the Task will be return a default value.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
public static Sink<TIn, Task<TIn>> LastOrDefault<TIn>()
=> FromGraph(new LastOrDefault<TIn>()).WithAttributes(DefaultAttributes.LastOrDefaultSink);
public static Sink<TIn, Task<IImmutableList<TIn>>> Seq<TIn>() => FromGraph(new SeqStage<TIn>());
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="IPublisher{TIn}"/>.
/// that can handle one <see cref="ISubscriber{TIn}"/>.
/// </summary>
public static Sink<TIn, IPublisher<TIn>> Publisher<TIn>()
=> new Sink<TIn, IPublisher<TIn>>(new PublisherSink<TIn>(DefaultAttributes.PublisherSink, Shape<TIn>("PublisherSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into <see cref="IPublisher{TIn}"/>
/// that can handle more than one <see cref="ISubscriber{TIn}"/>.
/// </summary>
public static Sink<TIn, IPublisher<TIn>> FanoutPublisher<TIn>()
=> new Sink<TIn, IPublisher<TIn>>(new FanoutPublisherSink<TIn>(DefaultAttributes.FanoutPublisherSink, Shape<TIn>("FanoutPublisherSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will consume the stream and discard the elements.
/// </summary>
public static Sink<TIn, Task> Ignore<TIn>()
=> new Sink<TIn, Task>(new SinkholeSink<TIn>(Shape<TIn>("BlackholeSink"), DefaultAttributes.IgnoreSink));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will invoke the given <paramref name="action"/> for each received element.
/// The sink is materialized into a <see cref="Task"/> will be completed with success when reaching the
/// normal end of the stream, or completed with a failure if there is a failure signaled in
/// the stream..
/// </summary>
public static Sink<TIn, Task> ForEach<TIn>(Action<TIn> action) => Flow.Create<TIn>()
.Select(input =>
{
action(input);
return NotUsed.Instance;
}).ToMaterialized(Ignore<NotUsed>(), Keep.Right).Named("foreachSink");
/// <summary>
/// Combine several sinks with fan-out strategy like <see cref="Broadcast{TIn}"/> or <see cref="Balance{TIn}"/> and returns <see cref="Sink{TIn,TMat}"/>.
/// </summary>
public static Sink<TIn, NotUsed> Combine<TIn, TOut, TMat>(Func<int, IGraph<UniformFanOutShape<TIn, TOut>, TMat>> strategy, Sink<TOut, NotUsed> first, Sink<TOut, NotUsed> second, params Sink<TOut, NotUsed>[] rest)
=> FromGraph(GraphDsl.Create(builder =>
{
var d = builder.Add(strategy(rest.Length + 2));
builder.From(d.Out(0)).To(first);
builder.From(d.Out(1)).To(second);
var index = 2;
foreach (var sink in rest)
builder.From(d.Out(index++)).To(sink);
return new SinkShape<TIn>(d.In);
}));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will invoke the given <paramref name="action"/>
/// to each of the elements as they pass in. The sink is materialized into a <see cref="Task"/>.
///
/// If the action throws an exception and the supervision decision is
/// <see cref="Directive.Stop"/> the <see cref="Task"/> will be completed with failure.
///
/// If the action throws an exception and the supervision decision is
/// <see cref="Directive.Resume"/> or <see cref="Directive.Restart"/> the
/// element is dropped and the stream continues.
///
/// <para/>
/// See also <seealso cref="SelectAsyncUnordered{TIn,TOut}"/>
/// </summary>
public static Sink<TIn, Task> ForEachParallel<TIn>(int parallelism, Action<TIn> action) => Flow.Create<TIn>()
.SelectAsyncUnordered(parallelism, input => Task.Run(() =>
{
action(input);
return NotUsed.Instance;
})).ToMaterialized(Ignore<NotUsed>(), Keep.Right);
/// <summary>
/// A <see cref="Sink{TIn, Task}"/> that will invoke the given <paramref name="aggregate"/> function for every received element,
/// giving it its previous output (or the given <paramref name="zero"/> value) and the element as input.
/// The returned <see cref="Task"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with the streams exception
/// if there is a failure signaled in the stream.
/// <seealso cref="AggregateAsync{TIn,TOut}"/>
/// </summary>
public static Sink<TIn, Task<TOut>> Aggregate<TIn, TOut>(TOut zero, Func<TOut, TIn, TOut> aggregate)
=> Flow.Create<TIn>()
.Aggregate(zero, aggregate)
.ToMaterialized(First<TOut>(), Keep.Right)
.Named("AggregateSink");
/// <summary>
/// A <see cref="Sink{TIn, Task}"/> that will invoke the given asynchronous function for every received element,
/// giving it its previous output (or the given <paramref name="zero"/> value) and the element as input.
/// The returned <see cref="Task"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with "Failure"
/// if there is a failure signaled in the stream.
///
/// <seealso cref="Aggregate{TIn,TOut}"/>
/// </summary>
public static Sink<TIn, Task<TOut>> AggregateAsync<TIn, TOut>(TOut zero, Func<TOut, TIn, Task<TOut>> aggregate)
=> Flow.Create<TIn, Task<TOut>>()
.AggregateAsync(zero, aggregate)
.ToMaterialized(First<TOut>(), Keep.Right)
.Named("AggregateAsyncSink");
/// <summary>
/// A <see cref="Sink{TIn,Task}"/> that will invoke the given <paramref name="reduce"/> for every received element, giving it its previous
/// output (from the second element) and the element as input.
/// The returned <see cref="Task{TIn}"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with `Failure`
/// if there is a failure signaled in the stream.
///
/// If the stream is empty (i.e. completes before signalling any elements),
/// the sum stage will fail its downstream with a <see cref="NoSuchElementException"/>,
/// which is semantically in-line with that standard library collections do in such situations.
/// </summary>
public static Sink<TIn, Task<TIn>> Sum<TIn>(Func<TIn, TIn, TIn> reduce) => Flow.Create<TIn>()
.Sum(reduce)
.ToMaterialized(First<TIn>(), Keep.Right)
.Named("SumSink");
/// <summary>
/// A <see cref="Sink{TIn, NotUsed}"/> that when the flow is completed, either through a failure or normal
/// completion, apply the provided function with <paramref name="success"/> or <paramref name="failure"/>.
/// </summary>
public static Sink<TIn, NotUsed> OnComplete<TIn>(Action success, Action<Exception> failure)
=> Flow.Create<TIn>()
.Transform(() => new OnCompleted<TIn, NotUsed>(success, failure))
.To(Ignore<NotUsed>())
.Named("OnCompleteSink");
///<summary>
/// Sends the elements of the stream to the given <see cref="IActorRef"/>.
/// If the target actor terminates the stream will be canceled.
/// When the stream is completed successfully the given <paramref name="onCompleteMessage"/>
/// will be sent to the destination actor.
/// When the stream is completed with failure a <see cref="Status.Failure"/>
/// message will be sent to the destination actor.
///
/// It will request at most <see cref="ActorMaterializerSettings.MaxInputBufferSize"/> number of elements from
/// upstream, but there is no back-pressure signal from the destination actor,
/// i.e. if the actor is not consuming the messages fast enough the mailbox
/// of the actor will grow. For potentially slow consumer actors it is recommended
/// to use a bounded mailbox with zero <see cref="BoundedMessageQueue.PushTimeOut"/> or use a rate
/// limiting stage in front of this <see cref="Sink{TIn, TMat}"/>.
///</summary>
public static Sink<TIn, NotUsed> ActorRef<TIn>(IActorRef actorRef, object onCompleteMessage)
=> new Sink<TIn, NotUsed>(new ActorRefSink<TIn>(actorRef, onCompleteMessage, DefaultAttributes.ActorRefSink, Shape<TIn>("ActorRefSink")));
/// <summary>
/// Sends the elements of the stream to the given <see cref="IActorRef"/> that sends back back-pressure signal.
/// First element is always <paramref name="onInitMessage"/>, then stream is waiting for acknowledgement message
/// <paramref name="ackMessage"/> from the given actor which means that it is ready to process
/// elements.It also requires <paramref name="ackMessage"/> message after each stream element
/// to make backpressure work.
///
/// If the target actor terminates the stream will be canceled.
/// When the stream is completed successfully the given <paramref name="onCompleteMessage"/>
/// will be sent to the destination actor.
/// When the stream is completed with failure - result of <paramref name="onFailureMessage"/>
/// function will be sent to the destination actor.
/// </summary>
public static Sink<TIn, NotUsed> ActorRefWithAck<TIn>(IActorRef actorRef, object onInitMessage, object ackMessage,
object onCompleteMessage, Func<Exception, object> onFailureMessage = null)
{
onFailureMessage = onFailureMessage ?? (ex => new Status.Failure(ex));
return
FromGraph(new ActorRefBackpressureSinkStage<TIn>(actorRef, onInitMessage, ackMessage,
onCompleteMessage, onFailureMessage));
}
///<summary>
/// Creates a <see cref="Sink{TIn,TMat}"/> that is materialized to an <see cref="IActorRef"/> which points to an Actor
/// created according to the passed in <see cref="Props"/>. Actor created by the <paramref name="props"/> should
/// be <see cref="ActorSubscriberSink{TIn}"/>.
///</summary>
public static Sink<TIn, IActorRef> ActorSubscriber<TIn>(Props props)
=> new Sink<TIn, IActorRef>(new ActorSubscriberSink<TIn>(props, DefaultAttributes.ActorSubscriberSink, Shape<TIn>("ActorSubscriberSink")));
///<summary>
/// <para>
/// Creates a <see cref="Sink{TIn,TMat}"/> that is materialized as an <see cref="ISinkQueue{TIn}"/>.
/// <see cref="ISinkQueue{TIn}.PullAsync"/> method is pulling element from the stream and returns <see cref="Task{Option}"/>.
/// <see cref="Task"/> completes when element is available.
/// </para>
/// <para>
/// Before calling the pull method a second time you need to wait until previous future completes.
/// Pull returns failed future with <see cref="IllegalStateException"/> if previous future has not yet completed.
/// </para>
/// <para>
/// <see cref="Sink{TIn,TMat}"/> will request at most number of elements equal to size of inputBuffer from
/// upstream and then stop back pressure. You can configure size of input by using WithAttributes method.
/// </para>
/// <para>
/// For stream completion you need to pull all elements from <see cref="ISinkQueue{T}"/> including last None
/// as completion marker.
/// </para>
///</summary>
public static Sink<TIn, ISinkQueue<TIn>> Queue<TIn>() => FromGraph(new QueueSink<TIn>());
/// <summary>
/// Creates a real <see cref="Sink{TIn,TMat}"/> upon receiving the first element. Internal <see cref="Sink{TIn,TMat}"/> will not be created if there are no elements,
/// because of completion or error.
///
/// If <paramref name="sinkFactory"/> throws an exception and the supervision decision is <see cref="Supervision.Directive.Stop"/>
/// the <see cref="Task"/> will be completed with failure. For all other supervision options it will try to create sink with next element.
///
/// <paramref name="fallback"/> will be executed when there was no elements and completed is received from upstream.
/// </summary>
public static Sink<TIn, Task<TMat>> LazySink<TIn, TMat>(Func<TIn, Task<Sink<TIn, TMat>>> sinkFactory,
Func<TMat> fallback) => FromGraph(new LazySink<TIn, TMat>(sinkFactory, fallback));
/// <summary>
/// A graph with the shape of a sink logically is a sink, this method makes
/// it so also in type.
/// </summary>
public static Sink<TIn, TMat> FromGraph<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> graph)
=> graph is Sink<TIn, TMat>
? (Sink<TIn, TMat>) graph
: new Sink<TIn, TMat>(graph.Module);
/// <summary>
/// Helper to create <see cref="Sink{TIn,TMat}"/> from <see cref="ISubscriber{TIn}"/>.
/// </summary>
public static Sink<TIn, NotUsed> FromSubscriber<TIn>(ISubscriber<TIn> subscriber)
=> new Sink<TIn, NotUsed>(new SubscriberSink<TIn>(subscriber, DefaultAttributes.SubscriberSink, Shape<TIn>("SubscriberSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that immediately cancels its upstream after materialization.
/// </summary>
public static Sink<TIn, NotUsed> Cancelled<TIn>()
=> new Sink<TIn, NotUsed>(new CancelSink<TIn>(DefaultAttributes.CancelledSink, Shape<TIn>("CancelledSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="IPublisher{TIn}"/>.
/// If <paramref name="fanout"/> is true, the materialized <see cref="IPublisher{TIn}"/> will support multiple <see cref="ISubscriber{TIn}"/>`s and
/// the size of the <see cref="ActorMaterializerSettings.MaxInputBufferSize"/> configured for this stage becomes the maximum number of elements that
/// the fastest <see cref="ISubscriber{T}"/> can be ahead of the slowest one before slowing
/// the processing down due to back pressure.
///
/// If <paramref name="fanout"/> is false then the materialized <see cref="IPublisher{TIn}"/> will only support a single <see cref="ISubscriber{TIn}"/> and
/// reject any additional <see cref="ISubscriber{TIn}"/>`s.
/// </summary>
public static Sink<TIn, IPublisher<TIn>> AsPublisher<TIn>(bool fanout)
{
SinkModule<TIn, IPublisher<TIn>> publisherSink;
if (fanout)
publisherSink = new FanoutPublisherSink<TIn>(DefaultAttributes.FanoutPublisherSink, Shape<TIn>("FanoutPublisherSink"));
else
publisherSink = new PublisherSink<TIn>(DefaultAttributes.PublisherSink, Shape<TIn>("PublisherSink"));
return new Sink<TIn, IPublisher<TIn>>(publisherSink);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>ExtensionFeedItem</c> resource.</summary>
public sealed partial class ExtensionFeedItemName : gax::IResourceName, sys::IEquatable<ExtensionFeedItemName>
{
/// <summary>The possible contents of <see cref="ExtensionFeedItemName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>.
/// </summary>
CustomerFeedItem = 1,
}
private static gax::PathTemplate s_customerFeedItem = new gax::PathTemplate("customers/{customer_id}/extensionFeedItems/{feed_item_id}");
/// <summary>Creates a <see cref="ExtensionFeedItemName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ExtensionFeedItemName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ExtensionFeedItemName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ExtensionFeedItemName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ExtensionFeedItemName"/> with the pattern
/// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ExtensionFeedItemName"/> constructed from the provided ids.</returns>
public static ExtensionFeedItemName FromCustomerFeedItem(string customerId, string feedItemId) =>
new ExtensionFeedItemName(ResourceNameType.CustomerFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ExtensionFeedItemName"/> with pattern
/// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ExtensionFeedItemName"/> with pattern
/// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>.
/// </returns>
public static string Format(string customerId, string feedItemId) => FormatCustomerFeedItem(customerId, feedItemId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ExtensionFeedItemName"/> with pattern
/// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ExtensionFeedItemName"/> with pattern
/// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>.
/// </returns>
public static string FormatCustomerFeedItem(string customerId, string feedItemId) =>
s_customerFeedItem.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ExtensionFeedItemName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="extensionFeedItemName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ExtensionFeedItemName"/> if successful.</returns>
public static ExtensionFeedItemName Parse(string extensionFeedItemName) => Parse(extensionFeedItemName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ExtensionFeedItemName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="extensionFeedItemName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ExtensionFeedItemName"/> if successful.</returns>
public static ExtensionFeedItemName Parse(string extensionFeedItemName, bool allowUnparsed) =>
TryParse(extensionFeedItemName, allowUnparsed, out ExtensionFeedItemName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ExtensionFeedItemName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="extensionFeedItemName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ExtensionFeedItemName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string extensionFeedItemName, out ExtensionFeedItemName result) =>
TryParse(extensionFeedItemName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ExtensionFeedItemName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="extensionFeedItemName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ExtensionFeedItemName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string extensionFeedItemName, bool allowUnparsed, out ExtensionFeedItemName result)
{
gax::GaxPreconditions.CheckNotNull(extensionFeedItemName, nameof(extensionFeedItemName));
gax::TemplatedResourceName resourceName;
if (s_customerFeedItem.TryParseName(extensionFeedItemName, out resourceName))
{
result = FromCustomerFeedItem(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(extensionFeedItemName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ExtensionFeedItemName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedItemId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
FeedItemId = feedItemId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ExtensionFeedItemName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
public ExtensionFeedItemName(string customerId, string feedItemId) : this(ResourceNameType.CustomerFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>FeedItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FeedItemId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerFeedItem: return s_customerFeedItem.Expand(CustomerId, FeedItemId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ExtensionFeedItemName);
/// <inheritdoc/>
public bool Equals(ExtensionFeedItemName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ExtensionFeedItemName a, ExtensionFeedItemName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ExtensionFeedItemName a, ExtensionFeedItemName b) => !(a == b);
}
public partial class ExtensionFeedItem
{
/// <summary>
/// <see cref="ExtensionFeedItemName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal ExtensionFeedItemName ResourceNameAsExtensionFeedItemName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ExtensionFeedItemName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="TargetedCampaign"/> resource name property.
/// </summary>
internal CampaignName TargetedCampaignAsCampaignName
{
get => string.IsNullOrEmpty(TargetedCampaign) ? null : CampaignName.Parse(TargetedCampaign, allowUnparsed: true);
set => TargetedCampaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="TargetedAdGroup"/> resource name property.
/// </summary>
internal AdGroupName TargetedAdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(TargetedAdGroup) ? null : AdGroupName.Parse(TargetedAdGroup, allowUnparsed: true);
set => TargetedAdGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="GeoTargetConstantName"/>-typed view over the <see cref="TargetedGeoTargetConstant"/> resource
/// name property.
/// </summary>
internal GeoTargetConstantName TargetedGeoTargetConstantAsGeoTargetConstantName
{
get => string.IsNullOrEmpty(TargetedGeoTargetConstant) ? null : GeoTargetConstantName.Parse(TargetedGeoTargetConstant, allowUnparsed: true);
set => TargetedGeoTargetConstant = value?.ToString() ?? "";
}
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
#if DOTNET35
using System;
using System.Collections.Generic;
using Rhino.Mocks.Exceptions;
using Rhino.Mocks.Generated;
using Rhino.Mocks.Interfaces;
namespace Rhino.Mocks
{
/// <summary>
/// A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks
/// </summary>
public static class RhinoMocksExtensions
{
/// <summary>
/// Create an expectation on this mock for this action to occur
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<VoidType> Expect<T>(this T mock, Action<T> action)
where T : class
{
return Expect<T, VoidType>(mock, t =>
{
action(t);
return null;
});
}
/// <summary>
/// Reset all expectations on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
public static void BackToRecord<T>(this T mock)
{
BackToRecord(mock, BackToRecordOptions.All);
}
/// <summary>
/// Reset the selected expectation on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="options">The options to reset the expectations on this mock.</param>
public static void BackToRecord<T>(this T mock, BackToRecordOptions options)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
var mocks = mockedObject.Repository;
mocks.BackToRecord(mock, options);
}
/// <summary>
/// Cause the mock state to change to replay, any further call is compared to the
/// ones that were called in the record state.
/// </summary>
/// <param name="mock">the mocked object to move to replay state</param>
public static void Replay<T>(this T mock)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
var mocks = mockedObject.Repository;
if (mocks.IsInReplayMode(mock) != true)
mocks.Replay(mockedObject);
}
/// <summary>
/// Gets the mock repository for this specificied mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <returns></returns>
public static MockRepository GetMockRepository<T>(this T mock)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
return mockedObject.Repository;
}
/// <summary>
/// Create an expectation on this mock for this action to occur
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<R> Expect<T, R>(this T mock, Function<T, R> action)
where T : class
{
if (mock == null)
throw new ArgumentNullException("mock", "You cannot mock a null instance");
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
MockRepository mocks = mockedObject.Repository;
var isInReplayMode = mocks.IsInReplayMode(mock);
mocks.BackToRecord(mock, BackToRecordOptions.None);
action(mock);
IMethodOptions<R> options = LastCall.GetOptions<R>();
options.TentativeReturn();
if (isInReplayMode)
mocks.ReplayCore(mock, false);
return options;
}
/// <summary>
/// Tell the mock object to perform a certain action when a matching
/// method is called.
/// Does not create an expectation for this method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<object> Stub<T>(this T mock, Action<T> action)
where T : class
{
return Stub<T, object>(mock, t =>
{
action(t);
return null;
});
}
/// <summary>
/// Tell the mock object to perform a certain action when a matching
/// method is called.
/// Does not create an expectation for this method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<R> Stub<T, R>(this T mock, Function<T, R> action)
where T : class
{
return Expect(mock, action).Repeat.Times(0, int.MaxValue);
}
/// <summary>
/// Gets the arguments for calls made on this mock object and the method that was called
/// in the action.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
/// <example>
/// Here we will get all the arguments for all the calls made to DoSomething(int)
/// <code>
/// var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0))
/// </code>
/// </example>
public static IList<object[]> GetArgumentsForCallsMadeOn<T>(this T mock, Action<T> action)
{
return GetArgumentsForCallsMadeOn(mock, action, DefaultConstraintSetup);
}
/// <summary>
/// Gets the arguments for calls made on this mock object and the method that was called
/// in the action and matches the given constraints
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
/// <returns></returns>
/// <example>
/// Here we will get all the arguments for all the calls made to DoSomething(int)
/// <code>
/// var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0))
/// </code>
/// </example>
public static IList<object[]> GetArgumentsForCallsMadeOn<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
return GetExpectationsToVerify(mock, action, setupConstraints).ArgumentsForAllCalls;
}
/// <summary>
/// Asserts that a particular method was called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasCalled<T>(this T mock, Action<T> action)
{
AssertWasCalled(mock, action, DefaultConstraintSetup);
}
private static void DefaultConstraintSetup(IMethodOptions<object> options)
{
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasCalled<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints);
foreach (var args in verificationInformation.ArgumentsForAllCalls)
{
if (verificationInformation.Expected.IsExpected(args))
{
verificationInformation.Expected.AddActualCall();
}
}
if (verificationInformation.Expected.ExpectationSatisfied)
return;
throw new ExpectationViolationException(verificationInformation.Expected.BuildVerificationFailureMessage());
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasCalled<T>(this T mock, Func<T, object> action)
{
var newAction = new Action<T>(t => action(t));
AssertWasCalled(mock, newAction, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasCalled<T>(this T mock, Func<T, object> action, Action<IMethodOptions<object>> setupConstraints)
{
var newAction = new Action<T>(t => action(t));
AssertWasCalled(mock, newAction, setupConstraints);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasNotCalled<T>(this T mock, Action<T> action)
{
AssertWasNotCalled(mock, action, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasNotCalled<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints);
foreach (var args in verificationInformation.ArgumentsForAllCalls)
{
if (verificationInformation.Expected.IsExpected(args))
throw new ExpectationViolationException("Expected that " +
verificationInformation.Expected.ErrorMessage +
" would not be called, but it was found on the actual calls made on the mocked object.");
}
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasNotCalled<T>(this T mock, Func<T, object> action)
{
var newAction = new Action<T>(t => action(t));
AssertWasNotCalled(mock, newAction, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasNotCalled<T>(this T mock, Func<T, object> action, Action<IMethodOptions<object>> setupConstraints)
{
var newAction = new Action<T>(t => action(t));
AssertWasNotCalled(mock, newAction, setupConstraints);
}
private static ExpectationVerificationInformation GetExpectationsToVerify<T>(T mock, Action<T> action,
Action<IMethodOptions<object>>
setupConstraints)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
MockRepository mocks = mockedObject.Repository;
if (mocks.IsInReplayMode(mockedObject) == false)
{
throw new InvalidOperationException(
"Cannot assert on an object that is not in replay mode. Did you forget to call ReplayAll() ?");
}
var mockToRecordExpectation =
(T)mocks.DynamicMock(FindAppropriteType<T>(mockedObject), mockedObject.ConstructorArguments);
action(mockToRecordExpectation);
AssertExactlySingleExpectaton(mocks, mockToRecordExpectation);
IMethodOptions<object> lastMethodCall = mocks.LastMethodCall<object>(mockToRecordExpectation);
lastMethodCall.TentativeReturn();
if (setupConstraints != null)
{
setupConstraints(lastMethodCall);
}
ExpectationsList expectationsToVerify = mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation);
if (expectationsToVerify.Count == 0)
throw new InvalidOperationException(
"The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()");
IExpectation expected = expectationsToVerify[0];
ICollection<object[]> argumentsForAllCalls = mockedObject.GetCallArgumentsFor(expected.Method);
return new ExpectationVerificationInformation
{
ArgumentsForAllCalls = new List<object[]>(argumentsForAllCalls),
Expected = expected
};
}
/// <summary>
/// Finds the approprite implementation type of this item.
/// This is the class or an interface outside of the rhino mocks.
/// </summary>
/// <param name="mockedObj">The mocked obj.</param>
/// <returns></returns>
private static Type FindAppropriteType<T>(IMockedObject mockedObj)
{
foreach (var type in mockedObj.ImplementedTypes)
{
if(type.IsClass && typeof(T).IsAssignableFrom(type))
return type;
}
foreach (var type in mockedObj.ImplementedTypes)
{
if(type.Assembly==typeof(IMockedObject).Assembly || !typeof(T).IsAssignableFrom(type))
continue;
return type;
}
return mockedObj.ImplementedTypes[0];
}
/// <summary>
/// Verifies all expectations on this mock object
/// </summary>
/// <param name="mockObject">The mock object.</param>
public static void VerifyAllExpectations(this object mockObject)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mockObject);
mockedObject.Repository.Verify(mockedObject);
}
/// <summary>
/// Gets the event raiser for the event that was called in the action passed
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <returns></returns>
public static IEventRaiser GetEventRaiser<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription)
where TEventSource : class
{
return mockObject
.Stub(eventSubscription)
.IgnoreArguments()
.GetEventRaiser();
}
/// <summary>
/// Raise the specified event using the passed arguments.
/// The even is extracted from the passed labmda
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public static void Raise<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription, object sender, EventArgs args)
where TEventSource : class
{
var eventRaiser = GetEventRaiser(mockObject, eventSubscription);
eventRaiser.Raise(sender, args);
}
/// <summary>
/// Raise the specified event using the passed arguments.
/// The even is extracted from the passed labmda
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <param name="args">The args.</param>
public static void Raise<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription, params object[] args)
where TEventSource : class
{
var eventRaiser = GetEventRaiser(mockObject, eventSubscription);
eventRaiser.Raise(args);
}
/// <summary>TODO: Make this better! It currently breaks down when mocking classes or
/// ABC's that call other virtual methods which are getting intercepted too. I wish
/// we could just walk Expression{Action{Action{T}} to assert only a single
/// method is being made.
///
/// The workaround is to not call foo.AssertWasCalled .. rather foo.VerifyAllExpectations()</summary>
/// <typeparam name="T">The type of mock object</typeparam>
/// <param name="mocks">The mock repository</param>
/// <param name="mockToRecordExpectation">The actual mock object to assert expectations on.</param>
private static void AssertExactlySingleExpectaton<T>(MockRepository mocks, T mockToRecordExpectation)
{
if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count == 0)
throw new InvalidOperationException(
"No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call");
if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count > 1)
throw new InvalidOperationException(
"You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations");
}
#region Nested type: VoidType
/// <summary>
/// Fake type that disallow creating it.
/// Should have been System.Type, but we can't use it.
/// </summary>
public class VoidType
{
private VoidType()
{
}
}
#endregion
}
}
#endif
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
namespace SchoolBusAPI.Models
{
/// <summary>
/// The School Bus entity, including only information that is of specific interest to the School Bus inspector and not tracked in other systems such as ICBC or NSC
/// </summary>
[MetaDataExtension (Description = "The School Bus entity, including only information that is of specific interest to the School Bus inspector and not tracked in other systems such as ICBC or NSC")]
public partial class SchoolBus : IEquatable<SchoolBus>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public SchoolBus()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="SchoolBus" /> class.
/// </summary>
/// <param name="Id">Primary Key (required).</param>
/// <param name="Regi">The ICBC Registration number for the School Bus.</param>
/// <param name="Plate">The ICBC Plate Number for the School Bus.</param>
/// <param name="VIN">The VIN for the School Bus.</param>
/// <param name="SchoolBusOwner">SchoolBusOwner.</param>
/// <param name="PermitNumber">The (generated) permit number for the School Bus. This will be added by the Inspector before the School Bus Permit can be printed and the bus can go into service..</param>
/// <param name="Status">Enumerated type of Status - Inactive, Active, Archived.</param>
/// <param name="IsOutOfProvince">IsOutOfProvince.</param>
/// <param name="ServiceArea">ServiceArea.</param>
/// <param name="HomeTerminalAddr1">Address 1 of physical location of the School Bus..</param>
/// <param name="HomeTerminalAddr2">Address 2 of physical location of the School Bus..</param>
/// <param name="HomeTerminalCity">City of physical location of the School Bus..</param>
/// <param name="HomeTerminalProvince">Province of physical location of the School Bus - free form..</param>
/// <param name="HomeTerminalPostalCode">Postal Code of physical location of the School Bus..</param>
/// <param name="HomeTerminalComment">A comment about the physical location of the bus so that the Inspector can more easily find it for an inspection.</param>
/// <param name="Restrictions">Text of any restrictions to be printed on the school bus permit..</param>
/// <param name="NextInspectionDate">The next inspection date for this School Bus. Set at the time an inspection is set..</param>
/// <param name="NextInspectionType">An enumerated type (by the UI) to indicate the type of the next inspection - Annual or Re-inspection based on the Pass/Fail status of the most recent inspection..</param>
/// <param name="SchoolBusDistrict">The School District in which the School Bus operates. The school bus may or may not be associated with the School District itself - we just track where it is regardless..</param>
/// <param name="IsIndependentSchool">True if the School Bus is associated with an Independent School. If true, the name of the Independent School should be in the companion field..</param>
/// <param name="NameOfIndependentSchool">The name of the Independent School to which the School Bus is associated. Should be null if the companion isIndependentSchool is false..</param>
/// <param name="SchoolBusClass">The enumerated class of School Bus..</param>
/// <param name="SchoolBusBodyType">The enumerated body type of the School Bus..</param>
/// <param name="SchoolBusBodyTypeOther">The enumerated body type of the School Bus..</param>
/// <param name="SchoolBusUnitNumber">The unit number of the Bus as defined by the School Bus owner - freeform text..</param>
/// <param name="SchoolBusSeatingCapacity">The maximum number of passengers in the bus based on the specific use of the bus. For example, the same 2-per seat / 24-passenger model might have a seating capacity of 36 if the specific bus is to be used for small children, 3 per seat..</param>
/// <param name="MobilityAidCapacity">The number of mobility aid passenger seats in the bus..</param>
public SchoolBus(int Id, string Regi = null, string Plate = null, string VIN = null, SchoolBusOwner SchoolBusOwner = null, string PermitNumber = null, string Status = null, bool? IsOutOfProvince = null, ServiceArea ServiceArea = null, string HomeTerminalAddr1 = null, string HomeTerminalAddr2 = null, City HomeTerminalCity = null, string HomeTerminalProvince = null, string HomeTerminalPostalCode = null, string HomeTerminalComment = null, string Restrictions = null, DateTime? NextInspectionDate = null, string NextInspectionType = null, SchoolDistrict SchoolBusDistrict = null, bool? IsIndependentSchool = null, string NameOfIndependentSchool = null, string SchoolBusClass = null, string SchoolBusBodyType = null, string SchoolBusBodyTypeOther = null, string SchoolBusUnitNumber = null, int? SchoolBusSeatingCapacity = null, int? MobilityAidCapacity = null)
{
this.Id = Id;
this.Regi = Regi;
this.Plate = Plate;
this.VIN = VIN;
this.SchoolBusOwner = SchoolBusOwner;
this.PermitNumber = PermitNumber;
this.Status = Status;
this.IsOutOfProvince = IsOutOfProvince;
this.ServiceArea = ServiceArea;
this.HomeTerminalAddr1 = HomeTerminalAddr1;
this.HomeTerminalAddr2 = HomeTerminalAddr2;
this.HomeTerminalCity = HomeTerminalCity;
this.HomeTerminalProvince = HomeTerminalProvince;
this.HomeTerminalPostalCode = HomeTerminalPostalCode;
this.HomeTerminalComment = HomeTerminalComment;
this.Restrictions = Restrictions;
this.NextInspectionDate = NextInspectionDate;
this.NextInspectionType = NextInspectionType;
this.SchoolBusDistrict = SchoolBusDistrict;
this.IsIndependentSchool = IsIndependentSchool;
this.NameOfIndependentSchool = NameOfIndependentSchool;
this.SchoolBusClass = SchoolBusClass;
this.SchoolBusBodyType = SchoolBusBodyType;
this.SchoolBusBodyTypeOther = SchoolBusBodyTypeOther;
this.SchoolBusUnitNumber = SchoolBusUnitNumber;
this.SchoolBusSeatingCapacity = SchoolBusSeatingCapacity;
this.MobilityAidCapacity = MobilityAidCapacity;
}
/// <summary>
/// Primary Key
/// </summary>
/// <value>Primary Key</value>
[MetaDataExtension (Description = "Primary Key")]
public int Id { get; set; }
/// <summary>
/// The ICBC Registration number for the School Bus
/// </summary>
/// <value>The ICBC Registration number for the School Bus</value>
[MetaDataExtension (Description = "The ICBC Registration number for the School Bus")]
public string Regi { get; set; }
/// <summary>
/// The ICBC Plate Number for the School Bus
/// </summary>
/// <value>The ICBC Plate Number for the School Bus</value>
[MetaDataExtension (Description = "The ICBC Plate Number for the School Bus")]
public string Plate { get; set; }
/// <summary>
/// The VIN for the School Bus
/// </summary>
/// <value>The VIN for the School Bus</value>
[MetaDataExtension (Description = "The VIN for the School Bus")]
public string VIN { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwner
/// </summary>
public SchoolBusOwner SchoolBusOwner { get; set; }
[ForeignKey("SchoolBusOwner")]
public int SchoolBusOwnerRefId { get; set; }
/// <summary>
/// The (generated) permit number for the School Bus. This will be added by the Inspector before the School Bus Permit can be printed and the bus can go into service.
/// </summary>
/// <value>The (generated) permit number for the School Bus. This will be added by the Inspector before the School Bus Permit can be printed and the bus can go into service.</value>
[MetaDataExtension (Description = "The (generated) permit number for the School Bus. This will be added by the Inspector before the School Bus Permit can be printed and the bus can go into service.")]
public string PermitNumber { get; set; }
/// <summary>
/// Enumerated type of Status - Inactive, Active, Archived
/// </summary>
/// <value>Enumerated type of Status - Inactive, Active, Archived</value>
[MetaDataExtension (Description = "Enumerated type of Status - Inactive, Active, Archived")]
public string Status { get; set; }
/// <summary>
/// Gets or Sets IsOutOfProvince
/// </summary>
public bool? IsOutOfProvince { get; set; }
/// <summary>
/// Gets or Sets ServiceArea
/// </summary>
public ServiceArea ServiceArea { get; set; }
[ForeignKey("ServiceArea")]
public int? ServiceAreaRefId { get; set; }
/// <summary>
/// Address 1 of physical location of the School Bus.
/// </summary>
/// <value>Address 1 of physical location of the School Bus.</value>
[MetaDataExtension (Description = "Address 1 of physical location of the School Bus.")]
public string HomeTerminalAddr1 { get; set; }
/// <summary>
/// Address 2 of physical location of the School Bus.
/// </summary>
/// <value>Address 2 of physical location of the School Bus.</value>
[MetaDataExtension (Description = "Address 2 of physical location of the School Bus.")]
public string HomeTerminalAddr2 { get; set; }
/// <summary>
/// City of physical location of the School Bus.
/// </summary>
/// <value>City of physical location of the School Bus.</value>
[MetaDataExtension (Description = "City of physical location of the School Bus.")]
public City HomeTerminalCity { get; set; }
/// <summary>
/// Province of physical location of the School Bus - free form.
/// </summary>
/// <value>Province of physical location of the School Bus - free form.</value>
[MetaDataExtension (Description = "Province of physical location of the School Bus - free form.")]
public string HomeTerminalProvince { get; set; }
/// <summary>
/// Postal Code of physical location of the School Bus.
/// </summary>
/// <value>Postal Code of physical location of the School Bus.</value>
[MetaDataExtension (Description = "Postal Code of physical location of the School Bus.")]
public string HomeTerminalPostalCode { get; set; }
/// <summary>
/// A comment about the physical location of the bus so that the Inspector can more easily find it for an inspection
/// </summary>
/// <value>A comment about the physical location of the bus so that the Inspector can more easily find it for an inspection</value>
[MetaDataExtension (Description = "A comment about the physical location of the bus so that the Inspector can more easily find it for an inspection")]
public string HomeTerminalComment { get; set; }
/// <summary>
/// Text of any restrictions to be printed on the school bus permit.
/// </summary>
/// <value>Text of any restrictions to be printed on the school bus permit.</value>
[MetaDataExtension (Description = "Text of any restrictions to be printed on the school bus permit.")]
public string Restrictions { get; set; }
/// <summary>
/// The next inspection date for this School Bus. Set at the time an inspection is set.
/// </summary>
/// <value>The next inspection date for this School Bus. Set at the time an inspection is set.</value>
[MetaDataExtension (Description = "The next inspection date for this School Bus. Set at the time an inspection is set.")]
public DateTime? NextInspectionDate { get; set; }
/// <summary>
/// An enumerated type (by the UI) to indicate the type of the next inspection - Annual or Re-inspection based on the Pass/Fail status of the most recent inspection.
/// </summary>
/// <value>An enumerated type (by the UI) to indicate the type of the next inspection - Annual or Re-inspection based on the Pass/Fail status of the most recent inspection.</value>
[MetaDataExtension (Description = "An enumerated type (by the UI) to indicate the type of the next inspection - Annual or Re-inspection based on the Pass/Fail status of the most recent inspection.")]
public string NextInspectionType { get; set; }
/// <summary>
/// The School District in which the School Bus operates. The school bus may or may not be associated with the School District itself - we just track where it is regardless.
/// </summary>
/// <value>The School District in which the School Bus operates. The school bus may or may not be associated with the School District itself - we just track where it is regardless.</value>
[MetaDataExtension (Description = "The School District in which the School Bus operates. The school bus may or may not be associated with the School District itself - we just track where it is regardless.")]
public SchoolDistrict SchoolBusDistrict { get; set; }
[ForeignKey("SchoolBusDistrict")]
public int? SchoolBusDistrictRefId { get; set; }
/// <summary>
/// True if the School Bus is associated with an Independent School. If true, the name of the Independent School should be in the companion field.
/// </summary>
/// <value>True if the School Bus is associated with an Independent School. If true, the name of the Independent School should be in the companion field.</value>
[MetaDataExtension (Description = "True if the School Bus is associated with an Independent School. If true, the name of the Independent School should be in the companion field.")]
public bool? IsIndependentSchool { get; set; }
/// <summary>
/// The name of the Independent School to which the School Bus is associated. Should be null if the companion isIndependentSchool is false.
/// </summary>
/// <value>The name of the Independent School to which the School Bus is associated. Should be null if the companion isIndependentSchool is false.</value>
[MetaDataExtension (Description = "The name of the Independent School to which the School Bus is associated. Should be null if the companion isIndependentSchool is false.")]
public string NameOfIndependentSchool { get; set; }
/// <summary>
/// The enumerated class of School Bus.
/// </summary>
/// <value>The enumerated class of School Bus.</value>
[MetaDataExtension (Description = "The enumerated class of School Bus.")]
public string SchoolBusClass { get; set; }
/// <summary>
/// The enumerated body type of the School Bus.
/// </summary>
/// <value>The enumerated body type of the School Bus.</value>
[MetaDataExtension (Description = "The enumerated body type of the School Bus.")]
public string SchoolBusBodyType { get; set; }
/// <summary>
/// The enumerated body type of the School Bus.
/// </summary>
/// <value>The enumerated body type of the School Bus.</value>
[MetaDataExtension (Description = "The enumerated body type of the School Bus.")]
public string SchoolBusBodyTypeOther { get; set; }
/// <summary>
/// The unit number of the Bus as defined by the School Bus owner - freeform text.
/// </summary>
/// <value>The unit number of the Bus as defined by the School Bus owner - freeform text.</value>
[MetaDataExtension (Description = "The unit number of the Bus as defined by the School Bus owner - freeform text.")]
public string SchoolBusUnitNumber { get; set; }
/// <summary>
/// The maximum number of passengers in the bus based on the specific use of the bus. For example, the same 2-per seat / 24-passenger model might have a seating capacity of 36 if the specific bus is to be used for small children, 3 per seat.
/// </summary>
/// <value>The maximum number of passengers in the bus based on the specific use of the bus. For example, the same 2-per seat / 24-passenger model might have a seating capacity of 36 if the specific bus is to be used for small children, 3 per seat.</value>
[MetaDataExtension (Description = "The maximum number of passengers in the bus based on the specific use of the bus. For example, the same 2-per seat / 24-passenger model might have a seating capacity of 36 if the specific bus is to be used for small children, 3 per seat.")]
public int? SchoolBusSeatingCapacity { get; set; }
/// <summary>
/// The number of mobility aid passenger seats in the bus.
/// </summary>
/// <value>The number of mobility aid passenger seats in the bus.</value>
[MetaDataExtension (Description = "The number of mobility aid passenger seats in the bus.")]
public int? MobilityAidCapacity { 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 SchoolBus {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Regi: ").Append(Regi).Append("\n");
sb.Append(" Plate: ").Append(Plate).Append("\n");
sb.Append(" VIN: ").Append(VIN).Append("\n");
sb.Append(" SchoolBusOwner: ").Append(SchoolBusOwner).Append("\n");
sb.Append(" PermitNumber: ").Append(PermitNumber).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" IsOutOfProvince: ").Append(IsOutOfProvince).Append("\n");
sb.Append(" ServiceArea: ").Append(ServiceArea).Append("\n");
sb.Append(" HomeTerminalAddr1: ").Append(HomeTerminalAddr1).Append("\n");
sb.Append(" HomeTerminalAddr2: ").Append(HomeTerminalAddr2).Append("\n");
sb.Append(" HomeTerminalCity: ").Append(HomeTerminalCity).Append("\n");
sb.Append(" HomeTerminalProvince: ").Append(HomeTerminalProvince).Append("\n");
sb.Append(" HomeTerminalPostalCode: ").Append(HomeTerminalPostalCode).Append("\n");
sb.Append(" HomeTerminalComment: ").Append(HomeTerminalComment).Append("\n");
sb.Append(" Restrictions: ").Append(Restrictions).Append("\n");
sb.Append(" NextInspectionDate: ").Append(NextInspectionDate).Append("\n");
sb.Append(" NextInspectionType: ").Append(NextInspectionType).Append("\n");
sb.Append(" SchoolBusDistrict: ").Append(SchoolBusDistrict).Append("\n");
sb.Append(" IsIndependentSchool: ").Append(IsIndependentSchool).Append("\n");
sb.Append(" NameOfIndependentSchool: ").Append(NameOfIndependentSchool).Append("\n");
sb.Append(" SchoolBusClass: ").Append(SchoolBusClass).Append("\n");
sb.Append(" SchoolBusBodyType: ").Append(SchoolBusBodyType).Append("\n");
sb.Append(" SchoolBusBodyTypeOther: ").Append(SchoolBusBodyTypeOther).Append("\n");
sb.Append(" SchoolBusUnitNumber: ").Append(SchoolBusUnitNumber).Append("\n");
sb.Append(" SchoolBusSeatingCapacity: ").Append(SchoolBusSeatingCapacity).Append("\n");
sb.Append(" MobilityAidCapacity: ").Append(MobilityAidCapacity).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 string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((SchoolBus)obj);
}
/// <summary>
/// Returns true if SchoolBus instances are equal
/// </summary>
/// <param name="other">Instance of SchoolBus to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SchoolBus other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Regi == other.Regi ||
this.Regi != null &&
this.Regi.Equals(other.Regi)
) &&
(
this.Plate == other.Plate ||
this.Plate != null &&
this.Plate.Equals(other.Plate)
) &&
(
this.VIN == other.VIN ||
this.VIN != null &&
this.VIN.Equals(other.VIN)
) &&
(
this.SchoolBusOwner == other.SchoolBusOwner ||
this.SchoolBusOwner != null &&
this.SchoolBusOwner.Equals(other.SchoolBusOwner)
) &&
(
this.PermitNumber == other.PermitNumber ||
this.PermitNumber != null &&
this.PermitNumber.Equals(other.PermitNumber)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.IsOutOfProvince == other.IsOutOfProvince ||
this.IsOutOfProvince != null &&
this.IsOutOfProvince.Equals(other.IsOutOfProvince)
) &&
(
this.ServiceArea == other.ServiceArea ||
this.ServiceArea != null &&
this.ServiceArea.Equals(other.ServiceArea)
) &&
(
this.HomeTerminalAddr1 == other.HomeTerminalAddr1 ||
this.HomeTerminalAddr1 != null &&
this.HomeTerminalAddr1.Equals(other.HomeTerminalAddr1)
) &&
(
this.HomeTerminalAddr2 == other.HomeTerminalAddr2 ||
this.HomeTerminalAddr2 != null &&
this.HomeTerminalAddr2.Equals(other.HomeTerminalAddr2)
) &&
(
this.HomeTerminalCity == other.HomeTerminalCity ||
this.HomeTerminalCity != null &&
this.HomeTerminalCity.Equals(other.HomeTerminalCity)
) &&
(
this.HomeTerminalProvince == other.HomeTerminalProvince ||
this.HomeTerminalProvince != null &&
this.HomeTerminalProvince.Equals(other.HomeTerminalProvince)
) &&
(
this.HomeTerminalPostalCode == other.HomeTerminalPostalCode ||
this.HomeTerminalPostalCode != null &&
this.HomeTerminalPostalCode.Equals(other.HomeTerminalPostalCode)
) &&
(
this.HomeTerminalComment == other.HomeTerminalComment ||
this.HomeTerminalComment != null &&
this.HomeTerminalComment.Equals(other.HomeTerminalComment)
) &&
(
this.Restrictions == other.Restrictions ||
this.Restrictions != null &&
this.Restrictions.Equals(other.Restrictions)
) &&
(
this.NextInspectionDate == other.NextInspectionDate ||
this.NextInspectionDate != null &&
this.NextInspectionDate.Equals(other.NextInspectionDate)
) &&
(
this.NextInspectionType == other.NextInspectionType ||
this.NextInspectionType != null &&
this.NextInspectionType.Equals(other.NextInspectionType)
) &&
(
this.SchoolBusDistrict == other.SchoolBusDistrict ||
this.SchoolBusDistrict != null &&
this.SchoolBusDistrict.Equals(other.SchoolBusDistrict)
) &&
(
this.IsIndependentSchool == other.IsIndependentSchool ||
this.IsIndependentSchool != null &&
this.IsIndependentSchool.Equals(other.IsIndependentSchool)
) &&
(
this.NameOfIndependentSchool == other.NameOfIndependentSchool ||
this.NameOfIndependentSchool != null &&
this.NameOfIndependentSchool.Equals(other.NameOfIndependentSchool)
) &&
(
this.SchoolBusClass == other.SchoolBusClass ||
this.SchoolBusClass != null &&
this.SchoolBusClass.Equals(other.SchoolBusClass)
) &&
(
this.SchoolBusBodyType == other.SchoolBusBodyType ||
this.SchoolBusBodyType != null &&
this.SchoolBusBodyType.Equals(other.SchoolBusBodyType)
) &&
(
this.SchoolBusBodyTypeOther == other.SchoolBusBodyTypeOther ||
this.SchoolBusBodyTypeOther != null &&
this.SchoolBusBodyTypeOther.Equals(other.SchoolBusBodyTypeOther)
) &&
(
this.SchoolBusUnitNumber == other.SchoolBusUnitNumber ||
this.SchoolBusUnitNumber != null &&
this.SchoolBusUnitNumber.Equals(other.SchoolBusUnitNumber)
) &&
(
this.SchoolBusSeatingCapacity == other.SchoolBusSeatingCapacity ||
this.SchoolBusSeatingCapacity != null &&
this.SchoolBusSeatingCapacity.Equals(other.SchoolBusSeatingCapacity)
) &&
(
this.MobilityAidCapacity == other.MobilityAidCapacity ||
this.MobilityAidCapacity != null &&
this.MobilityAidCapacity.Equals(other.MobilityAidCapacity)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
if (this.Regi != null)
{
hash = hash * 59 + this.Regi.GetHashCode();
}
if (this.Plate != null)
{
hash = hash * 59 + this.Plate.GetHashCode();
}
if (this.VIN != null)
{
hash = hash * 59 + this.VIN.GetHashCode();
}
if (this.SchoolBusOwner != null)
{
hash = hash * 59 + this.SchoolBusOwner.GetHashCode();
}
if (this.PermitNumber != null)
{
hash = hash * 59 + this.PermitNumber.GetHashCode();
}
if (this.Status != null)
{
hash = hash * 59 + this.Status.GetHashCode();
}
if (this.IsOutOfProvince != null)
{
hash = hash * 59 + this.IsOutOfProvince.GetHashCode();
}
if (this.ServiceArea != null)
{
hash = hash * 59 + this.ServiceArea.GetHashCode();
}
if (this.HomeTerminalAddr1 != null)
{
hash = hash * 59 + this.HomeTerminalAddr1.GetHashCode();
}
if (this.HomeTerminalAddr2 != null)
{
hash = hash * 59 + this.HomeTerminalAddr2.GetHashCode();
}
if (this.HomeTerminalCity != null)
{
hash = hash * 59 + this.HomeTerminalCity.GetHashCode();
}
if (this.HomeTerminalProvince != null)
{
hash = hash * 59 + this.HomeTerminalProvince.GetHashCode();
}
if (this.HomeTerminalPostalCode != null)
{
hash = hash * 59 + this.HomeTerminalPostalCode.GetHashCode();
}
if (this.HomeTerminalComment != null)
{
hash = hash * 59 + this.HomeTerminalComment.GetHashCode();
}
if (this.Restrictions != null)
{
hash = hash * 59 + this.Restrictions.GetHashCode();
}
if (this.NextInspectionDate != null)
{
hash = hash * 59 + this.NextInspectionDate.GetHashCode();
}
if (this.NextInspectionType != null)
{
hash = hash * 59 + this.NextInspectionType.GetHashCode();
}
if (this.SchoolBusDistrict != null)
{
hash = hash * 59 + this.SchoolBusDistrict.GetHashCode();
}
if (this.IsIndependentSchool != null)
{
hash = hash * 59 + this.IsIndependentSchool.GetHashCode();
}
if (this.NameOfIndependentSchool != null)
{
hash = hash * 59 + this.NameOfIndependentSchool.GetHashCode();
}
if (this.SchoolBusClass != null)
{
hash = hash * 59 + this.SchoolBusClass.GetHashCode();
}
if (this.SchoolBusBodyType != null)
{
hash = hash * 59 + this.SchoolBusBodyType.GetHashCode();
}
if (this.SchoolBusBodyTypeOther != null)
{
hash = hash * 59 + this.SchoolBusBodyTypeOther.GetHashCode();
}
if (this.SchoolBusUnitNumber != null)
{
hash = hash * 59 + this.SchoolBusUnitNumber.GetHashCode();
}
if (this.SchoolBusSeatingCapacity != null)
{
hash = hash * 59 + this.SchoolBusSeatingCapacity.GetHashCode();
}
if (this.MobilityAidCapacity != null)
{
hash = hash * 59 + this.MobilityAidCapacity.GetHashCode();
}
return hash;
}
}
#region Operators
public static bool operator ==(SchoolBus left, SchoolBus right)
{
return Equals(left, right);
}
public static bool operator !=(SchoolBus left, SchoolBus right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.RAMCacheInformationBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBRAMCacheInformationRAMCacheKey))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBRAMCacheInformationRAMCacheEntry))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBRAMCacheInformationRAMCacheEntryExactMatch))]
public partial class LocalLBRAMCacheInformation : iControlInterface {
public LocalLBRAMCacheInformation() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// evict_all_ramcache_entries
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/RAMCacheInformation",
RequestNamespace="urn:iControl:LocalLB/RAMCacheInformation", ResponseNamespace="urn:iControl:LocalLB/RAMCacheInformation")]
public void evict_all_ramcache_entries(
) {
this.Invoke("evict_all_ramcache_entries", new object [0]);
}
public System.IAsyncResult Beginevict_all_ramcache_entries(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("evict_all_ramcache_entries", new object[0], callback, asyncState);
}
public void Endevict_all_ramcache_entries(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// evict_ramcache_entry
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/RAMCacheInformation",
RequestNamespace="urn:iControl:LocalLB/RAMCacheInformation", ResponseNamespace="urn:iControl:LocalLB/RAMCacheInformation")]
public void evict_ramcache_entry(
LocalLBRAMCacheInformationRAMCacheKey [] keys
) {
this.Invoke("evict_ramcache_entry", new object [] {
keys});
}
public System.IAsyncResult Beginevict_ramcache_entry(LocalLBRAMCacheInformationRAMCacheKey [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("evict_ramcache_entry", new object[] {
keys}, callback, asyncState);
}
public void Endevict_ramcache_entry(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// evict_ramcache_entry_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/RAMCacheInformation",
RequestNamespace="urn:iControl:LocalLB/RAMCacheInformation", ResponseNamespace="urn:iControl:LocalLB/RAMCacheInformation")]
public void evict_ramcache_entry_v2(
LocalLBRAMCacheInformationRAMCacheKey [] keys,
bool exact_match
) {
this.Invoke("evict_ramcache_entry_v2", new object [] {
keys,
exact_match});
}
public System.IAsyncResult Beginevict_ramcache_entry_v2(LocalLBRAMCacheInformationRAMCacheKey [] keys,bool exact_match, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("evict_ramcache_entry_v2", new object[] {
keys,
exact_match}, callback, asyncState);
}
public void Endevict_ramcache_entry_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_ramcache_entry
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/RAMCacheInformation",
RequestNamespace="urn:iControl:LocalLB/RAMCacheInformation", ResponseNamespace="urn:iControl:LocalLB/RAMCacheInformation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBRAMCacheInformationRAMCacheEntry [] [] get_ramcache_entry(
LocalLBRAMCacheInformationRAMCacheKey [] keys
) {
object [] results = this.Invoke("get_ramcache_entry", new object [] {
keys});
return ((LocalLBRAMCacheInformationRAMCacheEntry [] [])(results[0]));
}
public System.IAsyncResult Beginget_ramcache_entry(LocalLBRAMCacheInformationRAMCacheKey [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ramcache_entry", new object[] {
keys}, callback, asyncState);
}
public LocalLBRAMCacheInformationRAMCacheEntry [] [] Endget_ramcache_entry(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBRAMCacheInformationRAMCacheEntry [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ramcache_entry_exact_match
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/RAMCacheInformation",
RequestNamespace="urn:iControl:LocalLB/RAMCacheInformation", ResponseNamespace="urn:iControl:LocalLB/RAMCacheInformation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBRAMCacheInformationRAMCacheEntryExactMatch [] [] get_ramcache_entry_exact_match(
LocalLBRAMCacheInformationRAMCacheKey [] keys
) {
object [] results = this.Invoke("get_ramcache_entry_exact_match", new object [] {
keys});
return ((LocalLBRAMCacheInformationRAMCacheEntryExactMatch [] [])(results[0]));
}
public System.IAsyncResult Beginget_ramcache_entry_exact_match(LocalLBRAMCacheInformationRAMCacheKey [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ramcache_entry_exact_match", new object[] {
keys}, callback, asyncState);
}
public LocalLBRAMCacheInformationRAMCacheEntryExactMatch [] [] Endget_ramcache_entry_exact_match(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBRAMCacheInformationRAMCacheEntryExactMatch [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/RAMCacheInformation",
RequestNamespace="urn:iControl:LocalLB/RAMCacheInformation", ResponseNamespace="urn:iControl:LocalLB/RAMCacheInformation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.RAMCacheInformation.RAMCacheVaryType", Namespace = "urn:iControl")]
public enum LocalLBRAMCacheInformationRAMCacheVaryType
{
RAM_CACHE_VARY_NONE,
RAM_CACHE_VARY_USERAGENT,
RAM_CACHE_VARY_ACCEPT_ENCODING,
RAM_CACHE_VARY_BOTH,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.RAMCacheInformation.RAMCacheEntry", Namespace = "urn:iControl")]
public partial class LocalLBRAMCacheInformationRAMCacheEntry
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private string host_nameField;
public string host_name
{
get { return this.host_nameField; }
set { this.host_nameField = value; }
}
private string uriField;
public string uri
{
get { return this.uriField; }
set { this.uriField = value; }
}
private LocalLBRAMCacheInformationRAMCacheVaryType vary_typeField;
public LocalLBRAMCacheInformationRAMCacheVaryType vary_type
{
get { return this.vary_typeField; }
set { this.vary_typeField = value; }
}
private long vary_countField;
public long vary_count
{
get { return this.vary_countField; }
set { this.vary_countField = value; }
}
private long hitsField;
public long hits
{
get { return this.hitsField; }
set { this.hitsField = value; }
}
private long receivedField;
public long received
{
get { return this.receivedField; }
set { this.receivedField = value; }
}
private long last_sentField;
public long last_sent
{
get { return this.last_sentField; }
set { this.last_sentField = value; }
}
private long expirationField;
public long expiration
{
get { return this.expirationField; }
set { this.expirationField = value; }
}
private long sizeField;
public long size
{
get { return this.sizeField; }
set { this.sizeField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.RAMCacheInformation.RAMCacheEntryExactMatch", Namespace = "urn:iControl")]
public partial class LocalLBRAMCacheInformationRAMCacheEntryExactMatch
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private string host_nameField;
public string host_name
{
get { return this.host_nameField; }
set { this.host_nameField = value; }
}
private string uriField;
public string uri
{
get { return this.uriField; }
set { this.uriField = value; }
}
private string vary_useragentField;
public string vary_useragent
{
get { return this.vary_useragentField; }
set { this.vary_useragentField = value; }
}
private string vary_encodingField;
public string vary_encoding
{
get { return this.vary_encodingField; }
set { this.vary_encodingField = value; }
}
private long hitsField;
public long hits
{
get { return this.hitsField; }
set { this.hitsField = value; }
}
private long receivedField;
public long received
{
get { return this.receivedField; }
set { this.receivedField = value; }
}
private long last_sentField;
public long last_sent
{
get { return this.last_sentField; }
set { this.last_sentField = value; }
}
private long expirationField;
public long expiration
{
get { return this.expirationField; }
set { this.expirationField = value; }
}
private long sizeField;
public long size
{
get { return this.sizeField; }
set { this.sizeField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.RAMCacheInformation.RAMCacheKey", Namespace = "urn:iControl")]
public partial class LocalLBRAMCacheInformationRAMCacheKey
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private string host_nameField;
public string host_name
{
get { return this.host_nameField; }
set { this.host_nameField = value; }
}
private string uriField;
public string uri
{
get { return this.uriField; }
set { this.uriField = value; }
}
private long maximum_responsesField;
public long maximum_responses
{
get { return this.maximum_responsesField; }
set { this.maximum_responsesField = value; }
}
};
}
| |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Cryptography.ECC;
using Neo.IO;
using System;
using System.IO;
using System.Linq;
using System.Numerics;
using ECCurve = Neo.Cryptography.ECC.ECCurve;
using ECPoint = Neo.Cryptography.ECC.ECPoint;
namespace Neo.UnitTests.Cryptography.ECC
{
[TestClass]
public class UT_ECPoint
{
public static byte[] GeneratePrivateKey(int privateKeyLength)
{
byte[] privateKey = new byte[privateKeyLength];
for (int i = 0; i < privateKeyLength; i++)
{
privateKey[i] = (byte)((byte)i % byte.MaxValue);
}
return privateKey;
}
[TestMethod]
public void TestCompareTo()
{
ECFieldElement X1 = new ECFieldElement(new BigInteger(100), ECCurve.Secp256k1);
ECFieldElement X2 = new ECFieldElement(new BigInteger(200), ECCurve.Secp256k1);
ECFieldElement X3 = new ECFieldElement(new BigInteger(100), ECCurve.Secp256r1);
X1.CompareTo(X2).Should().Be(-1);
Action action = () => X1.CompareTo(X3);
action.Should().Throw<InvalidOperationException>();
}
[TestMethod]
public void TestECPointConstructor()
{
ECPoint point = new ECPoint();
point.X.Should().BeNull();
point.Y.Should().BeNull();
point.Curve.Should().Be(ECCurve.Secp256r1);
ECFieldElement X = new ECFieldElement(new BigInteger(100), ECCurve.Secp256k1);
ECFieldElement Y = new ECFieldElement(new BigInteger(200), ECCurve.Secp256k1);
point = new ECPoint(X, Y, ECCurve.Secp256k1);
point.X.Should().Be(X);
point.Y.Should().Be(Y);
point.Curve.Should().Be(ECCurve.Secp256k1);
Action action = () => new ECPoint(X, null, ECCurve.Secp256k1);
action.Should().Throw<ArgumentException>();
action = () => new ECPoint(null, Y, ECCurve.Secp256k1);
action.Should().Throw<ArgumentException>();
action = () => new ECPoint(null, Y, null);
action.Should().Throw<ArgumentException>();
}
[TestMethod]
public void TestDecodePoint()
{
byte[] input1 = { 0 };
Action action = () => ECPoint.DecodePoint(input1, ECCurve.Secp256k1);
action.Should().Throw<FormatException>();
byte[] input2 = { 4, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 72,
58, 218, 119, 38, 163, 196, 101, 93, 164, 251, 252, 14, 17, 8, 168, 253, 23, 180, 72, 166, 133, 84, 25, 156, 71, 208, 143, 251, 16, 212, 184 };
ECPoint.DecodePoint(input2, ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
action = () => ECPoint.DecodePoint(input2.Take(32).ToArray(), ECCurve.Secp256k1);
action.Should().Throw<FormatException>();
byte[] input3 = { 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152 };
byte[] input4 = { 3, 107, 23, 209, 242, 225, 44, 66, 71, 248, 188, 230, 229, 99, 164, 64, 242, 119, 3, 125, 129, 45, 235, 51, 160, 244, 161, 57, 69, 216, 152, 194, 150 };
ECPoint.DecodePoint(input3, ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
ECPoint.DecodePoint(input4, ECCurve.Secp256r1).Should().Be(ECCurve.Secp256r1.G);
action = () => ECPoint.DecodePoint(input3.Take(input3.Length - 1).ToArray(), ECCurve.Secp256k1);
action.Should().Throw<FormatException>();
}
[TestMethod]
public void TestDeserializeFrom()
{
byte[] input1 = { 0 };
Action action = () => ECPoint.DeserializeFrom(new BinaryReader(new MemoryStream(input1)), ECCurve.Secp256k1);
action.Should().Throw<FormatException>();
byte[] input2 = { 4, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 72,
58, 218, 119, 38, 163, 196, 101, 93, 164, 251, 252, 14, 17, 8, 168, 253, 23, 180, 72, 166, 133, 84, 25, 156, 71, 208, 143, 251, 16, 212, 184 };
ECPoint.DeserializeFrom(new BinaryReader(new MemoryStream(input2)), ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
action = () => ECPoint.DeserializeFrom(new BinaryReader(new MemoryStream(input2.Take(32).ToArray())), ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
action.Should().Throw<FormatException>();
byte[] input3 = { 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152 };
ECPoint.DeserializeFrom(new BinaryReader(new MemoryStream(input3)), ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
byte[] input4 = { 3, 107, 23, 209, 242, 225, 44, 66, 71, 248, 188, 230, 229, 99, 164, 64, 242, 119, 3, 125, 129, 45, 235, 51, 160, 244, 161, 57, 69, 216, 152, 194, 150 };
ECPoint.DeserializeFrom(new BinaryReader(new MemoryStream(input4)), ECCurve.Secp256r1).Should().Be(ECCurve.Secp256r1.G);
action = () => ECPoint.DeserializeFrom(new BinaryReader(new MemoryStream(input3.Take(input3.Length - 1).ToArray())), ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
action.Should().Throw<FormatException>();
}
[TestMethod]
public void TestEncodePoint()
{
ECPoint point = new ECPoint(null, null, ECCurve.Secp256k1);
byte[] result1 = { 0 };
point.EncodePoint(true).Should().BeEquivalentTo(result1);
point = ECCurve.Secp256k1.G;
byte[] result2 = { 4, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 72,
58, 218, 119, 38, 163, 196, 101, 93, 164, 251, 252, 14, 17, 8, 168, 253, 23, 180, 72, 166, 133, 84, 25, 156, 71, 208, 143, 251, 16, 212, 184 };
point.EncodePoint(false).Should().BeEquivalentTo(result2);
point.EncodePoint(false).Should().BeEquivalentTo(result2);
byte[] result3 = { 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152 };
point.EncodePoint(true).Should().BeEquivalentTo(result3);
point.EncodePoint(true).Should().BeEquivalentTo(result3);
point = ECCurve.Secp256r1.G;
byte[] result4 = { 3, 107, 23, 209, 242, 225, 44, 66, 71, 248, 188, 230, 229, 99, 164, 64, 242, 119, 3, 125, 129, 45, 235, 51, 160, 244, 161, 57, 69, 216, 152, 194, 150 };
point.EncodePoint(true).Should().BeEquivalentTo(result4);
point.EncodePoint(true).Should().BeEquivalentTo(result4);
// Test cache
point = ECPoint.DecodePoint(ECCurve.Secp256r1.G.EncodePoint(true), ECCurve.Secp256r1);
point.EncodePoint(true).Should().BeEquivalentTo(result4);
point.EncodePoint(true).Should().BeEquivalentTo(result4);
byte[] result5 = "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5".HexToBytes();
point = ECPoint.DecodePoint(ECCurve.Secp256r1.G.EncodePoint(false), ECCurve.Secp256r1);
point.EncodePoint(true).Should().BeEquivalentTo(result4);
point.EncodePoint(true).Should().BeEquivalentTo(result4);
point.EncodePoint(false).Should().BeEquivalentTo(result5);
point.EncodePoint(false).Should().BeEquivalentTo(result5);
}
[TestMethod]
public void TestEquals()
{
ECPoint point = ECCurve.Secp256k1.G;
point.Equals(point).Should().BeTrue();
point.Equals(null).Should().BeFalse();
point = new ECPoint(null, null, ECCurve.Secp256k1);
point.Equals(new ECPoint(null, null, ECCurve.Secp256r1)).Should().BeTrue();
point.Equals(ECCurve.Secp256r1.G).Should().BeFalse();
ECCurve.Secp256r1.G.Equals(point).Should().BeFalse();
ECFieldElement X1 = new ECFieldElement(new BigInteger(100), ECCurve.Secp256k1);
ECFieldElement Y1 = new ECFieldElement(new BigInteger(200), ECCurve.Secp256k1);
ECFieldElement X2 = new ECFieldElement(new BigInteger(300), ECCurve.Secp256k1);
ECFieldElement Y2 = new ECFieldElement(new BigInteger(400), ECCurve.Secp256k1);
ECPoint point1 = new ECPoint(X1, Y1, ECCurve.Secp256k1);
ECPoint point2 = new ECPoint(X2, Y1, ECCurve.Secp256k1);
ECPoint point3 = new ECPoint(X1, Y2, ECCurve.Secp256k1);
point1.Equals(point2).Should().BeFalse();
point1.Equals(point3).Should().BeFalse();
}
[TestMethod]
public void TestEqualsObject()
{
object point = ECCurve.Secp256k1.G;
point.Equals(point).Should().BeTrue();
point.Equals(null).Should().BeFalse();
point.Equals(1u).Should().BeFalse();
point = new ECPoint(null, null, ECCurve.Secp256k1);
point.Equals(new ECPoint(null, null, ECCurve.Secp256r1)).Should().BeTrue();
point.Equals(ECCurve.Secp256r1.G).Should().BeFalse();
ECCurve.Secp256r1.G.Equals(point).Should().BeFalse();
ECFieldElement X1 = new ECFieldElement(new BigInteger(100), ECCurve.Secp256k1);
ECFieldElement Y1 = new ECFieldElement(new BigInteger(200), ECCurve.Secp256k1);
ECFieldElement X2 = new ECFieldElement(new BigInteger(300), ECCurve.Secp256k1);
ECFieldElement Y2 = new ECFieldElement(new BigInteger(400), ECCurve.Secp256k1);
object point1 = new ECPoint(X1, Y1, ECCurve.Secp256k1);
object point2 = new ECPoint(X2, Y1, ECCurve.Secp256k1);
object point3 = new ECPoint(X1, Y2, ECCurve.Secp256k1);
point1.Equals(point2).Should().BeFalse();
point1.Equals(point3).Should().BeFalse();
}
[TestMethod]
public void TestFromBytes()
{
byte[] input1 = { 0 };
Action action = () => ECPoint.FromBytes(input1, ECCurve.Secp256k1);
action.Should().Throw<FormatException>();
byte[] input2 = { 4, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 72,
58, 218, 119, 38, 163, 196, 101, 93, 164, 251, 252, 14, 17, 8, 168, 253, 23, 180, 72, 166, 133, 84, 25, 156, 71, 208, 143, 251, 16, 212, 184 };
ECPoint.FromBytes(input2, ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
byte[] input3 = { 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152 };
ECPoint.FromBytes(input3, ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
ECPoint.FromBytes(input2.Skip(1).ToArray(), ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G);
byte[] input4 = GeneratePrivateKey(72);
ECPoint.FromBytes(input4, ECCurve.Secp256k1).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("3634473727541135791764834762056624681715094789735830699031648" +
"273128038409767"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("18165245710263168158644330920009617039772504630129940696140050972160274286151"),
ECCurve.Secp256k1), ECCurve.Secp256k1));
byte[] input5 = GeneratePrivateKey(96);
ECPoint.FromBytes(input5, ECCurve.Secp256k1).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("1780731860627700044960722568376592200742329637303199754547598" +
"369979440671"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("14532552714582660066924456880521368950258152170031413196862950297402215317055"),
ECCurve.Secp256k1), ECCurve.Secp256k1));
byte[] input6 = GeneratePrivateKey(104);
ECPoint.FromBytes(input6, ECCurve.Secp256k1).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("3634473727541135791764834762056624681715094789735830699031648" +
"273128038409767"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("18165245710263168158644330920009617039772504630129940696140050972160274286151"),
ECCurve.Secp256k1), ECCurve.Secp256k1));
}
[TestMethod]
public void TestGetSize()
{
ECCurve.Secp256k1.G.Size.Should().Be(33);
ECCurve.Secp256k1.Infinity.Size.Should().Be(1);
}
[TestMethod]
public void TestMultiply()
{
ECPoint p = ECCurve.Secp256k1.G;
BigInteger k = BigInteger.Parse("100");
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("107303582290733097924842193972465022053148211775194373671539518313500194639752"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("103795966108782717446806684023742168462365449272639790795591544606836007446638"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
k = BigInteger.Parse("10000");
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("55279067612272658004429375184716238028207484982037227804583126224321918234542"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("93139664895507357192565643142424306097487832058389223752321585898830257071353"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
k = BigInteger.Parse("10000000000000");
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("115045167963494515061513744671884131783397561769819471159495798754884242293003"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("93759167105263077270762304290738437383691912799231615884447658154878797241853"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
k = BigInteger.Parse("1000000000000000000000000000000000000000");
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("114831276968810911840931876895388845736099852671055832194631099067239418074350"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("16721517996619732311261078486295444964227498319433363271180755596201863690708"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
k = new BigInteger(GeneratePrivateKey(100));
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("19222995016448259376216431079553428738726180595337971417371897285865264889977"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("6637081904924493791520919212064582313497884724460823966446023080706723904419"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
k = new BigInteger(GeneratePrivateKey(120));
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("79652345192111851576650978679091010173409410384772942769927955775006682639778"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("6460429961979335115790346961011058418773289452368186110818621539624566803831"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
k = new BigInteger(GeneratePrivateKey(300));
ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("105331914562708556186724786757483927866790351460145374033180496740107603569412"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("60523670886755698512704385951571322569877668383890769288780681319304421873758"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
}
[TestMethod]
public void TestDeserialize()
{
ECPoint point = new ECPoint(null, null, ECCurve.Secp256k1);
ISerializable serializable = point;
byte[] input = { 4, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152,
72, 58, 218, 119, 38, 163, 196, 101, 93, 164, 251, 252, 14, 17, 8, 168, 253, 23, 180, 72, 166, 133, 84, 25, 156, 71, 208, 143, 251, 16, 212, 184 };
serializable.Deserialize(new BinaryReader(new MemoryStream(input)));
point.X.Should().Be(ECCurve.Secp256k1.G.X);
point.Y.Should().Be(ECCurve.Secp256k1.G.Y);
}
[TestMethod]
public void TestSerialize()
{
MemoryStream stream = new MemoryStream();
ECPoint point = new ECPoint(null, null, ECCurve.Secp256k1);
ISerializable serializable = point;
serializable.Serialize(new BinaryWriter(stream));
stream.ToArray().Should().BeEquivalentTo(new byte[] { 0 });
}
[TestMethod]
public void TestOpAddition()
{
(ECCurve.Secp256k1.Infinity + ECCurve.Secp256k1.G).Should().Be(ECCurve.Secp256k1.G);
(ECCurve.Secp256k1.G + ECCurve.Secp256k1.Infinity).Should().Be(ECCurve.Secp256k1.G);
(ECCurve.Secp256k1.G + ECCurve.Secp256k1.G).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("8956589192654700423125292042593569236064414582962220983368432" +
"9913297188986597"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("12158399299693830322967808612713398636155367887041628176798871954788371653930"),
ECCurve.Secp256k1), ECCurve.Secp256k1));
(ECCurve.Secp256k1.G + new ECPoint(ECCurve.Secp256k1.G.X, new ECFieldElement(BigInteger.One, ECCurve.Secp256k1), ECCurve.Secp256k1)).Should().Be(ECCurve.Secp256k1.Infinity);
(ECCurve.Secp256k1.G + ECCurve.Secp256k1.G + ECCurve.Secp256k1.G).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("112711660439710606056748659173929673102" +
"114977341539408544630613555209775888121"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("2558302798057088369165690587740197640644886825481629506991988" +
"8960541586679410"), ECCurve.Secp256k1), ECCurve.Secp256k1));
}
[TestMethod]
public void TestOpMultiply()
{
ECPoint p = null;
byte[] n = new byte[] { 1 };
Action action = () => p = p * n;
action.Should().Throw<ArgumentNullException>();
p = ECCurve.Secp256k1.G;
n = null;
action.Should().Throw<ArgumentNullException>();
n = new byte[] { 1 };
action.Should().Throw<ArgumentException>();
p = ECCurve.Secp256k1.Infinity;
n = new byte[32];
(p * n).Should().Be(p);
p = ECCurve.Secp256k1.G;
(p * n).Should().Be(ECCurve.Secp256k1.Infinity);
n[0] = 1;
(p * n).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("63395642421589016740518975608504846303065672135176650115036476193363423546538"), ECCurve.Secp256k1),
new ECFieldElement(BigInteger.Parse("29236048674093813394523910922582374630829081423043497254162533033164154049666"), ECCurve.Secp256k1), ECCurve.Secp256k1));
}
[TestMethod]
public void TestOpSubtraction()
{
(ECCurve.Secp256k1.G - ECCurve.Secp256k1.Infinity).Should().Be(ECCurve.Secp256k1.G);
(ECCurve.Secp256k1.G - ECCurve.Secp256k1.G).Should().Be(ECCurve.Secp256k1.Infinity);
}
[TestMethod]
public void TestOpUnaryNegation()
{
(-ECCurve.Secp256k1.G).Should().Be(new ECPoint(ECCurve.Secp256k1.G.X, -ECCurve.Secp256k1.G.Y, ECCurve.Secp256k1));
}
[TestMethod]
public void TestTryParse()
{
ECPoint.TryParse("00", ECCurve.Secp256k1, out ECPoint result).Should().BeFalse();
result.Should().BeNull();
ECPoint.TryParse("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", ECCurve.Secp256k1,
out result).Should().BeTrue();
result.Should().Be(ECCurve.Secp256k1.G);
}
[TestMethod]
public void TestTwice()
{
ECCurve.Secp256k1.Infinity.Twice().Should().Be(ECCurve.Secp256k1.Infinity);
new ECPoint(new ECFieldElement(BigInteger.Zero, ECCurve.Secp256k1), new ECFieldElement(BigInteger.Zero, ECCurve.Secp256k1),
ECCurve.Secp256k1).Twice().Should().Be(ECCurve.Secp256k1.Infinity);
ECCurve.Secp256k1.G.Twice().Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("89565891926547004231252920425935692360644145829622209833684329913297188986597"),
ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("12158399299693830322967808612713398636155367887041628176798871954788371653930"), ECCurve.Secp256k1),
ECCurve.Secp256k1));
}
}
}
| |
// 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.Globalization;
using System.Runtime.Serialization;
using System.Text;
namespace System
{
public sealed partial class TimeZoneInfo
{
/// <summary>
/// Used to serialize and deserialize TimeZoneInfo objects based on the custom string serialization format.
/// </summary>
private struct StringSerializer
{
private enum State
{
Escaped = 0,
NotEscaped = 1,
StartOfToken = 2,
EndOfLine = 3
}
private readonly string _serializedText;
private int _currentTokenStartIndex;
private State _state;
// the majority of the strings contained in the OS time zones fit in 64 chars
private const int InitialCapacityForString = 64;
private const char Esc = '\\';
private const char Sep = ';';
private const char Lhs = '[';
private const char Rhs = ']';
private const string DateTimeFormat = "MM:dd:yyyy";
private const string TimeOfDayFormat = "HH:mm:ss.FFF";
/// <summary>
/// Creates the custom serialized string representation of a TimeZoneInfo instance.
/// </summary>
public static string GetSerializedString(TimeZoneInfo zone)
{
StringBuilder serializedText = StringBuilderCache.Acquire();
//
// <_id>;<_baseUtcOffset>;<_displayName>;<_standardDisplayName>;<_daylightDispayName>
//
SerializeSubstitute(zone.Id, serializedText);
serializedText.Append(Sep);
serializedText.Append(zone.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
SerializeSubstitute(zone.DisplayName, serializedText);
serializedText.Append(Sep);
SerializeSubstitute(zone.StandardName, serializedText);
serializedText.Append(Sep);
SerializeSubstitute(zone.DaylightName, serializedText);
serializedText.Append(Sep);
AdjustmentRule[] rules = zone.GetAdjustmentRules();
foreach (AdjustmentRule rule in rules)
{
serializedText.Append(Lhs);
serializedText.Append(rule.DateStart.ToString(DateTimeFormat, DateTimeFormatInfo.InvariantInfo));
serializedText.Append(Sep);
serializedText.Append(rule.DateEnd.ToString(DateTimeFormat, DateTimeFormatInfo.InvariantInfo));
serializedText.Append(Sep);
serializedText.Append(rule.DaylightDelta.TotalMinutes.ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
// serialize the TransitionTime's
SerializeTransitionTime(rule.DaylightTransitionStart, serializedText);
serializedText.Append(Sep);
SerializeTransitionTime(rule.DaylightTransitionEnd, serializedText);
serializedText.Append(Sep);
if (rule.BaseUtcOffsetDelta != TimeSpan.Zero)
{
// Serialize it only when BaseUtcOffsetDelta has a value to reduce the impact of adding rule.BaseUtcOffsetDelta
serializedText.Append(rule.BaseUtcOffsetDelta.TotalMinutes.ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
}
if (rule.NoDaylightTransitions)
{
// Serialize it only when NoDaylightTransitions is true to reduce the impact of adding rule.NoDaylightTransitions
serializedText.Append('1');
serializedText.Append(Sep);
}
serializedText.Append(Rhs);
}
serializedText.Append(Sep);
return StringBuilderCache.GetStringAndRelease(serializedText);
}
/// <summary>
/// Instantiates a TimeZoneInfo from a custom serialized string.
/// </summary>
public static TimeZoneInfo GetDeserializedTimeZoneInfo(string source)
{
StringSerializer s = new StringSerializer(source);
string id = s.GetNextStringValue();
TimeSpan baseUtcOffset = s.GetNextTimeSpanValue();
string displayName = s.GetNextStringValue();
string standardName = s.GetNextStringValue();
string daylightName = s.GetNextStringValue();
AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue();
try
{
return new TimeZoneInfo(id, baseUtcOffset, displayName, standardName, daylightName, rules, disableDaylightSavingTime: false);
}
catch (ArgumentException ex)
{
throw new SerializationException(SR.Serialization_InvalidData, ex);
}
catch (InvalidTimeZoneException ex)
{
throw new SerializationException(SR.Serialization_InvalidData, ex);
}
}
private StringSerializer(string str)
{
_serializedText = str;
_currentTokenStartIndex = 0;
_state = State.StartOfToken;
}
/// <summary>
/// Appends the String to the StringBuilder with all of the reserved chars escaped.
///
/// ";" -> "\;"
/// "[" -> "\["
/// "]" -> "\]"
/// "\" -> "\\"
/// </summary>
private static void SerializeSubstitute(string text, StringBuilder serializedText)
{
foreach (char c in text)
{
if (c == Esc || c == Lhs || c == Rhs || c == Sep)
{
serializedText.Append('\\');
}
serializedText.Append(c);
}
}
/// <summary>
/// Helper method to serialize a TimeZoneInfo.TransitionTime object.
/// </summary>
private static void SerializeTransitionTime(TransitionTime time, StringBuilder serializedText)
{
serializedText.Append(Lhs);
serializedText.Append(time.IsFixedDateRule ? '1' : '0');
serializedText.Append(Sep);
serializedText.Append(time.TimeOfDay.ToString(TimeOfDayFormat, DateTimeFormatInfo.InvariantInfo));
serializedText.Append(Sep);
serializedText.Append(time.Month.ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
if (time.IsFixedDateRule)
{
serializedText.Append(time.Day.ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
}
else
{
serializedText.Append(time.Week.ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
serializedText.Append(((int)time.DayOfWeek).ToString(CultureInfo.InvariantCulture));
serializedText.Append(Sep);
}
serializedText.Append(Rhs);
}
/// <summary>
/// Helper function to determine if the passed in string token is allowed to be preceded by an escape sequence token.
/// </summary>
private static void VerifyIsEscapableCharacter(char c)
{
if (c != Esc && c != Sep && c != Lhs && c != Rhs)
{
throw new SerializationException(SR.Format(SR.Serialization_InvalidEscapeSequence, c));
}
}
/// <summary>
/// Helper function that reads past "v.Next" data fields. Receives a "depth" parameter indicating the
/// current relative nested bracket depth that _currentTokenStartIndex is at. The function ends
/// successfully when "depth" returns to zero (0).
/// </summary>
private void SkipVersionNextDataFields(int depth /* starting depth in the nested brackets ('[', ']')*/)
{
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
State tokenState = State.NotEscaped;
// walk the serialized text, building up the token as we go...
for (int i = _currentTokenStartIndex; i < _serializedText.Length; i++)
{
if (tokenState == State.Escaped)
{
VerifyIsEscapableCharacter(_serializedText[i]);
tokenState = State.NotEscaped;
}
else if (tokenState == State.NotEscaped)
{
switch (_serializedText[i])
{
case Esc:
tokenState = State.Escaped;
break;
case Lhs:
depth++;
break;
case Rhs:
depth--;
if (depth == 0)
{
_currentTokenStartIndex = i + 1;
if (_currentTokenStartIndex >= _serializedText.Length)
{
_state = State.EndOfLine;
}
else
{
_state = State.StartOfToken;
}
return;
}
break;
case '\0':
// invalid character
throw new SerializationException(SR.Serialization_InvalidData);
default:
break;
}
}
}
throw new SerializationException(SR.Serialization_InvalidData);
}
/// <summary>
/// Helper function that reads a string token from the serialized text. The function
/// updates <see cref="_currentTokenStartIndex"/> to point to the next token on exit.
/// Also <see cref="_state"/> is set to either <see cref="State.StartOfToken"/> or
/// <see cref="State.EndOfLine"/> on exit.
/// </summary>
private string GetNextStringValue()
{
// first verify the internal state of the object
if (_state == State.EndOfLine)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
State tokenState = State.NotEscaped;
StringBuilder token = StringBuilderCache.Acquire(InitialCapacityForString);
// walk the serialized text, building up the token as we go...
for (int i = _currentTokenStartIndex; i < _serializedText.Length; i++)
{
if (tokenState == State.Escaped)
{
VerifyIsEscapableCharacter(_serializedText[i]);
token.Append(_serializedText[i]);
tokenState = State.NotEscaped;
}
else if (tokenState == State.NotEscaped)
{
switch (_serializedText[i])
{
case Esc:
tokenState = State.Escaped;
break;
case Lhs:
// '[' is an unexpected character
throw new SerializationException(SR.Serialization_InvalidData);
case Rhs:
// ']' is an unexpected character
throw new SerializationException(SR.Serialization_InvalidData);
case Sep:
_currentTokenStartIndex = i + 1;
if (_currentTokenStartIndex >= _serializedText.Length)
{
_state = State.EndOfLine;
}
else
{
_state = State.StartOfToken;
}
return StringBuilderCache.GetStringAndRelease(token);
case '\0':
// invalid character
throw new SerializationException(SR.Serialization_InvalidData);
default:
token.Append(_serializedText[i]);
break;
}
}
}
//
// we are at the end of the line
//
if (tokenState == State.Escaped)
{
// we are at the end of the serialized text but we are in an escaped state
throw new SerializationException(SR.Format(SR.Serialization_InvalidEscapeSequence, string.Empty));
}
throw new SerializationException(SR.Serialization_InvalidData);
}
/// <summary>
/// Helper function to read a DateTime token.
/// </summary>
private DateTime GetNextDateTimeValue(string format)
{
string token = GetNextStringValue();
DateTime time;
if (!DateTime.TryParseExact(token, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out time))
{
throw new SerializationException(SR.Serialization_InvalidData);
}
return time;
}
/// <summary>
/// Helper function to read a TimeSpan token.
/// </summary>
private TimeSpan GetNextTimeSpanValue()
{
int token = GetNextInt32Value();
try
{
return new TimeSpan(hours: 0, minutes: token, seconds: 0);
}
catch (ArgumentOutOfRangeException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
/// <summary>
/// Helper function to read an Int32 token.
/// </summary>
private int GetNextInt32Value()
{
string token = GetNextStringValue();
int value;
if (!int.TryParse(token, NumberStyles.AllowLeadingSign /* "[sign]digits" */, CultureInfo.InvariantCulture, out value))
{
throw new SerializationException(SR.Serialization_InvalidData);
}
return value;
}
/// <summary>
/// Helper function to read an AdjustmentRule[] token.
/// </summary>
private AdjustmentRule[] GetNextAdjustmentRuleArrayValue()
{
List<AdjustmentRule> rules = new List<AdjustmentRule>(1);
int count = 0;
// individual AdjustmentRule array elements do not require semicolons
AdjustmentRule rule = GetNextAdjustmentRuleValue();
while (rule != null)
{
rules.Add(rule);
count++;
rule = GetNextAdjustmentRuleValue();
}
// the AdjustmentRule array must end with a separator
if (_state == State.EndOfLine)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
return count != 0 ? rules.ToArray() : null;
}
/// <summary>
/// Helper function to read an AdjustmentRule token.
/// </summary>
private AdjustmentRule GetNextAdjustmentRuleValue()
{
// first verify the internal state of the object
if (_state == State.EndOfLine)
{
return null;
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
// check to see if the very first token we see is the separator
if (_serializedText[_currentTokenStartIndex] == Sep)
{
return null;
}
// verify the current token is a left-hand-side marker ("[")
if (_serializedText[_currentTokenStartIndex] != Lhs)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
_currentTokenStartIndex++;
DateTime dateStart = GetNextDateTimeValue(DateTimeFormat);
DateTime dateEnd = GetNextDateTimeValue(DateTimeFormat);
TimeSpan daylightDelta = GetNextTimeSpanValue();
TransitionTime daylightStart = GetNextTransitionTimeValue();
TransitionTime daylightEnd = GetNextTransitionTimeValue();
TimeSpan baseUtcOffsetDelta = TimeSpan.Zero;
int noDaylightTransitions = 0;
// verify that the string is now at the right-hand-side marker ("]") ...
if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
// Check if we have baseUtcOffsetDelta in the serialized string and then deserialize it
if ((_serializedText[_currentTokenStartIndex] >= '0' && _serializedText[_currentTokenStartIndex] <= '9') ||
_serializedText[_currentTokenStartIndex] == '-' || _serializedText[_currentTokenStartIndex] == '+')
{
baseUtcOffsetDelta = GetNextTimeSpanValue();
}
// Check if we have NoDaylightTransitions in the serialized string and then deserialize it
if ((_serializedText[_currentTokenStartIndex] >= '0' && _serializedText[_currentTokenStartIndex] <= '1'))
{
noDaylightTransitions = GetNextInt32Value();
}
if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
if (_serializedText[_currentTokenStartIndex] != Rhs)
{
// skip ahead of any "v.Next" data at the end of the AdjustmentRule
//
// FUTURE: if the serialization format is extended in the future then this
// code section will need to be changed to read the new fields rather
// than just skipping the data at the end of the [AdjustmentRule].
SkipVersionNextDataFields(1);
}
else
{
_currentTokenStartIndex++;
}
// create the AdjustmentRule from the deserialized fields ...
AdjustmentRule rule;
try
{
rule = AdjustmentRule.CreateAdjustmentRule(dateStart, dateEnd, daylightDelta, daylightStart, daylightEnd, baseUtcOffsetDelta, noDaylightTransitions > 0);
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
// finally set the state to either EndOfLine or StartOfToken for the next caller
if (_currentTokenStartIndex >= _serializedText.Length)
{
_state = State.EndOfLine;
}
else
{
_state = State.StartOfToken;
}
return rule;
}
/// <summary>
/// Helper function to read a TransitionTime token.
/// </summary>
private TransitionTime GetNextTransitionTimeValue()
{
// first verify the internal state of the object
if (_state == State.EndOfLine ||
(_currentTokenStartIndex < _serializedText.Length && _serializedText[_currentTokenStartIndex] == Rhs))
{
//
// we are at the end of the line or we are starting at a "]" character
//
throw new SerializationException(SR.Serialization_InvalidData);
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
// verify the current token is a left-hand-side marker ("[")
if (_serializedText[_currentTokenStartIndex] != Lhs)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
_currentTokenStartIndex++;
int isFixedDate = GetNextInt32Value();
if (isFixedDate != 0 && isFixedDate != 1)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
TransitionTime transition;
DateTime timeOfDay = GetNextDateTimeValue(TimeOfDayFormat);
timeOfDay = new DateTime(1, 1, 1, timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
int month = GetNextInt32Value();
if (isFixedDate == 1)
{
int day = GetNextInt32Value();
try
{
transition = TransitionTime.CreateFixedDateRule(timeOfDay, month, day);
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
else
{
int week = GetNextInt32Value();
int dayOfWeek = GetNextInt32Value();
try
{
transition = TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, (DayOfWeek)dayOfWeek);
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
// verify that the string is now at the right-hand-side marker ("]") ...
if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
{
throw new SerializationException(SR.Serialization_InvalidData);
}
if (_serializedText[_currentTokenStartIndex] != Rhs)
{
// skip ahead of any "v.Next" data at the end of the AdjustmentRule
//
// FUTURE: if the serialization format is extended in the future then this
// code section will need to be changed to read the new fields rather
// than just skipping the data at the end of the [TransitionTime].
SkipVersionNextDataFields(1);
}
else
{
_currentTokenStartIndex++;
}
// check to see if the string is now at the separator (";") ...
bool sepFound = false;
if (_currentTokenStartIndex < _serializedText.Length &&
_serializedText[_currentTokenStartIndex] == Sep)
{
// handle the case where we ended on a ";"
_currentTokenStartIndex++;
sepFound = true;
}
if (!sepFound)
{
// we MUST end on a separator
throw new SerializationException(SR.Serialization_InvalidData);
}
// finally set the state to either EndOfLine or StartOfToken for the next caller
if (_currentTokenStartIndex >= _serializedText.Length)
{
_state = State.EndOfLine;
}
else
{
_state = State.StartOfToken;
}
return transition;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// This editor helper class makes it easy to create and show a context menu.
/// It ensures that it's possible to add multiple items with the same name.
/// </summary>
public static class NGUIContextMenu
{
[MenuItem("Help/NGUI Documentation (v.3.7.7)")]
static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); }
[MenuItem("Help/NGUI Support Forum")]
static void ShowHelp01 (MenuCommand command) { Application.OpenURL("http://www.tasharen.com/forum/index.php?board=1.0"); }
[MenuItem("CONTEXT/UIWidget/Copy Widget")]
static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Values")]
static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Style")]
static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); }
[MenuItem("CONTEXT/UIWidget/Help")]
static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); }
[MenuItem("CONTEXT/UIButton/Help")]
static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); }
[MenuItem("CONTEXT/UIToggle/Help")]
static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); }
[MenuItem("CONTEXT/UIRoot/Help")]
static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); }
[MenuItem("CONTEXT/UICamera/Help")]
static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); }
[MenuItem("CONTEXT/UIAnchor/Help")]
static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); }
[MenuItem("CONTEXT/UIStretch/Help")]
static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); }
[MenuItem("CONTEXT/UISlider/Help")]
static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); }
[MenuItem("CONTEXT/UI2DSprite/Help")]
static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); }
[MenuItem("CONTEXT/UIScrollBar/Help")]
static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); }
[MenuItem("CONTEXT/UIProgressBar/Help")]
static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); }
[MenuItem("CONTEXT/UIPopupList/Help")]
static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); }
[MenuItem("CONTEXT/UIInput/Help")]
static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); }
[MenuItem("CONTEXT/UIKeyBinding/Help")]
static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); }
[MenuItem("CONTEXT/UIGrid/Help")]
static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); }
[MenuItem("CONTEXT/UITable/Help")]
static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); }
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); }
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIPlaySound/Help")]
static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); }
[MenuItem("CONTEXT/UICenterOnChild/Help")]
static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); }
[MenuItem("CONTEXT/UICenterOnClick/Help")]
static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); }
[MenuItem("CONTEXT/UITweener/Help")]
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); }
[MenuItem("CONTEXT/ActiveAnimation/Help")]
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIPanel/Help")]
static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); }
[MenuItem("CONTEXT/UILocalize/Help")]
static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); }
[MenuItem("CONTEXT/Localization/Help")]
static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); }
[MenuItem("CONTEXT/UIKeyNavigation/Help")]
static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); }
[MenuItem("CONTEXT/PropertyBinding/Help")]
static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); }
public delegate UIWidget AddFunc (GameObject go);
static List<string> mEntries = new List<string>();
static GenericMenu mMenu;
/// <summary>
/// Clear the context menu list.
/// </summary>
static public void Clear ()
{
mEntries.Clear();
mMenu = null;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, callback, param);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddChild (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeGameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddChildWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddSibling (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeTransform.parent.gameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Add commonly NGUI context menu options.
/// </summary>
static public void AddCommonItems (GameObject target)
{
if (target != null)
{
UIWidget widget = target.GetComponent<UIWidget>();
string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object");
AddItem(myName + "/Bring to Front", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.BringForward(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Push to Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.PushBack(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Nudge Forward", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], 1);
},
null);
AddItem(myName + "/Nudge Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], -1);
},
null);
if (widget != null)
{
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform);
if (target.GetComponent<BoxCollider>() != null)
{
AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target);
}
}
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Delete", false, OnDelete, target);
NGUIContextMenu.AddSeparator("");
if (Selection.activeTransform.parent != null && widget != null)
{
AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite);
AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite);
AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel);
AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget);
AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture);
AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite);
}
else
{
AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite);
}
NGUIContextMenu.AddSeparator("Create/");
AddItem("Create/Panel", false, AddPanel, target);
AddItem("Create/Scroll View", false, AddScrollView, target);
AddItem("Create/Grid", false, AddChild<UIGrid>, target);
AddItem("Create/Table", false, AddChild<UITable>, target);
AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target);
if (target.GetComponent<UIPanel>() != null)
{
if (target.GetComponent<UIScrollView>() == null)
{
AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView));
NGUIContextMenu.AddSeparator("Attach/");
}
}
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
else if (target.collider == null && target.GetComponent<Collider2D>() == null)
#else
else if (target.GetComponent<Collider>() == null && target.GetComponent<Collider2D>() == null)
#endif
{
AddItem("Attach/Box Collider", false, AttachCollider, null);
NGUIContextMenu.AddSeparator("Attach/");
}
bool header = false;
UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target);
if (scrollView != null)
{
if (scrollView.GetComponentInChildren<UICenterOnChild>() == null)
{
AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild));
header = true;
}
}
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
if (target.collider != null || target.GetComponent<Collider2D>() != null)
#else
if (target.GetComponent<Collider>() != null || target.GetComponent<Collider2D>() != null)
#endif
{
if (scrollView != null)
{
if (target.GetComponent<UIDragScrollView>() == null)
{
AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView));
header = true;
}
if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null)
{
AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick));
header = true;
}
}
if (header) NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Button Script", false, Attach, typeof(UIButton));
AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle));
AddItem("Attach/Slider Script", false, Attach, typeof(UISlider));
AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar));
AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider));
AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList));
AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput));
NGUIContextMenu.AddSeparator("Attach/");
if (target.GetComponent<UIDragResize>() == null)
AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize));
if (target.GetComponent<UIDragScrollView>() == null)
{
for (int i = 0; i < UIPanel.list.Count; ++i)
{
UIPanel pan = UIPanel.list[i];
if (pan.clipping == UIDrawCall.Clipping.None) continue;
UIScrollView dr = pan.GetComponent<UIScrollView>();
if (dr == null) continue;
AddItem("Attach/Drag Scroll View", false, delegate(object obj)
{ target.AddComponent<UIDragScrollView>().scrollView = dr; }, null);
header = true;
break;
}
}
AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding));
if (target.GetComponent<UIKeyNavigation>() == null)
AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation));
NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween));
AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation));
AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound));
}
AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding));
if (target.GetComponent<UILocalize>() == null)
AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize));
if (widget != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
AddMissingItem<TweenColor>(target, "Tween/Color");
AddMissingItem<TweenWidth>(target, "Tween/Width");
AddMissingItem<TweenHeight>(target, "Tween/Height");
}
else if (target.GetComponent<UIPanel>() != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
}
NGUIContextMenu.AddSeparator("Tween/");
AddMissingItem<TweenPosition>(target, "Tween/Position");
AddMissingItem<TweenRotation>(target, "Tween/Rotation");
AddMissingItem<TweenScale>(target, "Tween/Scale");
AddMissingItem<TweenTransform>(target, "Tween/Transform");
if (target.GetComponent<AudioSource>() != null)
AddMissingItem<TweenVolume>(target, "Tween/Volume");
if (target.GetComponent<Camera>() != null)
{
AddMissingItem<TweenFOV>(target, "Tween/Field of View");
AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size");
}
}
}
/// <summary>
/// Helper function that adds a widget collider to the specified object.
/// </summary>
static void AttachCollider (object obj)
{
if (Selection.activeGameObject != null)
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AddWidgetCollider(Selection.gameObjects[i]);
}
/// <summary>
/// Helper function that adds the specified type to all selected game objects. Used with the menu options above.
/// </summary>
static void Attach (object obj)
{
if (Selection.activeGameObject == null) return;
System.Type type = (System.Type)obj;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
{
GameObject go = Selection.gameObjects[i];
if (go.GetComponent(type) != null) continue;
#if !UNITY_3_5
Component cmp = go.AddComponent(type);
Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type);
#endif
}
}
/// <summary>
/// Helper function.
/// </summary>
static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour
{
if (target.GetComponent<T>() == null)
AddItem(name, false, Attach, typeof(T));
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddChild<T> (object obj) where T : MonoBehaviour
{
GameObject go = obj as GameObject;
T t = NGUITools.AddChild<T>(go);
Selection.activeGameObject = t.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddPanel (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddScrollView (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
panel.clipping = UIDrawCall.Clipping.SoftClip;
panel.gameObject.AddComponent<UIScrollView>();
panel.name = "Scroll View";
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Add help options based on the components present on the specified game object.
/// </summary>
static public void AddHelp (GameObject go, bool addSeparator)
{
MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>();
bool addedSomething = false;
for (int i = 0; i < comps.Length; ++i)
{
System.Type type = comps[i].GetType();
string url = NGUIHelp.GetHelpURL(type);
if (url != null)
{
if (addSeparator)
{
addSeparator = false;
AddSeparator("");
}
AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null);
addedSomething = true;
}
}
if (addedSomething) AddSeparator("Help/");
AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null);
}
static void OnHelp (object obj) { NGUIHelp.Show(obj); }
static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); }
static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); }
static void OnDelete (object obj)
{
GameObject go = obj as GameObject;
Selection.activeGameObject = go.transform.parent.gameObject;
Undo.DestroyObjectImmediate(go);
}
/// <summary>
/// Add a new disabled context menu entry.
/// </summary>
static public void AddDisabledItem (string item)
{
if (mMenu == null) mMenu = new GenericMenu();
mMenu.AddDisabledItem(new GUIContent(item));
}
/// <summary>
/// Add a separator to the menu.
/// </summary>
static public void AddSeparator (string path)
{
if (mMenu == null) mMenu = new GenericMenu();
// For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf?
if (Application.platform != RuntimePlatform.OSXEditor)
mMenu.AddSeparator(path);
}
/// <summary>
/// Show the context menu with all the added items.
/// </summary>
static public void Show ()
{
if (mMenu != null)
{
mMenu.ShowAsContext();
mMenu = null;
mEntries.Clear();
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the VgiCInterconsultaItem class.
/// </summary>
[Serializable]
public partial class VgiCInterconsultaItemCollection : ActiveList<VgiCInterconsultaItem, VgiCInterconsultaItemCollection>
{
public VgiCInterconsultaItemCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>VgiCInterconsultaItemCollection</returns>
public VgiCInterconsultaItemCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
VgiCInterconsultaItem 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 VGI_CInterconsultaItems table.
/// </summary>
[Serializable]
public partial class VgiCInterconsultaItem : ActiveRecord<VgiCInterconsultaItem>, IActiveRecord
{
#region .ctors and Default Settings
public VgiCInterconsultaItem()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public VgiCInterconsultaItem(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public VgiCInterconsultaItem(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public VgiCInterconsultaItem(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("VGI_CInterconsultaItems", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdCInterconsultaItems = new TableSchema.TableColumn(schema);
colvarIdCInterconsultaItems.ColumnName = "idCInterconsultaItems";
colvarIdCInterconsultaItems.DataType = DbType.Int32;
colvarIdCInterconsultaItems.MaxLength = 0;
colvarIdCInterconsultaItems.AutoIncrement = true;
colvarIdCInterconsultaItems.IsNullable = false;
colvarIdCInterconsultaItems.IsPrimaryKey = true;
colvarIdCInterconsultaItems.IsForeignKey = false;
colvarIdCInterconsultaItems.IsReadOnly = false;
colvarIdCInterconsultaItems.DefaultSetting = @"";
colvarIdCInterconsultaItems.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdCInterconsultaItems);
TableSchema.TableColumn colvarIdItems = new TableSchema.TableColumn(schema);
colvarIdItems.ColumnName = "idItems";
colvarIdItems.DataType = DbType.Int32;
colvarIdItems.MaxLength = 0;
colvarIdItems.AutoIncrement = false;
colvarIdItems.IsNullable = true;
colvarIdItems.IsPrimaryKey = false;
colvarIdItems.IsForeignKey = false;
colvarIdItems.IsReadOnly = false;
colvarIdItems.DefaultSetting = @"";
colvarIdItems.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdItems);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "Nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 200;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarValor = new TableSchema.TableColumn(schema);
colvarValor.ColumnName = "Valor";
colvarValor.DataType = DbType.Int32;
colvarValor.MaxLength = 0;
colvarValor.AutoIncrement = false;
colvarValor.IsNullable = true;
colvarValor.IsPrimaryKey = false;
colvarValor.IsForeignKey = false;
colvarValor.IsReadOnly = false;
colvarValor.DefaultSetting = @"";
colvarValor.ForeignKeyTableName = "";
schema.Columns.Add(colvarValor);
TableSchema.TableColumn colvarCInterconsulta = new TableSchema.TableColumn(schema);
colvarCInterconsulta.ColumnName = "CInterconsulta";
colvarCInterconsulta.DataType = DbType.AnsiString;
colvarCInterconsulta.MaxLength = 100;
colvarCInterconsulta.AutoIncrement = false;
colvarCInterconsulta.IsNullable = true;
colvarCInterconsulta.IsPrimaryKey = false;
colvarCInterconsulta.IsForeignKey = false;
colvarCInterconsulta.IsReadOnly = false;
colvarCInterconsulta.DefaultSetting = @"";
colvarCInterconsulta.ForeignKeyTableName = "";
schema.Columns.Add(colvarCInterconsulta);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("VGI_CInterconsultaItems",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdCInterconsultaItems")]
[Bindable(true)]
public int IdCInterconsultaItems
{
get { return GetColumnValue<int>(Columns.IdCInterconsultaItems); }
set { SetColumnValue(Columns.IdCInterconsultaItems, value); }
}
[XmlAttribute("IdItems")]
[Bindable(true)]
public int? IdItems
{
get { return GetColumnValue<int?>(Columns.IdItems); }
set { SetColumnValue(Columns.IdItems, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("Valor")]
[Bindable(true)]
public int? Valor
{
get { return GetColumnValue<int?>(Columns.Valor); }
set { SetColumnValue(Columns.Valor, value); }
}
[XmlAttribute("CInterconsulta")]
[Bindable(true)]
public string CInterconsulta
{
get { return GetColumnValue<string>(Columns.CInterconsulta); }
set { SetColumnValue(Columns.CInterconsulta, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int? varIdItems,string varNombre,int? varValor,string varCInterconsulta)
{
VgiCInterconsultaItem item = new VgiCInterconsultaItem();
item.IdItems = varIdItems;
item.Nombre = varNombre;
item.Valor = varValor;
item.CInterconsulta = varCInterconsulta;
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 varIdCInterconsultaItems,int? varIdItems,string varNombre,int? varValor,string varCInterconsulta)
{
VgiCInterconsultaItem item = new VgiCInterconsultaItem();
item.IdCInterconsultaItems = varIdCInterconsultaItems;
item.IdItems = varIdItems;
item.Nombre = varNombre;
item.Valor = varValor;
item.CInterconsulta = varCInterconsulta;
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 IdCInterconsultaItemsColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdItemsColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ValorColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn CInterconsultaColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdCInterconsultaItems = @"idCInterconsultaItems";
public static string IdItems = @"idItems";
public static string Nombre = @"Nombre";
public static string Valor = @"Valor";
public static string CInterconsulta = @"CInterconsulta";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Types;
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
namespace IronPython.Runtime.Operations {
public static class ArrayOps {
#region Python APIs
[SpecialName]
public static Array Add(Array data1, Array data2) {
if (data1 == null) throw PythonOps.TypeError("expected array for 1st argument, got None");
if (data2 == null) throw PythonOps.TypeError("expected array for 2nd argument, got None");
if (data1.Rank > 1 || data2.Rank > 1) throw new NotImplementedException("can't add multidimensional arrays");
Type type1 = data1.GetType();
Type type2 = data2.GetType();
Type type = (type1 == type2) ? type1.GetElementType()! : typeof(object);
Array ret = Array.CreateInstance(type, data1.Length + data2.Length);
Array.Copy(data1, 0, ret, 0, data1.Length);
Array.Copy(data2, 0, ret, data1.Length, data2.Length);
return ret;
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType pythonType, int length) {
Type type = pythonType.UnderlyingSystemType.GetElementType()!;
return Array.CreateInstance(type, length);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType pythonType, params int[] lengths) {
Type type = pythonType.UnderlyingSystemType.GetElementType()!;
return Array.CreateInstance(type, lengths);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType pythonType, ICollection items) {
Type type = pythonType.UnderlyingSystemType.GetElementType()!;
Array res = Array.CreateInstance(type, items.Count);
int i = 0;
foreach (var item in items) {
res.SetValue(Converter.Convert(item, type), i++);
}
return res;
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType pythonType, object items) {
Type type = pythonType.UnderlyingSystemType.GetElementType()!;
object? lenFunc;
if (!PythonOps.TryGetBoundAttr(items, "__len__", out lenFunc))
throw PythonOps.TypeErrorForBadInstance("expected object with __len__ function, got {0}", items);
int len = context.LanguageContext.ConvertToInt32(PythonOps.CallWithContext(context, lenFunc));
Array res = Array.CreateInstance(type, len);
IEnumerator ie = PythonOps.GetEnumerator(items);
int i = 0;
while (ie.MoveNext()) {
res.SetValue(Converter.Convert(ie.Current, type), i++);
}
return res;
}
/// <summary>
/// Multiply two object[] arrays - slow version, we need to get the type, etc...
/// </summary>
[SpecialName]
public static Array Multiply(Array data, int count) {
if (data.Rank > 1) throw new NotImplementedException("can't multiply multidimensional arrays");
Type elemType = data.GetType().GetElementType()!;
if (count <= 0) return Array.CreateInstance(elemType, 0);
int newCount = data.Length * count;
Array ret = Array.CreateInstance(elemType, newCount);
Array.Copy(data, 0, ret, 0, data.Length);
// this should be extremely fast for large count as it uses the same algoithim as efficient integer powers
// ??? need to test to see how large count and n need to be for this to be fastest approach
int block = data.Length;
int pos = data.Length;
while (pos < newCount) {
Array.Copy(ret, 0, ret, pos, Math.Min(block, newCount - pos));
pos += block;
block *= 2;
}
return ret;
}
[SpecialName]
public static object? GetItem(Array data, int index) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
if (data.Rank != 1) throw PythonOps.TypeError("bad dimensions for array, got {0} expected {1}", 1, data.Rank);
return data.GetValue(PythonOps.FixIndex(index, data.Length) + data.GetLowerBound(0));
}
[SpecialName]
public static object GetItem(Array data, Slice slice) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
return GetSlice(data, data.Length, slice);
}
[SpecialName]
public static object? GetItem(Array data, PythonTuple tuple) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
return GetItem(data, tuple._data);
}
[SpecialName]
public static object? GetItem(Array data, params object?[] indices) {
if (indices == null || indices.Length < 1) throw PythonOps.TypeError("__getitem__ requires at least 1 parameter");
if (indices.Length == 1 && Converter.TryConvertToInt32(indices[0], out int iindex)) {
return GetItem(data, iindex);
}
Type t = data.GetType();
Debug.Assert(t.HasElementType);
int[] iindices = TupleToIndices(data, indices);
if (data.Rank != indices.Length) throw PythonOps.TypeError("bad dimensions for array, got {0} expected {1}", indices.Length, data.Rank);
for (int i = 0; i < iindices.Length; i++) iindices[i] += data.GetLowerBound(i);
return data.GetValue(iindices);
}
[SpecialName]
public static void SetItem(Array data, int index, object value) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
if (data.Rank != 1) throw PythonOps.TypeError("bad dimensions for array, got {0} expected {1}", 1, data.Rank);
data.SetValue(Converter.Convert(value, data.GetType().GetElementType()), PythonOps.FixIndex(index, data.Length) + data.GetLowerBound(0));
}
[SpecialName]
public static void SetItem(Array a, params object[] indexAndValue) {
if (indexAndValue == null || indexAndValue.Length < 2) throw PythonOps.TypeError("__setitem__ requires at least 2 parameters");
if (indexAndValue.Length == 2 && Converter.TryConvertToInt32(indexAndValue[0], out int iindex)) {
SetItem(a, iindex, indexAndValue[1]);
return;
}
Type t = a.GetType();
Debug.Assert(t.HasElementType);
object[] args = ArrayUtils.RemoveLast(indexAndValue);
int[] indices = TupleToIndices(a, args);
if (a.Rank != args.Length) throw PythonOps.TypeError("bad dimensions for array, got {0} expected {1}", args.Length, a.Rank);
for (int i = 0; i < indices.Length; i++) indices[i] += a.GetLowerBound(i);
Type elm = t.GetElementType()!;
a.SetValue(Converter.Convert(indexAndValue[indexAndValue.Length - 1], elm), indices);
}
[SpecialName]
public static void SetItem(Array a, Slice index, object? value) {
if (a.Rank != 1) throw PythonOps.NotImplementedError("slice on multi-dimensional array");
Type elm = a.GetType().GetElementType()!;
index.DoSliceAssign(
delegate (int idx, object? val) {
a.SetValue(Converter.Convert(val, elm), idx + a.GetLowerBound(0));
},
a.Length,
value);
}
public static string __repr__(CodeContext/*!*/ context, [NotNull]Array/*!*/ self) {
var infinite = PythonOps.GetAndCheckInfinite(self);
if (infinite == null) {
return "...";
}
int index = infinite.Count;
infinite.Add(self);
try {
StringBuilder ret = new StringBuilder();
if (self.Rank == 1) {
// single dimensional Array's have a valid display
ret.Append("Array[");
Type elemType = self.GetType().GetElementType()!;
ret.Append(DynamicHelpers.GetPythonTypeFromType(elemType).Name);
ret.Append("]");
ret.Append("((");
for (int i = 0; i < self.Length; i++) {
if (i > 0) ret.Append(", ");
ret.Append(PythonOps.Repr(context, self.GetValue(i + self.GetLowerBound(0))));
}
ret.Append("))");
} else {
// multi dimensional arrays require multiple statements to construct so we just
// give enough info to identify the object and its type.
ret.Append("<");
ret.Append(self.Rank);
ret.Append(" dimensional Array[");
Type elemType = self.GetType().GetElementType()!;
ret.Append(DynamicHelpers.GetPythonTypeFromType(elemType).Name);
ret.Append("] at ");
ret.Append(PythonOps.HexId(self));
ret.Append(">");
}
return ret.ToString();
} finally {
System.Diagnostics.Debug.Assert(index == infinite.Count - 1);
infinite.RemoveAt(index);
}
}
#endregion
#region Internal APIs
/// <summary>
/// Multiply two object[] arrays - internal version used for objects backed by arrays
/// </summary>
internal static object?[] Multiply(object?[] data, int size, int count) {
int newCount;
try {
newCount = checked(size * count);
} catch (OverflowException) {
throw PythonOps.MemoryError();
}
var ret = ArrayOps.CopyArray(data, newCount);
if (count > 0) {
// this should be extremely fast for large count as it uses the same algoithim as efficient integer powers
// ??? need to test to see how large count and n need to be for this to be fastest approach
int block = size;
int pos = size;
while (pos < newCount) {
Array.Copy(ret, 0, ret, pos, Math.Min(block, newCount - pos));
pos += block;
block *= 2;
}
}
return ret;
}
/// <summary>
/// Add two arrays - internal versions for objects backed by arrays
/// </summary>
/// <param name="data1"></param>
/// <param name="size1"></param>
/// <param name="data2"></param>
/// <param name="size2"></param>
/// <returns></returns>
internal static object?[] Add(object?[] data1, int size1, object?[] data2, int size2) {
var ret = ArrayOps.CopyArray(data1, size1 + size2);
Array.Copy(data2, 0, ret, size1, size2);
return ret;
}
internal static object?[] GetSlice(object?[] data, int start, int stop) {
if (stop <= start) return ArrayUtils.EmptyObjects;
var ret = new object?[stop - start];
int index = 0;
for (int i = start; i < stop; i++) {
ret[index++] = data[i];
}
return ret;
}
internal static object?[] GetSlice(object?[] data, int start, int stop, int step) {
Debug.Assert(step != 0);
if (step == 1) {
return GetSlice(data, start, stop);
}
int size = PythonOps.GetSliceCount(start, stop, step);
if (size <= 0) return ArrayUtils.EmptyObjects;
var res = new object?[size];
for (int i = 0, index = start; i < res.Length; i++, index += step) {
res[i] = data[index];
}
return res;
}
internal static object?[] GetSlice(object?[] data, Slice slice) {
int start, stop, step;
slice.indices(data.Length, out start, out stop, out step);
return GetSlice(data, start, stop, step);
}
internal static Array GetSlice(Array data, int size, Slice slice) {
if (data.Rank != 1) throw PythonOps.NotImplementedError("slice on multi-dimensional array");
int start, stop, step;
slice.indices(size, out start, out stop, out step);
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
if (data.GetType().GetElementType() == typeof(object))
return ArrayUtils.EmptyObjects;
return Array.CreateInstance(data.GetType().GetElementType()!, 0);
}
if (step == 1) {
int n = stop - start;
Array ret = Array.CreateInstance(data.GetType().GetElementType()!, n);
Array.Copy(data, start + data.GetLowerBound(0), ret, 0, n);
return ret;
} else {
int n = PythonOps.GetSliceCount(start, stop, step);
Array ret = Array.CreateInstance(data.GetType().GetElementType()!, n);
int ri = 0;
for (int i = 0, index = start; i < n; i++, index += step) {
ret.SetValue(data.GetValue(index + data.GetLowerBound(0)), ri++);
}
return ret;
}
}
internal static object?[] CopyArray(object?[] data, int newSize) {
if (newSize == 0) return ArrayUtils.EmptyObjects;
var newData = new object?[newSize];
if (data.Length < 20) {
for (int i = 0; i < data.Length && i < newSize; i++) {
newData[i] = data[i];
}
} else {
Array.Copy(data, newData, Math.Min(newSize, data.Length));
}
return newData;
}
#endregion
#region Private helpers
private static int[] TupleToIndices(Array a, IList<object?> tuple) {
int[] indices = new int[tuple.Count];
for (int i = 0; i < indices.Length; i++) {
int iindex = Converter.ConvertToInt32(tuple[i]);
indices[i] = i < a.Rank ? PythonOps.FixIndex(iindex, a.GetLength(i)) : int.MinValue;
}
return indices;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Xml.Tests
{
public class RemoveChildTests
{
private static readonly XmlNodeType[] s_XmlNodeTypes = new XmlNodeType[] { XmlNodeType.Whitespace, XmlNodeType.SignificantWhitespace, XmlNodeType.CDATA, XmlNodeType.Text, XmlNodeType.Comment };
private enum InsertType { InsertBefore, InsertAfter }
[Fact]
public static void IterativelyRemoveAllChildNodes()
{
var xml = @"<root>
text node one
<elem1 child1="""" child2=""duu"" child3=""e1;e2;"" child4=""a1"" child5=""goody"">
text node two e1; text node three
</elem1><!-- comment3 --><?PI3 processing instruction?>e2;<foo /><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><elem2 att1=""id1"" att2=""up"" att3=""attribute3""><a /></elem2><elem2>
elem2-text1
<a>
this-is-a
</a>
elem2-text2
e3;e4;<!-- elem2-comment1-->
elem2-text3
<b>
this-is-b
</b>
elem2-text4
<?elem2_PI elem2-PI?>
elem2-text5
</elem2></root>";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
var count = xmlDocument.DocumentElement.ChildNodes.Count;
for (int idx = 0; idx < count; idx++)
xmlDocument.DocumentElement.RemoveChild(xmlDocument.DocumentElement.ChildNodes[0]);
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
}
[Fact]
public static void RemoveDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<?PI pi1?><root><child1/><child2/><child3/></root><!--comment-->");
var root = xmlDocument.DocumentElement;
Assert.Equal(3, xmlDocument.ChildNodes.Count);
xmlDocument.RemoveChild(root);
Assert.Equal(2, xmlDocument.ChildNodes.Count);
Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.ChildNodes[0].NodeType);
Assert.Equal(XmlNodeType.Comment, xmlDocument.ChildNodes[1].NodeType);
}
[Fact]
public static void OldChildIsNull()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
Assert.Throws<NullReferenceException>(() => xmlDocument.DocumentElement.RemoveChild(null));
}
[Fact]
public static void OldChildIsFirstChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(child1, xmlDocument.DocumentElement.FirstChild);
xmlDocument.DocumentElement.RemoveChild(child1);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(child2, xmlDocument.DocumentElement.FirstChild);
}
[Fact]
public static void NotChildNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1><gchild1/></child1><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Throws<ArgumentException>(() => child1.RemoveChild(child2));
}
[Fact]
public static void AccessRemovedChildByReference()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>child1</root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
Assert.Equal("child1", child1.Value);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
xmlDocument.DocumentElement.RemoveChild(child1);
Assert.Equal("child1", child1.Value);
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
}
[Fact]
public static void RepeatedRemoveInsert()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var element = xmlDocument.CreateElement("elem");
for (int i = 0; i < 100; i++)
{
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
xmlDocument.DocumentElement.AppendChild(element);
Assert.True(xmlDocument.DocumentElement.HasChildNodes);
xmlDocument.DocumentElement.RemoveChild(element);
}
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
Assert.Null(element.ParentNode);
}
[Fact]
public static void FromNodesThatCannotContainChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><?PI pi node?>some test<!--comment--><![CDATA[some data]]></root>");
var piNode = xmlDocument.DocumentElement.ChildNodes[0];
var textNode = xmlDocument.DocumentElement.ChildNodes[1];
var commentNode = xmlDocument.DocumentElement.ChildNodes[2];
var cdataNode = xmlDocument.DocumentElement.ChildNodes[3];
Assert.Equal(XmlNodeType.ProcessingInstruction, piNode.NodeType);
Assert.Throws<InvalidOperationException>(() => piNode.RemoveChild(null));
Assert.Equal(XmlNodeType.Text, textNode.NodeType);
Assert.Throws<InvalidOperationException>(() => textNode.RemoveChild(null));
Assert.Equal(XmlNodeType.Comment, commentNode.NodeType);
Assert.Throws<InvalidOperationException>(() => commentNode.RemoveChild(null));
Assert.Equal(XmlNodeType.CDATA, cdataNode.NodeType);
Assert.Throws<InvalidOperationException>(() => cdataNode.RemoveChild(null));
}
[Fact]
public static void Text_Text_Text()
{
RemoveChildTestBase(new[] { XmlNodeType.Text, XmlNodeType.Text, XmlNodeType.Text });
}
[Fact]
public static void Whitespace_Whitespace_Whitespace()
{
RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.Whitespace, XmlNodeType.Whitespace, XmlNodeType.Whitespace });
}
[Fact]
public static void SignificantWhitespace_SignificantWhitespace_SignificantWhitespace()
{
RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.SignificantWhitespace, XmlNodeType.SignificantWhitespace, XmlNodeType.SignificantWhitespace });
}
[Fact]
public static void CDATA_CDATA_CDATA()
{
RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.CDATA, XmlNodeType.CDATA, XmlNodeType.CDATA });
}
[Fact]
public static void Whitespace_Text_Text_CDATA_SignificantWhitespace_SignificantWhitespace()
{
RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.Whitespace, XmlNodeType.Text, XmlNodeType.Text, XmlNodeType.CDATA, XmlNodeType.SignificantWhitespace, XmlNodeType.SignificantWhitespace });
}
[Fact]
public static void Text_Comment_CDATA()
{
var xml = @"<TMC>text<!-- comments --><![CDATA[ < & <tag> < ! > & </tag> ]]></TMC>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertBefore, nodeType);
}
[Fact]
public static void Text_Comment_SignificantWhitespace()
{
var xml = @"<TCS xml:space=""preserve"">text<!-- comments --> </TCS>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertBefore, nodeType);
}
[Fact]
public static void Whitespace_Comment_Text()
{
var xml = @"<WMT>
<!-- comments -->text</WMT>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertBefore, nodeType);
}
[Fact]
public static void Whitespace_Element_Whitespace()
{
var xml = @"<WEW>
<E/>
</WEW>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType);
}
[Fact]
public static void Text_Element_Text()
{
var xml = @"<TET>text1<E/>text2</TET>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType);
}
[Fact]
public static void SignificantWhitespace_Element_SignificantWhitespace()
{
var xml = @" <SES xml:space=""preserve""> <E/> </SES>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType);
}
[Fact]
public static void CDATA_Element_CDATA()
{
var xml = @"<CEC><![CDATA[ < & <tag> < ! > & </tag> ]]><E/><![CDATA[ < & <tag> < ! > & </tag> ]]></CEC>";
foreach (var nodeType in s_XmlNodeTypes)
DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType);
}
private static void RemoveChildTestBase(XmlNodeType[] nodeTypes)
{
for (int i = 0; i < nodeTypes.Length; i++)
RemoveChildTestBase(nodeTypes, i);
}
private static void DeleteNonTextNodeBase(string xml, InsertType insertType, XmlNodeType nodeType)
{
string[] expected = new string[3];
var xmlDocument = new XmlDocument { PreserveWhitespace = true };
xmlDocument.LoadXml(xml);
XmlNode parent = xmlDocument.DocumentElement;
XmlNode firstChild = parent.FirstChild;
XmlNode lastChild = parent.LastChild;
XmlNode nodeToRemove = parent.FirstChild.NextSibling;
expected[0] = firstChild.OuterXml + lastChild.OuterXml;
// deletion
parent.RemoveChild(nodeToRemove);
// verify
Assert.Equal(2, parent.ChildNodes.Count);
Assert.Equal(expected[0], parent.InnerXml);
Assert.Equal(firstChild.ParentNode, parent);
Assert.Equal(lastChild.ParentNode, parent);
VerifySiblings(firstChild, lastChild, InsertType.InsertAfter);
// now, parent contains two textnodes only
XmlNode newChild = CreateNode(xmlDocument, nodeType);
XmlNode refChild = (insertType == InsertType.InsertBefore) ? lastChild : firstChild;
expected[1] = firstChild.OuterXml + newChild.OuterXml + lastChild.OuterXml;
expected[2] = parent.InnerXml;
// insertion
var insertDelegate = CreateInsertBeforeOrAfter(insertType);
insertDelegate(parent, newChild, refChild);
// verify
Assert.Equal(3, parent.ChildNodes.Count);
Assert.Equal(expected[1], parent.InnerXml);
Assert.Equal(newChild.ParentNode, parent);
Assert.Equal(lastChild.ParentNode, parent);
Assert.Equal(firstChild.ParentNode, parent);
VerifySiblings(firstChild, newChild, InsertType.InsertAfter);
VerifySiblings(newChild, lastChild, InsertType.InsertAfter);
// delete the newChild
parent.RemoveChild(newChild);
// verify
Assert.Equal(2, parent.ChildNodes.Count);
Assert.Equal(expected[2], parent.InnerXml);
Assert.Equal(firstChild.ParentNode, parent);
Assert.Equal(lastChild.ParentNode, parent);
VerifySiblings(firstChild, lastChild, InsertType.InsertAfter);
}
private static void RemoveChildTestBase(XmlNodeType[] nodeTypes, int ithNodeToRemove)
{
int total = nodeTypes.Length;
XmlDocument doc = new XmlDocument { PreserveWhitespace = true };
var parent = doc.CreateElement("root");
doc.AppendChild(parent);
var newChildren = new XmlNode[total];
string expected = string.Empty;
for (int i = 0; i < total; i++)
{
newChildren[i] = CreateNode(doc, nodeTypes[i]);
parent.AppendChild(newChildren[i]);
expected += newChildren[i].OuterXml;
}
Assert.Equal(total, parent.ChildNodes.Count);
Assert.Equal(expected, parent.InnerXml);
for (int i = 0; i < total - 1; i++)
{
Verify(parent, newChildren[i], newChildren[i + 1]);
VerifySiblings(newChildren[i], newChildren[i + 1]);
}
expected = string.Empty;
for (int i = 0; i < total; i++)
if (i != ithNodeToRemove)
expected += newChildren[i].OuterXml;
// remove either the FirstChild or LastChild according to the value of ithNodeToRemove
parent.RemoveChild(newChildren[ithNodeToRemove]);
Assert.Equal(total - 1, parent.ChildNodes.Count);
Assert.Equal(expected, parent.InnerXml);
}
private static void VerifySiblings(XmlNode refChild, XmlNode newChild)
{
Assert.Equal(newChild, refChild.NextSibling);
Assert.Equal(refChild, newChild.PreviousSibling);
}
private static void VerifySiblings(XmlNode refChild, XmlNode newChild, InsertType insertType)
{
switch (insertType)
{
case InsertType.InsertBefore:
VerifySiblings(newChild, refChild);
break;
case InsertType.InsertAfter:
VerifySiblings(refChild, newChild);
break;
default:
throw new ArgumentException("Wrong InsertType: '" + insertType + "'");
}
}
private static void Verify(XmlNode parent, XmlNode child, XmlNode newChild)
{
Assert.Equal(child.ParentNode, parent);
Assert.Equal(newChild.ParentNode, parent);
}
private static XmlNode CreateNode(XmlDocument doc, XmlNodeType nodeType)
{
Assert.NotNull(doc);
switch (nodeType)
{
case XmlNodeType.CDATA:
return doc.CreateCDataSection(@"< & <tag> < ! > & </tag> ");
case XmlNodeType.Comment:
return doc.CreateComment(@"comment");
case XmlNodeType.Element:
return doc.CreateElement("E");
case XmlNodeType.Text:
return doc.CreateTextNode("text");
case XmlNodeType.Whitespace:
return doc.CreateWhitespace(@" ");
case XmlNodeType.SignificantWhitespace:
return doc.CreateSignificantWhitespace(" ");
default:
throw new ArgumentException("Wrong XmlNodeType: '" + nodeType + "'");
}
}
private static XmlNode InsertBefore(XmlNode parent, XmlNode newChild, XmlNode refChild)
{
Assert.NotNull(parent);
Assert.NotNull(newChild);
return parent.InsertBefore(newChild, refChild);
}
private static XmlNode InsertAfter(XmlNode parent, XmlNode newChild, XmlNode refChild)
{
Assert.NotNull(parent);
Assert.NotNull(newChild);
return parent.InsertAfter(newChild, refChild);
}
private static Func<XmlNode, XmlNode, XmlNode, XmlNode> CreateInsertBeforeOrAfter(InsertType insertType)
{
switch (insertType)
{
case InsertType.InsertBefore:
return InsertBefore;
case InsertType.InsertAfter:
return InsertAfter;
}
throw new ArgumentException("Unknown type");
}
}
}
| |
// Triangulator source code by Nick Gravelyn.
// https://github.com/nickgravelyn/Triangulator
//
// Licensed under the MIT license.
// https://github.com/nickgravelyn/Triangulator/blob/master/LICENSE
//
using System.Collections.Generic;
using System.Diagnostics;
/* Unmerged change from project 'Gorgon.Renderers.Gorgon2D (net5.0-windows)'
Before:
using System.Text;
After:
using System.Numerics;
using System.Text;
*/
using System.Numerics;
using System.Text;
using Gorgon.Diagnostics;
using Gorgon.Math;
using Gorgon.Renderers
/* Unmerged change from project 'Gorgon.Renderers.Gorgon2D (net5.0-windows)'
Before:
using System.Numerics;
After:
using Gorgon.Renderers.Geometry;
*/
.Geometry;
using DX = SharpDX;
namespace GorgonTriangulator
{
/// <summary>
/// A class exposing methods for triangulating 2D polygons. This is the sole public
/// class in the entire library; all other classes/structures are intended as internal-only
/// objects used only to assist in triangulation.
///
/// This class makes use of the DEBUG conditional and produces quite verbose output when built
/// in Debug mode. This is quite useful for debugging purposes, but can slow the process down
/// quite a bit. For optimal performance, build the library in Release mode.
///
/// The triangulation is also not optimized for garbage sensitive processing. The point of the
/// library is a robust, yet simple, system for triangulating 2D shapes. It is intended to be
/// used as part of your content pipeline or at load-time. It is not something you want to be
/// using each and every frame unless you really don't care about garbage.
/// </summary>
internal class Triangulator
{
#region Fields
private readonly IndexableCyclicalLinkedList<Vertex> _polygonVertices = new();
private readonly IndexableCyclicalLinkedList<Vertex> _earVertices = new();
private readonly CyclicalList<Vertex> _convexVertices = new();
private readonly CyclicalList<Vertex> _reflexVertices = new();
private readonly List<Triangle> _triangles = new();
// The log used for debug messages.
private readonly IGorgonLog _log;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="Triangulator"/> class.
/// </summary>
/// <param name="log">The log used for debug messages..</param>
public Triangulator(IGorgonLog log) => _log = log ?? GorgonLog.NullLog;
#endregion
#region Public Methods
/// <summary>
/// Triangulates a 2D polygon produced the indexes required to render the points as a triangle list.
/// </summary>
/// <param name="inputVertices">The polygon vertices in counter-clockwise winding order.</param>
/// <param name="desiredWindingOrder">The desired output winding order.</param>
/// <returns>A tuple containing a list of vertices, indices and bounds.</returns>
public (int[] indices, DX.RectangleF bounds) Triangulate(Gorgon2DVertex[] inputVertices, WindingOrder desiredWindingOrder)
{
Log("\nBeginning triangulation...");
//make sure we have our vertices wound properly
if (DetermineWindingOrder(inputVertices) == WindingOrder.Clockwise)
{
ReverseWindingOrder(inputVertices);
}
//clear all of the lists
_triangles.Clear();
_polygonVertices.Clear();
_earVertices.Clear();
_convexVertices.Clear();
_reflexVertices.Clear();
//generate the cyclical list of vertices in the polygon
for (int i = 0; i < inputVertices.Length; i++)
{
_polygonVertices.AddLast(new Vertex(new Vector2(inputVertices[i].Position.X, inputVertices[i].Position.Y), i));
}
//categorize all of the vertices as convex, reflex, and ear
FindConvexAndReflexVertices();
FindEarVertices();
//clip all the ear vertices
while (_polygonVertices.Count > 3 && _earVertices.Count > 0)
{
ClipNextEar();
}
//if there are still three points, use that for the last triangle
if (_polygonVertices.Count == 3)
{
_triangles.Add(new Triangle(
_polygonVertices[0].Value,
_polygonVertices[1].Value,
_polygonVertices[2].Value));
}
//add all of the triangle indices to the output array
int[] outputIndices = new int[_triangles.Count * 3];
//move the if statement out of the loop to prevent all the
//redundant comparisons
if (desiredWindingOrder == WindingOrder.CounterClockwise)
{
for (int i = 0; i < _triangles.Count; i++)
{
Triangle triangle = _triangles[i];
outputIndices[(i * 3)] = triangle.A.Index;
outputIndices[(i * 3) + 1] = triangle.B.Index;
outputIndices[(i * 3) + 2] = triangle.C.Index;
}
}
else
{
for (int i = 0; i < _triangles.Count; i++)
{
Triangle triangle = _triangles[i];
outputIndices[(i * 3)] = triangle.C.Index;
outputIndices[(i * 3) + 1] = triangle.B.Index;
outputIndices[(i * 3) + 2] = triangle.A.Index;
}
}
var minMax = new DX.RectangleF();
// Calculate bounds.
for (int i = 0; i < inputVertices.Length; ++i)
{
ref Vector4 pos = ref inputVertices[i].Position;
minMax.Left = minMax.Left.Min(pos.X);
minMax.Top = minMax.Top.Min(pos.Y);
minMax.Right = minMax.Right.Max(pos.X);
minMax.Bottom = minMax.Bottom.Max(pos.Y);
}
return (outputIndices, minMax);
}
/// <summary>
/// Ensures that a set of vertices are wound in a particular order, reversing them if necessary.
/// </summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <param name="windingOrder">The desired winding order.</param>
/// <returns>A new set of vertices if the winding order didn't match; otherwise the original set.</returns>
public void EnsureWindingOrder(Gorgon2DVertex[] vertices, WindingOrder windingOrder)
{
Log("\nEnsuring winding order of {0}...", windingOrder);
if (DetermineWindingOrder(vertices) != windingOrder)
{
Log("Reversing vertices...");
ReverseWindingOrder(vertices);
}
else
{
Log("No reversal needed.");
}
}
/// <summary>
/// Reverses the winding order for a set of vertices.
/// </summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <returns>The new vertices for the polygon with the opposite winding order.</returns>
public void ReverseWindingOrder(Gorgon2DVertex[] vertices)
{
Log("\nReversing winding order...");
#if DEBUG
var vString = new StringBuilder();
foreach (Gorgon2DVertex v in vertices)
{
vString.Append($"{v.Position}, ");
}
Log("Original Vertices: {0}", vString);
#endif
int end = vertices.Length - 1;
int start = 0;
while (end > start)
{
Gorgon2DVertex temp = vertices[end];
vertices[end] = vertices[start];
vertices[start] = temp;
--end;
++start;
}
#if DEBUG
vString = new StringBuilder();
foreach (Gorgon2DVertex v in vertices)
{
vString.Append($"{v.Position}, ");
}
Log("New Vertices After Reversal: {0}\n", vString);
#endif
}
/// <summary>
/// Determines the winding order of a polygon given a set of vertices.
/// </summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <returns>The calculated winding order of the polygon.</returns>
public WindingOrder DetermineWindingOrder(Gorgon2DVertex[] vertices)
{
int clockWiseCount = 0;
int counterClockWiseCount = 0;
Vector4 p1 = vertices[0].Position;
for (int i = 1; i < vertices.Length; i++)
{
Vector4 p2 = vertices[i].Position;
Vector4 p3 = vertices[(i + 1) % vertices.Length].Position;
var e1 = Vector4.Subtract(p1, p2);
var e2 = Vector4.Subtract(p3, p2);
if ((e1.X * e2.Y) - (e1.Y * e2.X) >= 0)
{
clockWiseCount++;
}
else
{
counterClockWiseCount++;
}
p1 = p2;
}
return (clockWiseCount > counterClockWiseCount)
? WindingOrder.Clockwise
: WindingOrder.CounterClockwise;
}
private void ClipNextEar()
{
//find the triangle
Vertex ear = _earVertices[0].Value;
Vertex prev = _polygonVertices[_polygonVertices.IndexOf(ear) - 1].Value;
Vertex next = _polygonVertices[_polygonVertices.IndexOf(ear) + 1].Value;
_triangles.Add(new Triangle(ear, next, prev));
//remove the ear from the shape
_earVertices.RemoveAt(0);
_polygonVertices.RemoveAt(_polygonVertices.IndexOf(ear));
Log("\nRemoved Ear: {0}", ear);
//validate the neighboring vertices
ValidateAdjacentVertex(prev);
ValidateAdjacentVertex(next);
//write out the states of each of the lists
#if DEBUG
var rString = new StringBuilder();
foreach (Vertex v in _reflexVertices)
{
rString.Append($"{v.Index}, ");
}
Log("Reflex Vertices: {0}", rString);
var cString = new StringBuilder();
foreach (Vertex v in _convexVertices)
{
cString.Append($"{v.Index}, ");
}
Log("Convex Vertices: {0}", cString);
var eString = new StringBuilder();
foreach (Vertex v in _earVertices)
{
eString.Append($"{v.Index}, ");
}
Log("Ear Vertices: {0}", eString);
#endif
}
private void ValidateAdjacentVertex(Vertex vertex)
{
Log("Validating: {0}...", vertex);
if (_reflexVertices.Contains(vertex))
{
if (IsConvex(vertex))
{
_reflexVertices.Remove(vertex);
_convexVertices.Add(vertex);
Log("Vertex: {0} now convex", vertex);
}
else
{
Log("Vertex: {0} still reflex", vertex);
}
}
if (!_convexVertices.Contains(vertex))
{
return;
}
bool wasEar = _earVertices.Contains(vertex);
bool isEar = IsEar(vertex);
if (wasEar && !isEar)
{
_earVertices.Remove(vertex);
Log("Vertex: {0} no longer ear", vertex);
}
else if (!wasEar && isEar)
{
_earVertices.AddFirst(vertex);
Log("Vertex: {0} now ear", vertex);
}
else
{
Log("Vertex: {0} still ear", vertex);
}
}
private void FindConvexAndReflexVertices()
{
for (int i = 0; i < _polygonVertices.Count; i++)
{
Vertex v = _polygonVertices[i].Value;
if (IsConvex(v))
{
_convexVertices.Add(v);
Log("Convex: {0}", v);
}
else
{
_reflexVertices.Add(v);
Log("Reflex: {0}", v);
}
}
}
private void FindEarVertices()
{
for (int i = 0; i < _convexVertices.Count; i++)
{
Vertex c = _convexVertices[i];
if (!IsEar(c))
{
continue;
}
_earVertices.AddLast(c);
Log("Ear: {0}", c);
}
}
private bool IsEar(Vertex c)
{
Vertex p = _polygonVertices[_polygonVertices.IndexOf(c) - 1].Value;
Vertex n = _polygonVertices[_polygonVertices.IndexOf(c) + 1].Value;
Log("Testing vertex {0} as ear with triangle {1}, {0}, {2}...", c, p, n);
foreach (Vertex t in _reflexVertices)
{
if (t.Equals(p) || t.Equals(c) || t.Equals(n))
{
continue;
}
if (!Triangle.ContainsPoint(p, c, n, t))
{
continue;
}
Log("\tTriangle contains vertex {0}...", t);
return false;
}
return true;
}
private bool IsConvex(Vertex c)
{
Vertex p = _polygonVertices[_polygonVertices.IndexOf(c) - 1].Value;
Vertex n = _polygonVertices[_polygonVertices.IndexOf(c) + 1].Value;
var d1 = Vector2.Normalize(c.Position - p.Position);
var d2 = Vector2.Normalize(n.Position - c.Position);
var n2 = new Vector2(-d2.Y, d2.X);
return (Vector2.Dot(d1, n2) <= 0f);
}
[Conditional("DEBUG")]
private void Log(string format, params object[] parameters)
{
if (_log == GorgonLog.NullLog)
{
return;
}
_log?.Print(format, LoggingLevel.Verbose, parameters);
}
#endregion
}
/// <summary>
/// Specifies a desired winding order for the shape vertices.
/// </summary>
internal enum WindingOrder
{
/// <summary>
/// Clockwise winding for vertices.
/// </summary>
Clockwise,
/// <summary>
/// Counterclockwise winding for vertices.
/// </summary>
CounterClockwise
}
}
| |
using Prism.Properties;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
namespace Prism.Validation
{
/// <summary>
/// The BindableValidator class run validation rules of an entity, and stores a collection of errors of the properties that did not pass validation.
/// The validation is run on each property change or whenever the ValidateProperties method is called.
/// It also provides an indexer property, that uses the property names as keys and return the error list for the specified property.
/// </summary>
public class BindableValidator : INotifyPropertyChanged
{
private readonly INotifyPropertyChanged _entityToValidate;
private IDictionary<string, ReadOnlyCollection<string>> _errors = new Dictionary<string, ReadOnlyCollection<string>>();
/// <summary>
/// Represents a collection of empty error values.
/// </summary>
public static readonly ReadOnlyCollection<string> EmptyErrorsCollection = new ReadOnlyCollection<string>(new List<string>());
/// <summary>
/// Initializes a new instance of the BindableValidator class with the entity to validate.
/// </summary>
/// <param name="entityToValidate">The entity to validate</param>
/// <exception cref="ArgumentNullException">When <paramref name="entityToValidate"/> is <see langword="null" />.</exception>
public BindableValidator(INotifyPropertyChanged entityToValidate)
{
if (entityToValidate == null)
{
throw new ArgumentNullException(nameof(entityToValidate));
}
_entityToValidate = entityToValidate;
IsValidationEnabled = true;
}
/// <summary>
/// Multicast event for errors change notifications.
/// </summary>
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
/// <summary>
/// Multicast event for property change notifications.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Returns the errors of the property.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <returns>The errors of the property, if it has errors. Otherwise, the BindableValidator.EmptyErrorsCollection.</returns>
public ReadOnlyCollection<string> this[string propertyName]
{
get
{
ReadOnlyCollection<string> errors;
if (_errors.TryGetValue(propertyName, out errors))
return errors;
else
return EmptyErrorsCollection;
}
}
/// <summary>
/// Gets the list of errors per property.
/// </summary>
/// <value>
/// The dictionary of property names and errors collection pairs.
/// </value>
public IDictionary<string, ReadOnlyCollection<string>> Errors => _errors;
/// <summary>
/// Returns true if the Validation functionality is enabled. Otherwise, false.
/// </summary>
public bool IsValidationEnabled { get; set; }
/// <summary>
/// Returns a new ReadOnlyDictionary containing all the errors of the Entity, separated by property.
/// </summary>
/// <returns>
/// A ReadOnlyDictionary that contains a KeyValuePair for each property with errors.
/// Each KeyValuePair has a property name as the key, and the value is the collection of errors of that property.
/// </returns>
public ReadOnlyDictionary<string, ReadOnlyCollection<string>> GetAllErrors()
{
return new ReadOnlyDictionary<string, ReadOnlyCollection<string>>(_errors);
}
/// <summary>
/// Updates the errors collection of the entity, notifying if the errors collection has changed.
/// </summary>
/// <param name="entityErrors">The collection of errors for the entity.</param>
public void SetAllErrors(IDictionary<string, ReadOnlyCollection<string>> entityErrors)
{
if (entityErrors == null)
{
throw new ArgumentNullException(nameof(entityErrors));
}
_errors.Clear();
foreach (var item in entityErrors)
{
SetPropertyErrors(item.Key, item.Value);
}
OnPropertyChanged("Item[]");
OnErrorsChanged(string.Empty);
}
/// <summary>
/// Validates the property, based on the rules set in the property ValidationAttributes attributes.
/// It updates the errors collection with the new validation results (notifying if necessary).
/// </summary>
/// <param name="propertyName">The name of the property to validate.</param>
/// <returns>True if the property is valid. Otherwise, false.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="propertyName"/> is <see langword="null" /> or an empty string value.</exception>
/// <exception cref="ArgumentException">When the <paramref name="propertyName"/> parameter does not match any property name.</exception>
public bool ValidateProperty(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentNullException(nameof(propertyName));
}
var propertyInfo = _entityToValidate.GetType().GetRuntimeProperty(propertyName);
if (propertyInfo == null)
{
var errorString = Resources.InvalidPropertyNameException;
throw new ArgumentException(errorString, propertyName);
}
var propertyErrors = new List<string>();
bool isValid = TryValidateProperty(propertyInfo, propertyErrors);
bool errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors);
if (errorsChanged)
{
OnErrorsChanged(propertyName);
OnPropertyChanged(string.Format(CultureInfo.CurrentCulture, "Item[{0}]", propertyName));
}
return isValid;
}
/// <summary>
/// Validates all the properties decorated with the ValidationAttribute attribute.
/// It updates each property errors collection with the new validation results (notifying if necessary).
/// </summary>
/// <returns>True if the property is valid. Otherwise, false.</returns>
public bool ValidateProperties()
{
var propertiesWithChangedErrors = new List<string>();
// Get all the properties decorated with the ValidationAttribute attribute.
var propertiesToValidate = _entityToValidate.GetType()
.GetRuntimeProperties()
.Where(c => c.GetCustomAttributes(typeof(ValidationAttribute)).Any());
foreach (PropertyInfo propertyInfo in propertiesToValidate)
{
var propertyErrors = new List<string>();
TryValidateProperty(propertyInfo, propertyErrors);
// If the errors have changed, save the property name to notify the update at the end of this method.
bool errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors);
if (errorsChanged && !propertiesWithChangedErrors.Contains(propertyInfo.Name))
{
propertiesWithChangedErrors.Add(propertyInfo.Name);
}
}
// Notify each property whose set of errors has changed since the last validation.
foreach (string propertyName in propertiesWithChangedErrors)
{
OnErrorsChanged(propertyName);
OnPropertyChanged(string.Format(CultureInfo.CurrentCulture, "Item[{0}]", propertyName));
}
return _errors.Values.Count == 0;
}
/// <summary>
/// Performs a validation of a property, adding the results in the propertyErrors list.
/// </summary>
/// <param name="propertyInfo">The PropertyInfo of the property to validate</param>
/// <param name="propertyErrors">A list containing the current error messages of the property.</param>
/// <returns>True if the property is valid. Otherwise, false.</returns>
private bool TryValidateProperty(PropertyInfo propertyInfo, List<string> propertyErrors)
{
var results = new List<ValidationResult>();
var context = new ValidationContext(_entityToValidate) { MemberName = propertyInfo.Name };
var propertyValue = propertyInfo.GetValue(_entityToValidate);
// Validate the property
bool isValid = Validator.TryValidateProperty(propertyValue, context, results);
if (results.Any())
{
propertyErrors.AddRange(results.Select(c => c.ErrorMessage));
}
return isValid;
}
/// <summary>
/// Updates the errors collection of the property.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="propertyNewErrors">The new collection of property errors.</param>
/// <returns>True if the property errors have changed. Otherwise, false.</returns>
private bool SetPropertyErrors(string propertyName, IList<string> propertyNewErrors)
{
bool errorsChanged = false;
// If the property does not have errors, simply add them
if (!_errors.ContainsKey(propertyName))
{
if (propertyNewErrors.Any())
{
_errors.Add(propertyName, new ReadOnlyCollection<string>(propertyNewErrors));
errorsChanged = true;
}
}
else
{
// If the property has errors, check if the number of errors are different.
// If the number of errors is the same, check if there are new ones
if (propertyNewErrors.Count != _errors[propertyName].Count || _errors[propertyName].Intersect(propertyNewErrors).Count() != propertyNewErrors.Count())
{
if (propertyNewErrors.Any())
{
_errors[propertyName] = new ReadOnlyCollection<string>(propertyNewErrors);
}
else
{
_errors.Remove(propertyName);
}
errorsChanged = true;
}
}
return errorsChanged;
}
/// <summary>
/// Notifies listeners that a property value has changed.
/// </summary>
/// <param name="propertyName">Name of the property used to notify listeners.</param>
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Notifies listeners that the errors of a property have changed.
/// </summary>
/// <param name="propertyName">Name of the property used to notify listeners.</param>
private void OnErrorsChanged(string propertyName)
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class DiagnosticsTest : RemoteExecutorTestBase
{
[Fact]
public static void EventSource_ExistsWithCorrectId()
{
Type esType = typeof(HttpClient).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
Assert.NotNull(esType);
Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType));
Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType));
Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest"));
}
// Diagnostic tests are each invoked in their own process as they enable/disable
// process-wide EventSource-based tracing, and other tests in the same process
// could interfere with the tests, as well as the enabling of tracing interfering
// with those tests.
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
Guid requestGuid = Guid.Empty;
bool responseLogged = false;
Guid responseGuid = Guid.Empty;
bool exceptionLogged = false;
bool activityLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
exceptionLogged = true;
}
else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut"))
{
activityLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable( s => !s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
}
Assert.True(requestLogged, "Request was not logged.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
Assert.Equal(requestGuid, responseGuid);
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNoLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
Task response = client.GetAsync(url);
await Task.WhenAll(response, requestLines);
AssertNoHeadersAreInjected(requestLines.Result);
}).Wait();
}
Assert.False(requestLogged, "Request was logged while logging disabled.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled.");
WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled.");
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_HttpTracingEnabled_Succeeds()
{
RemoteInvoke(async () =>
{
using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose))
{
var events = new ConcurrentQueue<EventWrittenEventArgs>();
await listener.RunWithCallbackAsync(events.Enqueue, async () =>
{
// Exercise various code paths to get coverage of tracing
using (var client = new HttpClient())
{
// Do a get to a loopback server
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server),
client.GetAsync(url));
});
// Do a post to a remote server
byte[] expectedData = Enumerable.Range(0, 20000).Select(i => unchecked((byte)i)).ToArray();
HttpContent content = new ByteArrayContent(expectedData);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.RemoteEchoServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
// We don't validate receiving specific events, but rather that we do at least
// receive some events, and that enabling tracing doesn't cause other failures
// in processing.
Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages
Assert.InRange(events.Count, 1, int.MaxValue);
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionLogging()
{
RemoteInvoke(() =>
{
bool exceptionLogged = false;
bool responseLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledLogging()
{
RemoteInvoke(() =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
cancelLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
CancellationTokenSource tcs = new CancellationTokenSource();
Task request = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) =>
{
tcs.Cancel();
return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
});
Task response = client.GetAsync(url, tcs.Token);
await Assert.ThrowsAnyAsync<Exception>(() => Task.WhenAll(response, request));
}).Wait();
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => cancelLogged, TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceActivityLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
bool exceptionLogged = false;
Activity parentActivity = new Activity("parent");
parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString());
parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString());
parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request
parentActivity.Start();
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
Assert.True(Activity.Current.Duration != TimeSpan.Zero);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
Task response = client.GetAsync(url);
await Task.WhenAll(response, requestLines);
AssertHeadersAreInjected(requestLines.Result, parentActivity);
}).Wait();
}
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
Assert.False(requestLogged, "Request was logged when Activity logging was enabled.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
{
RemoteInvoke(() =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")){activityStartLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) {activityStopLogged = true;}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable((s, r, _) =>
{
if (s.StartsWith("System.Net.Http.HttpRequestOut"))
{
var request = r as HttpRequestMessage;
if (request != null)
return !request.RequestUri.Equals(Configuration.Http.RemoteEchoServer);
}
return true;
});
using (var client = new HttpClient())
{
var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
}
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled.");
// Poll with a timeout since logging response is not synchronized with returning a response.
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionActivityLogging()
{
RemoteInvoke(() =>
{
bool exceptionLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
activityStopLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging()
{
RemoteInvoke(() =>
{
bool exceptionLogged = false;
bool activityLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception"));
using (var client = new HttpClient())
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1),
"Exception was not logged within 1 second timeout.");
Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging()
{
RemoteInvoke(() =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(Activity.Current);
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut"));
using (var client = new HttpClient())
{
var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
{
RemoteInvoke(() =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
cancelLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
CancellationTokenSource tcs = new CancellationTokenSource();
Task request = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) =>
{
tcs.Cancel();
return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
});
Task response = client.GetAsync(url, tcs.Token);
await Assert.ThrowsAnyAsync<Exception>(() => Task.WhenAll(response, request));
}).Wait();
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => cancelLogged, TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}).Dispose();
}
private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName)
{
Type t = obj.GetType();
PropertyInfo p = t.GetRuntimeProperty(propertyName);
object propertyValue = p.GetValue(obj);
Assert.NotNull(propertyValue);
Assert.IsAssignableFrom<T>(propertyValue);
return (T)propertyValue;
}
private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin doesn't time out.
Assert.True(SpinWait.SpinUntil(p, timeout), message);
}
private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin times out.
Assert.False(SpinWait.SpinUntil(p, timeout), message);
}
private void AssertHeadersAreInjected(List<string> requestLines, Activity parent)
{
string requestId = null;
var correlationContext = new List<NameValueHeaderValue>();
foreach (var line in requestLines)
{
if (line.StartsWith("Request-Id"))
{
requestId = line.Substring("Request-Id".Length).Trim(' ', ':');
}
if (line.StartsWith("Correlation-Context"))
{
var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':');
foreach (var kvp in corrCtxString.Split(','))
{
correlationContext.Add(NameValueHeaderValue.Parse(kvp));
}
}
}
Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled");
Assert.True(requestId.StartsWith(parent.Id));
Assert.NotEqual(parent.Id, requestId);
List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList();
Assert.Equal(baggage.Count, correlationContext.Count);
foreach (var kvp in baggage)
{
Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext);
}
}
private void AssertNoHeadersAreInjected(List<string> requestLines)
{
foreach (var line in requestLines)
{
Assert.False(line.StartsWith("Request-Id"),
"Request-Id header was injected when instrumentation was disabled");
Assert.False(line.StartsWith("Correlation-Context"),
"Correlation-Context header was injected when instrumentation was disabled");
}
}
}
}
| |
/*
Copyright (c) 2010 by Genstein
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Xml;
using System.Globalization;
namespace Trizbort
{
/// <summary>
/// Wrapper around an XmlElement for ease of access.
/// </summary>
internal class XmlElementReader
{
public XmlElementReader()
{
}
public XmlElementReader(XmlElement element)
{
Element = element;
}
public XmlElementReader this[string localName]
{
get
{
if (Element != null)
{
foreach (var node in Element.ChildNodes)
{
if (!(node is XmlElement))
continue;
var element = (XmlElement)node;
if (element.LocalName == localName)
{
return new XmlElementReader(element);
}
}
}
return new XmlElementReader();
}
}
public List<XmlElementReader> Children
{
get
{
if (m_children == null)
{
m_children = new List<XmlElementReader>();
if (Element != null)
{
foreach (var node in Element.ChildNodes)
{
if (!(node is XmlElement))
continue;
var element = (XmlElement)node;
m_children.Add(new XmlElementReader(element));
}
}
}
return m_children;
}
}
public string Name
{
get
{
if (Element != null)
{
return Element.LocalName;
}
return string.Empty;
}
}
public bool HasName(string value)
{
return StringComparer.InvariantCultureIgnoreCase.Compare(Name, value) == 0;
}
public string Text
{
get
{
if (Element != null)
{
return Element.InnerText;
}
return string.Empty;
}
}
public string ToText(string defaultValue)
{
var text = Text;
if (!string.IsNullOrEmpty(text))
{
return text;
}
return defaultValue;
}
public int ToInt()
{
return ToInt(0);
}
public int ToInt(int defaultValue)
{
int value;
if (int.TryParse(Text, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return value;
}
return defaultValue;
}
public float ToFloat()
{
return ToFloat(0);
}
public float ToFloat(float defaultValue)
{
float value;
if (float.TryParse(Text, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return value;
}
return defaultValue;
}
public bool ToBool()
{
return ToBool(false);
}
public bool ToBool(bool defaultValue)
{
if (StringComparer.InvariantCultureIgnoreCase.Compare(Text, XmlScribe.Yes) == 0)
{
return true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Compare(Text, XmlScribe.No) == 0)
{
return false;
}
return defaultValue;
}
public Color ToColor(Color defaultValue)
{
try
{
return ColorTranslator.FromHtml(Text);
}
catch (Exception)
{
return defaultValue;
}
}
public CompassPoint ToCompassPoint(CompassPoint defaultValue)
{
CompassPoint point;
if (CompassPointHelper.FromName(Text, out point))
{
return point;
}
return defaultValue;
}
public XmlAttributeReader Attribute(string localName)
{
if (Element != null)
{
foreach (XmlAttribute attribute in Element.Attributes)
{
if (StringComparer.InvariantCultureIgnoreCase.Compare(attribute.LocalName, localName) == 0)
{
return new XmlAttributeReader(attribute.Value);
}
}
}
return new XmlAttributeReader(string.Empty);
}
public XmlElement Element
{
get;
private set;
}
private List<XmlElementReader> m_children;
}
}
| |
namespace Data.Repository
{
using Data.Repository.Context;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
/// <summary>
/// A generic class for a basic Db relation operations.
/// </summary>
public class BaseRepository<T> : IRepository<T> where T : class
{
#region Properties
protected AppDbContext Db { get; set; }
protected bool disposed { get; set; }
#endregion Properties
#region Constructors
/// <summary>
/// The constructor requires an open DataContext to work with.
/// </summary>
/// <param name="context">An optional open DataContext.</param>
public BaseRepository(AppDbContext context = null)
{
Db = context ?? new AppDbContext();
disposed = false;
}
#endregion Constructors
#region Methods
/// <summary>
/// Returns a single object with a primary key of the provided id.
/// </summary>
/// <param name="id">The primary key of the object to fetch.</param>
/// <returns>A single object with the provided primary key or null</returns>
public virtual T Get(int id)
{
return Db.Set<T>().Find(id);
}
/// <summary>
/// An overloaded Get() to retrieve a specific portion of the relation.
/// </summary>
/// <param name="id">The primary key of the object to fetch.</param>
/// <param name="numOfRecords">The page size.</param>
/// <param name="pageNumber">The page number.</param>
/// <returns>An ICollection of objects in range specified according to the arguments.</returns>
public virtual ICollection<T> Get(int pageNumber, int numOfRecords, Expression<Func<T, int>> orderBy)
{
int recordstoPass = (pageNumber - 1) * numOfRecords;
return Db.Set<T>().OrderBy(orderBy).Skip(recordstoPass).Take(numOfRecords).ToList();
}
/// <summary>
/// Returns a single object with a primary key of the provided id.
/// </summary>
/// <param name="id">The primary key of the object to fetch.</param>
/// <returns>A single object with the provided primary key or null.</returns>
public virtual async Task<T> GetAsync(int id)
{
return await Db.Set<T>().FindAsync(id);
}
/// <summary>
/// An overloaded GetAsync() to retrieve a specific portion of the relation.
/// </summary>
/// <param name="id">The primary key of the object to fetch</param>
/// <param name="numOfRecords">The page size.</param>
/// <param name="pageNumber">The page number.</param>
/// <returns>An ICollection of objects in range specified according to the arguments.</returns>
public virtual async Task<ICollection<T>> GetAsync(int pageNumber, int numOfRecords, Expression<Func<T, int>> orderBy)
{
int recordstoPass = (pageNumber - 1) * numOfRecords;
return await Db.Set<T>().OrderBy(orderBy).Skip(recordstoPass).Take(numOfRecords).ToListAsync();
}
/// <summary>
/// Gets a collection of all objects in the database.
/// </summary>
/// <returns>An ICollection of every object in the database.</returns>
public virtual ICollection<T> GetAll()
{
return Db.Set<T>().ToList();
}
/// <summary>
/// Gets a collection of all objects in the database.
/// </summary>
/// <returns>An ICollection of every object in the database.</returns>
public virtual async Task<ICollection<T>> GetAllAsync()
{
return await Db.Set<T>().ToListAsync();
}
/// <summary>
/// Returns a single object which matches the provided expression.
/// </summary>
/// <param name="filter">A Linq expression filter to find a single result.</param>
/// <returns>A single object which matches the expression filter.
/// If more than one object is found or if zero are found, null is returned.</returns>
public virtual T Find(Expression<Func<T, bool>> filter)
{
IQueryable<T> query = Db.Set<T>();
return Db.Set<T>().SingleOrDefault(filter);
}
/// <summary>
/// Returns a single object which matches the provided expression.
/// </summary>
/// <param name="filter">A Linq expression filter to find a single result.</param>
/// <returns>A single object which matches the expression filter.
/// If more than one object is found or if zero are found, null is returned.</returns>
public virtual async Task<T> FindAsync(Expression<Func<T, bool>> filter)
{
return await Db.Set<T>().SingleOrDefaultAsync(filter);
}
/// <summary>
/// Returns a collection of objects which match the provided expression.
/// </summary>
/// <param name="filter">A linq expression filter to find one or more results.</param>
/// <returns>An ICollection of object which match the expression filter.</returns>
public virtual ICollection<T> FindAll(Expression<Func<T, bool>> filter)
{
return Db.Set<T>().Where(filter).ToList();
}
/// <summary>
/// Returns a collection of objects which match the provided expression.
/// </summary>
/// <param name="filter">A linq expression filter to find one or more results.</param>
/// <returns>An ICollection of object which match the expression filter.</returns>
public virtual async Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> filter)
{
return await Db.Set<T>().Where(filter).ToListAsync();
}
/// <summary>
/// Inserts a single object to the database and commits the change.
/// </summary>
/// <param name="e">The object to insert.</param>
/// <returns>The resulting object including its primary key after the insert.</returns>
public virtual T Add(T e)
{
Db.Set<T>().Add(e);
Db.SaveChanges();
return e;
}
/// <summary>
/// Inserts a single object to the database and commits the change.
/// </summary>
/// <param name="e">The object to insert.</param>
/// <returns>The resulting object including its primary key after the insert.</returns>
public virtual async Task<T> AddAsync(T e)
{
Db.Set<T>().Add(e);
await Db.SaveChangesAsync();
return e;
}
/// <summary>
/// Inserts a collection of objects into the database and commits the changes.
/// </summary>
/// <param name="eList">An IEnumerable list of objects to insert.</param>
/// <returns>The IEnumerable resulting list of inserted objects including the primary keys.</returns>
public virtual IEnumerable<T> AddAll(IEnumerable<T> eList)
{
Db.Set<T>().AddRange(eList);
Db.SaveChanges();
return eList;
}
/// <summary>
/// Inserts a collection of objects into the database and commits the changes.
/// </summary>
/// <param name="eList">An IEnumerable list of objects to insert.</param>
/// <returns>The IEnumerable resulting list of inserted objects including the primary keys.</returns>
public virtual async Task<IEnumerable<T>> AddAllAsync(IEnumerable<T> eList)
{
Db.Set<T>().AddRange(eList);
await Db.SaveChangesAsync();
return eList;
}
/// <summary>
/// Updates a single object based on the provided primary key and commits the change.
/// </summary>
/// <param name="updated">The updated object to apply to the database.</param>
/// <param name="key">The primary key of the object to update.</param>
/// <returns>The resulting updated object.</returns>
public virtual T Update(T updated, int key)
{
if (updated == null)
return null;
T existing = Db.Set<T>().Find(key);
if (existing != null)
{
Db.Entry(existing).CurrentValues.SetValues(updated);
Db.SaveChanges();
}
return existing;
}
/// <summary>
/// Updates a single object based on the provided primary key and commits the change.
/// </summary>
/// <param name="updated">The updated object to apply to the database.</param>
/// <param name="key">The primary key of the object to update.</param>
/// <returns>The resulting updated object.</returns>
public virtual async Task<T> UpdateAsync(T updated, int key)
{
if (updated == null)
return null;
T existing = await Db.Set<T>().FindAsync(key);
if (existing != null)
{
Db.Entry(existing).CurrentValues.SetValues(updated);
await Db.SaveChangesAsync();
}
return existing;
}
/// <summary>
/// Deletes a single object from the database and commits the change.
/// </summary>
/// <param name="e">The object to delete.</param>
/// <returns>The number of effected objects.</returns>
public virtual int Delete(T e)
{
Db.Set<T>().Remove(e);
return Db.SaveChanges();
}
/// <summary>
/// Deletes a single object from the database and commits the change.
/// </summary>
/// <param name="e">The object to delete.</param>
/// <returns>The number of effected objects.</returns>
public virtual async Task<int> DeleteAsync(T e)
{
Db.Set<T>().Remove(e);
return await Db.SaveChangesAsync();
}
/// <summary>
/// Gets the count of the number of objects in the database.
/// </summary>
/// <returns>The count of the number of objects.</returns>
public virtual int Count()
{
return Db.Set<T>().Count();
}
/// <summary>
/// Gets the count of the number of objects in the database.
/// </summary>
/// <returns>The count of the number of objects.</returns>
public virtual async Task<int> CountAsync()
{
return await Db.Set<T>().CountAsync();
}
#endregion Methods
#region IDisposable Implementation
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
Db.Dispose();
}
disposed = true;
}
#endregion IDisposable Implementation
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.WebEncoders.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public class HtmlHelperCheckBoxTest
{
[Fact]
public void CheckBoxOverridesCalculatedValuesWithValuesFromHtmlAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property3]]"" " +
@"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act
var html = helper.CheckBox("Property3",
isChecked: null,
htmlAttributes: new { @checked = "checked", value = "false" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxExplicitParametersOverrideDictionary_ForValueInModel()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property3]]"" " +
@"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act
var html = helper.CheckBox("Property3",
isChecked: true,
htmlAttributes: new { @checked = "unchecked", value = "false" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxExplicitParametersOverrideDictionary_ForNullModel()
{
// Arrange
var expected = @"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[foo]]"" name=""HtmlEncode[[foo]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[false]]"" />" +
@"<input name=""HtmlEncode[[foo]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var html = helper.CheckBox("foo",
isChecked: true,
htmlAttributes: new { @checked = "unchecked", value = "false" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxWithInvalidBooleanThrows()
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act & Assert
var ex = Assert.Throws<FormatException>(
() => helper.CheckBox("Property2", isChecked: null, htmlAttributes: null));
Assert.Contains("Boolean", ex.Message);
}
[Fact]
public void CheckBoxWithNullExpressionThrows()
{
// Arrange
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false);
// Act & Assert
ExceptionAssert.ThrowsArgument(
() => helper.CheckBox(null, isChecked: true, htmlAttributes: null),
"expression",
expected);
}
[Fact]
public void CheckBoxWithNullExpression_DoesNotThrow_WithNameAttribute()
{
// Arrange
var expected = @"<input class=""HtmlEncode[[some-class]]"" name=""HtmlEncode[[-expression-]]"" " +
@"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[-expression-]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false);
helper.ViewContext.ClientValidationEnabled = false;
var attributes = new Dictionary<string, object>
{
{ "class", "some-class"},
{ "name", "-expression-" },
};
// Act
var html = helper.CheckBox(null, isChecked: false, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxCheckedWithOnlyName_GeneratesExpectedValue()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBox_WithCanRenderAtEndOfFormSet_DoesNotGenerateInlineHiddenTag()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.FormContext.CanRenderAtEndOfForm = true;
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);
// Assert
Assert.True(helper.ViewContext.FormContext.HasEndOfFormContent);
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
var writer = new StringWriter();
var hiddenTag = Assert.Single(helper.ViewContext.FormContext.EndOfFormContent);
hiddenTag.WriteTo(writer, new HtmlTestEncoder());
Assert.Equal("<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
writer.ToString());
}
[Fact]
public void CheckBox_WithHiddenInputRenderModeNone_DoesNotGenerateHiddenInput()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.CheckBoxHiddenInputRenderMode = CheckBoxHiddenInputRenderMode.None;
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);
// Assert
Assert.False(helper.ViewContext.FormContext.HasEndOfFormContent);
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBox_WithHiddenInputRenderModeInline_GeneratesHiddenInput()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.FormContext.CanRenderAtEndOfForm = true;
helper.ViewContext.CheckBoxHiddenInputRenderMode = CheckBoxHiddenInputRenderMode.Inline;
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBox_WithHiddenInputRenderModeEndOfForm_GeneratesHiddenInput()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.FormContext.CanRenderAtEndOfForm = true;
helper.ViewContext.CheckBoxHiddenInputRenderMode = CheckBoxHiddenInputRenderMode.EndOfForm;
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);
// Assert
Assert.True(helper.ViewContext.FormContext.HasEndOfFormContent);
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
var writer = new StringWriter();
var hiddenTag = Assert.Single(helper.ViewContext.FormContext.EndOfFormContent);
hiddenTag.WriteTo(writer, new HtmlTestEncoder());
Assert.Equal("<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
writer.ToString());
}
[Fact]
public void CheckBox_WithHiddenInputRenderModeEndOfForm_WithCanRenderAtEndOfFormNotSet_GeneratesHiddenInput()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.FormContext.CanRenderAtEndOfForm = false;
helper.ViewContext.CheckBoxHiddenInputRenderMode = CheckBoxHiddenInputRenderMode.EndOfForm;
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);
// Assert
Assert.False(helper.ViewContext.FormContext.HasEndOfFormContent);
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxUsesAttemptedValueFromModelState()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxNotInTemplate_GetsValueFromViewDataDictionary()
{
// Arrange
var expected =
@"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel();
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_GetsValueFromViewDataDictionary()
{
// Arrange
var expected =
@"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Prefix_Property1]]"" " +
@"name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Remove(nameof(TestModel.Property1));
helper.ViewData["Prefix.Property1"] = true;
helper.ViewData.Model = new TestModel();
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxNotInTemplate_GetsValueFromPropertyOfViewDataEntry()
{
// Arrange
var expected =
@"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Prefix_Property1]]"" " +
@"name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Remove(nameof(TestModel.Property1));
helper.ViewData["Prefix"] = new TestModel { Property1 = true };
helper.ViewData.Model = new TestModel();
// Act
var html = helper.CheckBox("Prefix.Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_GetsValueFromPropertyOfViewDataEntry()
{
// Arrange
var expected =
@"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Prefix_Property1]]"" " +
@"name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Remove(nameof(TestModel.Property1));
helper.ViewData["Prefix"] = new TestModel { Property1 = true };
helper.ViewData.Model = new TestModel();
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxNotInTemplate_GetsModelValue_IfModelStateAndViewDataEmpty()
{
// Arrange
var expected =
@"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = true };
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_GetsModelValue_IfModelStateAndViewDataEmpty()
{
// Arrange
var expected =
@"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Prefix_Property1]]"" " +
@"name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = true };
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxNotInTemplate_NotChecked_IfPropertyIsNotFound()
{
// Arrange
var expected =
@"<input id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_NotChecked_IfPropertyIsNotFound()
{
// Arrange
var expected =
@"<input id=""HtmlEncode[[Prefix_Property1]]"" " +
@"name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxGeneratesUnobtrusiveValidationAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Name");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Name]]""" +
@" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());
// Act
var html = helper.CheckBox("Name", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxReplacesUnderscoresInHtmlAttributesWithDashes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" " +
@"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };
// Act
var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: htmlAttributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_ReplaceDotsInIdByDefaultWithUnderscores()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" " +
@"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var dictionary = new RouteValueDictionary(new { Property3 = "Property3Value" });
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var html = helper.CheckBox("Property1", isChecked: false, htmlAttributes: dictionary);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_ReplacesDotsInIdWithIdDotReplacement()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix!!!Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" " +
@"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var dictionary = new Dictionary<string, object> { { "Property3", "Property3Value" } };
var helper = DefaultTemplatesUtilities.GetHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel>(
model: null,
idAttributeDotReplacement: "!!!");
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var html = helper.CheckBox("Property1", isChecked: false, htmlAttributes: dictionary);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxInTemplate_WithEmptyExpression_GeneratesExpectedValue()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[MyPrefix]]"" name=""HtmlEncode[[MyPrefix]]"" " +
@"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false);
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
var attributes = new Dictionary<string, object>
{
{ "Property3", "Property3Value" },
{ "name", "-expression-" }, // overridden
};
// Act
var html = helper.CheckBox(string.Empty, isChecked: false, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxWithComplexExpressionsEvaluatesValuesInViewDataDictionary()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[ComplexProperty_Property1]]"" " +
@"name=""HtmlEncode[[ComplexProperty." +
@"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]""" +
@" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());
// Act
var html = helper.CheckBox("ComplexProperty.Property1", isChecked: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var viewData = GetTestModelViewData();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
viewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");
// Act
var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Theory]
[InlineData(false, "")]
[InlineData(true, "checked=\"HtmlEncode[[checked]]\" ")]
public void CheckBoxForWithNonNullContainer_UsesPropertyValue(bool value, string expectedChecked)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
// Mono issue - https://github.com/aspnet/External/issues/19
var expected =
$@"<input {{0}}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
expected = string.Format(CultureInfo.InvariantCulture, expected, expectedChecked);
var viewData = GetTestModelViewData();
viewData.Model = new TestModel
{
Property1 = value,
};
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
// Act
var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxForOverridesCalculatedParametersWithValuesFromHtmlAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property3");
var expected =
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
$@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property3]]"" name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act
var html = helper.CheckBoxFor(m => m.Property3, new { @checked = "checked", value = "false" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxForGeneratesUnobtrusiveValidationAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Name");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Name]]""" +
@" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var viewDataDictionary = new ViewDataDictionary<ModelWithValidation>(metadataProvider)
{
Model = new ModelWithValidation()
};
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewDataDictionary);
// Act
var html = helper.CheckBoxFor(m => m.Name, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Theory]
[InlineData("false", "")]
[InlineData("true", "checked=\"HtmlEncode[[checked]]\" ")]
public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected =
$@"<input {{0}}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
expected = string.Format(CultureInfo.InvariantCulture, expected, expectedChecked);
var viewData = GetTestModelViewData();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
viewData.ModelState.SetModelValue("Property1", new string[] { attemptedValue }, attemptedValue);
// Act
var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxFor_WithObjectAttribute_MapsUnderscoresInNamesToDashes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };
// Act
var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
var attributes = new Dictionary<string, object>
{
{ "Property3", "Property3Value" },
{ "name", "-expression-" }, // overridden
};
// Act
var html = helper.CheckBoxFor(m => m.Property1, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxForInTemplate_GeneratesExpectedValue()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" Property3=""HtmlEncode[[PropValue]]"" " +
@"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
var attributes = new Dictionary<string, object> { { "Property3", "PropValue" } };
// Act
var html = helper.CheckBoxFor(m => m.Property1, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void CheckBoxFor_WithComplexExpressions_DoesNotUseValuesFromViewDataDictionary()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[ComplexProperty_Property1]]"" name=""HtmlEncode[[ComplexProperty." +
@"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());
// Act
var html = helper.CheckBoxFor(m => m.ComplexProperty.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void Checkbox_UsesSpecifiedExpression()
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var checkboxResult = helper.CheckBox("Property1");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[checkbox]]\" value=\"HtmlEncode[[true]]\" />" +
"<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
HtmlContentUtilities.HtmlContentToString(checkboxResult));
}
[Fact]
public void Checkbox_UsesSpecifiedIsChecked()
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var checkboxResult = helper.CheckBox("Property1", isChecked: true);
// Assert
Assert.Equal(
"<input checked=\"HtmlEncode[[checked]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[checkbox]]\" value=\"HtmlEncode[[true]]\" />" +
"<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
HtmlContentUtilities.HtmlContentToString(checkboxResult));
}
[Fact]
public void Checkbox_UsesSpecifiedIsCheckedRegardlessOfExpressionValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = true };
// Act
var checkboxResult = helper.CheckBox("Property1", isChecked: false);
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[checkbox]]\" value=\"HtmlEncode[[true]]\" />" +
"<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
HtmlContentUtilities.HtmlContentToString(checkboxResult));
}
[Fact]
public void Checkbox_UsesSpecifiedHtmlAttributes()
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var checkboxResult = helper.CheckBox("Property1", htmlAttributes: new { attr = "value" });
// Assert
Assert.Equal(
"<input attr=\"HtmlEncode[[value]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[checkbox]]\" value=\"HtmlEncode[[true]]\" />" +
"<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
HtmlContentUtilities.HtmlContentToString(checkboxResult));
}
private static ViewDataDictionary<TestModel> GetTestModelViewData()
{
return new ViewDataDictionary<TestModel>(new EmptyModelMetadataProvider())
{
{ "Property1", true },
{ "Property2", "NotTrue" },
{ "Property3", false }
};
}
private static ViewDataDictionary<ModelWithValidation> GetModelWithValidationViewData()
{
var provider = TestModelMetadataProvider.CreateDefaultProvider();
var viewData = new ViewDataDictionary<ModelWithValidation>(provider)
{
{ "ComplexProperty.Property1", true },
{ "ComplexProperty.Property2", "NotTrue" },
{ "ComplexProperty.Property3", false }
};
viewData.Model = new ModelWithValidation();
return viewData;
}
private class TestModel
{
public bool Property1 { get; set; }
public bool Property2 { get; set; }
public bool Property3 { get; set; }
}
private class ModelWithValidation
{
[Required]
public bool Name { get; set; }
public TestModel ComplexProperty { get; set; }
}
}
}
| |
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)
{
Attributes.Add(WebmasterToolsNameTable.XmlAttributeType, null);
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)
{
Attributes.Add(WebmasterToolsNameTable.XmlAttributeType, type);
Attributes.Add(WebmasterToolsNameTable.XmlAttributeInUse, inUse);
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the Type attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Type
{
get { return Attributes[WebmasterToolsNameTable.XmlAttributeType] as string; }
set { Attributes[WebmasterToolsNameTable.XmlAttributeType] = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the In Use attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string InUse
{
get { return Attributes[WebmasterToolsNameTable.XmlAttributeInUse] as string; }
set { 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)
{
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)
{
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)
{
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)
{
Attributes.Add(WebmasterToolsNameTable.XmlAttributeLanguage, value);
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the Language attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string LanguageAttribute
{
get { return Attributes[WebmasterToolsNameTable.XmlAttributeLanguage] as string; }
set { 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)
{
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)
{
Attributes.Add(WebmasterToolsNameTable.XmlSubjectElement, value);
}
//////////////////////////////////////////////////////////////////////
/// <summary>convienience accessor for the Subject attribute</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string SubjectAttribute
{
get { return Attributes[WebmasterToolsNameTable.XmlSubjectElement] as string; }
set { 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)
{
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class PropertyBuilderTest11
{
private const string DynamicAssemblyName = "TestDynamicAssembly";
private const string DynamicModuleName = "TestDynamicModule";
private const string DynamicTypeName = "TestDynamicType";
private const string DynamicFieldName = "TestDynamicFieldA";
private const string DynamicPropertyName = "TestDynamicProperty";
private const string DynamicMethodName = "DynamicMethodA";
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private enum Colors
{
Red = 0,
Green = 1,
Blue = 2
}
private TypeBuilder GetTypeBuilder(TypeAttributes typeAtt)
{
AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = DynamicAssemblyName;
AssemblyBuilder myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(myAssemblyName,
AssemblyBuilderAccess.Run);
ModuleBuilder myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(myAssemblyBuilder,
DynamicModuleName);
return myModuleBuilder.DefineType(DynamicTypeName, typeAtt);
}
[Fact]
public void TestWithIntegerType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(int);
Type[] paramTypes = new Type[0];
int defaultValue = _generator.GetInt32();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is int);
Assert.Equal((int)actualValue, defaultValue);
}
[Fact]
public void TestWithBoolType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(bool);
Type[] paramTypes = new Type[0];
bool defaultValue = 0 == (_generator.GetInt32() & 1);
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is bool);
Assert.Equal((bool)actualValue, defaultValue);
}
[Fact]
public void TestWithSByteType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(SByte);
Type[] paramTypes = new Type[0];
SByte defaultValue = (SByte)(_generator.GetInt32() % (SByte.MaxValue + 1));
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is sbyte);
Assert.Equal((sbyte)actualValue, defaultValue);
}
[Fact]
public void TestWithShortType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(short);
Type[] paramTypes = new Type[0];
Int16 defaultValue = _generator.GetInt16();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is short);
Assert.Equal((short)actualValue, defaultValue);
}
[Fact]
public void TestWithLongType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(long);
Type[] paramTypes = new Type[0];
long defaultValue = _generator.GetInt64();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is long);
Assert.Equal((long)actualValue, defaultValue);
}
[Fact]
public void TestWithByteType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(byte);
Type[] paramTypes = new Type[0];
byte defaultValue = _generator.GetByte();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is byte);
Assert.Equal((byte)actualValue, defaultValue);
}
[Fact]
public void TestWithUShortType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(ushort);
Type[] paramTypes = new Type[0];
ushort defaultValue = (ushort)(_generator.GetInt32() % (ushort.MaxValue + 1));
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is ushort);
Assert.Equal((ushort)actualValue, defaultValue);
}
[Fact]
public void TestWithUIntType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(uint);
Type[] paramTypes = new Type[0];
uint defaultValue = (ushort)(_generator.GetInt64() % ((long)uint.MaxValue + 1));
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is uint);
Assert.Equal((uint)actualValue, defaultValue);
}
[Fact]
public void TestWithULongType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(ulong);
Type[] paramTypes = new Type[0];
ulong defaultValue = (ulong)long.MaxValue + (ulong)_generator.GetInt64();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is ulong);
Assert.Equal((ulong)actualValue, defaultValue);
}
[Fact]
public void TestWithFloatType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(float);
Type[] paramTypes = new Type[0];
float defaultValue = _generator.GetSingle();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is float);
Assert.Equal((float)actualValue, defaultValue);
}
[Fact]
public void TestWithDoubleType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(double);
Type[] paramTypes = new Type[0];
double defaultValue = _generator.GetDouble();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is double);
Assert.Equal((double)actualValue, defaultValue);
}
[Fact]
public void TestWithDateTimeType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(DateTime);
Type[] paramTypes = new Type[0];
DateTime defaultValue = DateTime.Now;
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is DateTime);
Assert.Equal((DateTime)actualValue, defaultValue);
}
[Fact]
public void TestWithCharType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(char);
Type[] paramTypes = new Type[0];
char defaultValue = _generator.GetChar();
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is char);
Assert.Equal((char)actualValue, defaultValue);
}
[Fact]
public void TestWithStringType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(string);
Type[] paramTypes = new Type[0];
string defaultValue = _generator.GetString(true, 0, 260);
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is string);
Assert.Equal((string)actualValue, defaultValue);
}
[Fact]
public void TestWithEnumType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(Colors);
Type[] paramTypes = new Type[0];
Colors defaultValue = (Colors)(_generator.GetInt32() % 3);
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.True(actualValue is Colors);
Assert.Equal((Colors)actualValue, defaultValue);
}
[Fact]
public void TestWithObjectType()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(object);
Type[] paramTypes = new Type[0];
object defaultValue = null;
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
Assert.Equal(defaultValue, (object)actualValue);
}
private object ExecutePosTest(object defaultValue, MethodAttributes getMethodAttr, Type returnType, Type[] paramTypes, BindingFlags bindingAttr)
{
TypeBuilder myTypeBuilder = GetTypeBuilder(TypeAttributes.Class | TypeAttributes.Public);
PropertyBuilder myPropertyBuilder = myTypeBuilder.DefineProperty(DynamicPropertyName,
PropertyAttributes.HasDefault,
returnType, null);
myPropertyBuilder.SetConstant(defaultValue);
// Define the "get" accessor method for DynamicPropertyName
MethodBuilder myMethodBuilder = myTypeBuilder.DefineMethod(DynamicMethodName,
getMethodAttr, returnType, paramTypes);
ILGenerator methodILGenerator = myMethodBuilder.GetILGenerator();
methodILGenerator.Emit(OpCodes.Ldarg_0);
methodILGenerator.Emit(OpCodes.Ret);
// Map the 'get' method created above to our PropertyBuilder
myPropertyBuilder.SetGetMethod(myMethodBuilder);
Type myType = myTypeBuilder.CreateTypeInfo().AsType();
PropertyInfo myProperty = myType.GetProperty(DynamicPropertyName, bindingAttr);
return myProperty.GetConstantValue();
}
[Fact]
public void NegTest1()
{
TypeBuilder myTypeBuilder;
PropertyBuilder myPropertyBuilder;
MethodBuilder myMethodBuilder;
Type[] paramTypes = new Type[]
{
typeof(int)
};
myTypeBuilder = GetTypeBuilder(TypeAttributes.Class | TypeAttributes.Public);
myPropertyBuilder = myTypeBuilder.DefineProperty(DynamicPropertyName,
PropertyAttributes.None,
typeof(int),
new Type[0]);
myMethodBuilder = myTypeBuilder.DefineMethod(DynamicMethodName,
MethodAttributes.Public,
CallingConventions.HasThis,
typeof(int),
paramTypes);
ILGenerator methodILGenerator = myMethodBuilder.GetILGenerator();
methodILGenerator.Emit(OpCodes.Ldarg_0);
methodILGenerator.Emit(OpCodes.Ldarg_1);
methodILGenerator.Emit(OpCodes.Ret);
Type myType = myTypeBuilder.CreateTypeInfo().AsType();
Assert.Throws<InvalidOperationException>(() => { myPropertyBuilder.SetConstant(1); });
}
[Fact]
public void PosTest18()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(object);
Type[] paramTypes = new Type[0];
object defaultValue = "TestCase";
object actualValue;
actualValue = ExecutePosTest(
defaultValue,
getMethodAttr,
returnType,
paramTypes,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Static);
}
[Fact]
public void NegTest3()
{
MethodAttributes getMethodAttr = MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
Type returnType = typeof(decimal);
Type[] paramTypes = new Type[0];
decimal defaultValue = (decimal)_generator.GetSingle();
object actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = ExecutePosTest(defaultValue, getMethodAttr, returnType, paramTypes, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for DisksOperations.
/// </summary>
public static partial class DisksOperationsExtensions
{
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
public static Disk CreateOrUpdate(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk)
{
return operations.CreateOrUpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> CreateOrUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
public static Disk Update(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk)
{
return operations.UpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> UpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static Disk Get(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.GetAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> GetAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse Delete(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.DeleteAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> DeleteAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<Disk> ListByResourceGroup(this IDisksOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListByResourceGroupAsync(this IDisksOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Disk> List(this IDisksOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListAsync(this IDisksOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
public static AccessUri GrantAccess(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData)
{
return operations.GrantAccessAsync(resourceGroupName, diskName, grantAccessData).GetAwaiter().GetResult();
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessUri> GrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse RevokeAccess(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.RevokeAccessAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> RevokeAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RevokeAccessWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
public static Disk BeginCreateOrUpdate(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> BeginCreateOrUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
public static Disk BeginUpdate(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk)
{
return operations.BeginUpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> BeginUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse BeginDelete(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.BeginDeleteAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginDeleteAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
public static AccessUri BeginGrantAccess(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData)
{
return operations.BeginGrantAccessAsync(resourceGroupName, diskName, grantAccessData).GetAwaiter().GetResult();
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessUri> BeginGrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse BeginRevokeAccess(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.BeginRevokeAccessAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginRevokeAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRevokeAccessWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Disk> ListByResourceGroupNext(this IDisksOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListByResourceGroupNextAsync(this IDisksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Disk> ListNext(this IDisksOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListNextAsync(this IDisksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using BuildIt.Logging;
using CommonServiceLocator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace BuildIt
{
/// <summary>
/// Helper class that simplifies writing log information.
/// </summary>
public static class LogHelper
{
private static ILoggerService logService;
private static bool hasLookedForLogService;
private static int wakeUpLock;
/// <summary>
/// Gets or sets the LogService instance.
/// </summary>
public static ILoggerService LogService
{
get
{
try
{
if (hasLookedForLogService)
{
return logService;
}
hasLookedForLogService = true;
if (!ServiceLocator.IsLocationProviderSet)
{
return null;
}
return logService ?? (LogService = ServiceLocator.Current.GetInstance<ILoggerService>());
}
catch (Exception ex)
{
Debug.WriteLine("Error retrieving ILogService implementation: " + ex.Message);
return null;
}
}
set
{
logService = value;
hasLookedForLogService = true;
}
}
/// <summary>
/// Gets or sets a simple log output handler.
/// </summary>
public static Action<string> LogOutput { get; set; }
private static Queue<ILogEntry> LogQueue { get; } = new Queue<ILogEntry>();
private static object LogQueueLock { get; } = new object();
private static AutoResetEvent LogWaiter { get; } = new AutoResetEvent(false);
/// <summary>
/// Logs information about an entity.
/// </summary>
/// <typeparam name="TEntity">The type of entity to write.</typeparam>
/// <param name="entity">The entity to write (serialized).</param>
/// <param name="caller">The name of the calling method (optional but defaults to the caller method name).</param>
[Obsolete("Use LogEntity()")]
public static void Log<TEntity>(this TEntity entity, [CallerMemberName] string caller = null)
{
// ReSharper disable once ExplicitCallerInfoArgument - backward compat
entity.LogEntity(null, null, null, LogLevel.Information, null, caller);
}
/// <summary>
/// Logs information about an entity.
/// </summary>
/// <typeparam name="TEntity">The type of entity to write.</typeparam>
/// <param name="entity">The entity to write (serialized).</param>
/// <param name="message">The message to be logged (optional).</param>
/// <param name="categories">The category to be logged (optional).</param>
/// <param name="metadata">The metadata to be logged (optional).</param>
/// <param name="level">The log level to log (optional but defaults to Information).</param>
/// <param name="assembly">The assembly name to be logged (optional). </param>
/// <param name="caller">The name of the calling method (optional but defaults to the caller method name).</param>
public static void LogEntity<TEntity>(this TEntity entity, string message = null, string[] categories = null, IDictionary<string, string> metadata = null, LogLevel level = LogLevel.Information, Assembly assembly = null, [CallerMemberName] string caller = null)
{
try
{
var entry = new TypedLogEntry<TEntity>(level, assembly?.GetName().Name, caller, entity, message, null, metadata, categories);
InternalWriteLog(entry);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
/// <summary>
/// Logs a message - for backward compatibility.
/// </summary>
/// <param name="message">The message to be logged (optional).</param>
/// <param name="caller">The name of the calling method (optional but defaults to the caller method name).</param>
[Obsolete("Use LogMessage()")]
public static void Log(this string message, [CallerMemberName] string caller = null)
{
// ReSharper disable once ExplicitCallerInfoArgument - backward compat
message.LogMessage(null, null, LogLevel.Information, null, caller);
}
/// <summary>
/// Logs a message.
/// </summary>
/// <param name="message">The message to be logged (optional).</param>
/// <param name="categories">The category to be logged (optional).</param>
/// <param name="metadata">The metadata to be logged (optional).</param>
/// <param name="level">The log level to log (optional but defaults to Information).</param>
/// <param name="assembly">The assembly name to be logged (optional). </param>
/// <param name="caller">The name of the calling method (optional but defaults to the caller method name).</param>
public static void LogMessage(this string message, string[] categories = null, IDictionary<string, string> metadata = null, LogLevel level = LogLevel.Information, Assembly assembly = null, [CallerMemberName] string caller = null)
{
try
{
var entry = new LogEntry(level, assembly?.GetName().Name, caller, message, null, metadata, categories);
InternalWriteLog(entry);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
/// <summary>
/// Logs an exception - for backward compatibility.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="message">The message (optional) to log.</param>
/// <param name="caller">The calling method.</param>
[Obsolete("Use LogError()")]
public static void LogException(this Exception exception, string message = null, [CallerMemberName] string caller = null)
{
// ReSharper disable once ExplicitCallerInfoArgument - backward compat
exception.LogError(message, null, null, LogLevel.Error, null, caller);
}
/// <summary>
/// Logs an exception.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="message">The message (optional) to log.</param>
/// <param name="categories">The category to be logged (optional).</param>
/// <param name="metadata">The metadata to be logged (optional).</param>
/// <param name="level">The log level to log (optional but defaults to Information).</param>
/// <param name="assembly">The assembly name to be logged (optional). </param>
/// <param name="caller">The calling method.</param>
public static void LogError(this Exception exception, string message = null, string[] categories = null, IDictionary<string, string> metadata = null, LogLevel level = LogLevel.Error, Assembly assembly = null, [CallerMemberName] string caller = null)
{
try
{
var entry = new LogEntry(level, assembly?.GetName().Name, caller, message, exception, metadata, categories);
InternalWriteLog(entry);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private static void InternalWriteLog(ILogEntry log)
{
try
{
if (log == null)
{
return;
}
if (LogService == null && LogOutput == null)
{
return;
}
lock (LogQueueLock)
{
LogQueue.Enqueue(log);
}
if (Interlocked.CompareExchange(ref wakeUpLock, 1, 0) == 0)
{
Task.Run(() => WakeUp());
}
else
{
LogWaiter.Set();
}
}
catch (Exception ext)
{
Debug.WriteLine(ext.Message);
}
}
private static async void WakeUp()
{
try
{
while (LogQueue.Count > 0)
{
ILogEntry entry;
lock (LogQueueLock)
{
entry = LogQueue.Dequeue();
}
if (entry == null)
{
return;
}
try
{
if (LogService?.Filter != null)
{
var ok = await LogService.Filter.IncludeLog(entry);
if (!ok)
{
continue;
}
}
LogOutput?.Invoke(entry.ToString());
if (LogService != null)
{
await LogService.Log(entry);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
if (LogQueue.Count == 0)
{
LogWaiter.WaitOne();
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
LogWaiter.Reset();
Interlocked.Exchange(ref wakeUpLock, 0);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using AntlrGrammarEditor.Fragments;
using AntlrGrammarEditor.Processors.ParserCompilation;
using AntlrGrammarEditor.Processors.ParserGeneration;
using AntlrGrammarEditor.Sources;
using AntlrGrammarEditor.WorkflowState;
using static AntlrGrammarEditor.Helpers;
namespace AntlrGrammarEditor.Processors.ParserCompilers
{
public abstract class ParserCompiler : StageProcessor
{
private const string CompilerHelperFileName = "AntlrCompileTest";
private const string TemplateLexerName = "__TemplateLexerName__";
private const string TemplateParserName = "__TemplateParserName__";
private const string RuntimesPath = "__RuntimesPath__";
private const string PackageName = "__PackageName__";
public const string RuntimesDirName = "AntlrRuntimes";
private static readonly Regex FragmentMarkRegexBegin;
private static readonly Regex FragmentMarkRegexEnd;
private static readonly Regex CSharpStopStringRegex = new (@"^Build FAILED\.$", RegexOptions.Compiled);
private readonly object _lockObject = new ();
private readonly OpenCloseMark _packageNameMark;
private readonly OpenCloseMark _parserPartMark;
private readonly OpenCloseMark _lexerIncludeMark;
private readonly OpenCloseMark _parserIncludeMark;
private readonly OpenCloseMark _caseInsensitiveMark;
private readonly Dictionary<string, FragmentMapper> _fragmentMappers = new ();
private readonly Dictionary<string, (Source, RuntimeFileInfo)> _runtimeFiles = new();
protected readonly GrammarCheckedState GrammarCheckedState;
protected readonly RuntimeInfo CurrentRuntimeInfo;
protected readonly ParserCompiledState Result;
protected readonly string RuntimeDir;
protected readonly string WorkingDirectory;
protected readonly string RuntimeLibraryPath;
protected readonly List<string> Buffer = new();
private bool _ignoreDiagnosis;
public string? RuntimeLibrary { get; set; }
public string GrammarName => Result.ParserGeneratedState.GrammarCheckedState.MainGrammarName;
public CaseInsensitiveType CaseInsensitiveType => Result.CaseInsensitiveType;
protected abstract Regex ParserCompilerMessageRegex { get; }
static ParserCompiler()
{
var mark = new OpenCloseMark(ParserGenerator.FragmentMarkWord, RuntimeInfo.Runtimes[Runtime.Java],
ParserGenerator.FragmentMarkSuffix);
var digitRegex = @"\d";
int digitsCount = ParserGenerator.FragmentMarkDigitsCount;
var digitsRegex = new StringBuilder(digitRegex.Length * digitsCount).Insert(0, digitRegex, digitsCount).ToString();
var digitsGroup = $"({digitsRegex})";
var fragmentRegexStringBegin = Regex.Escape($"{mark.StartCommentToken}{mark.Suffix}{mark.Name}") +
digitsGroup +
Regex.Escape(mark.EndCommentToken);
var fragmentRegexStringEnd = Regex.Escape($"{mark.StartCommentToken}{mark.Name}") +
digitsGroup +
Regex.Escape($"{mark.Suffix}{mark.EndCommentToken}");
FragmentMarkRegexBegin = new Regex(fragmentRegexStringBegin, RegexOptions.Compiled);
FragmentMarkRegexEnd = new Regex(fragmentRegexStringEnd, RegexOptions.Compiled);
}
protected ParserCompiler(ParserGeneratedState state, CaseInsensitiveType? caseInsensitiveType)
{
GrammarCheckedState = state.GrammarCheckedState;
var definedCaseInsensitiveType = caseInsensitiveType ??
state.GrammarCheckedState.CaseInsensitiveType ?? CaseInsensitiveType.None;
Result = new ParserCompiledState(state, definedCaseInsensitiveType, _runtimeFiles);
CurrentRuntimeInfo = Result.ParserGeneratedState.Runtime.GetRuntimeInfo();
string runtimeSource = state.Runtime.GetGeneralRuntimeName();
RuntimeDir = Path.Combine(RuntimesDirName, runtimeSource);
RuntimeLibraryPath = RuntimeLibrary ?? Path.Combine(RuntimeDir, CurrentRuntimeInfo.RuntimeLibrary);
WorkingDirectory = Path.Combine(ParserGenerator.HelperDirectoryName,
state.GrammarCheckedState.MainGrammarName, Result.ParserGeneratedState.Runtime.ToString());
_packageNameMark = new OpenCloseMark("PackageName", CurrentRuntimeInfo);
_parserPartMark = new OpenCloseMark("ParserPart", CurrentRuntimeInfo);
_lexerIncludeMark = new OpenCloseMark("LexerInclude", CurrentRuntimeInfo);
_parserIncludeMark = new OpenCloseMark("ParserInclude", CurrentRuntimeInfo);
_caseInsensitiveMark = new OpenCloseMark("AntlrCaseInsensitive", CurrentRuntimeInfo);
}
public ParserCompiledState Compile(CancellationToken cancellationToken = default)
{
Processor? processor = null;
try
{
_runtimeFiles.Clear();
PreprocessGeneratedFiles();
CopyHelperFiles();
string arguments = PrepareFilesAndGetArguments();
PrepareEntryPointCode();
lock (Buffer)
Buffer.Clear();
Result.Command = CurrentRuntimeInfo.RuntimeCompilerToolToolName + " " + arguments;
processor = new Processor(CurrentRuntimeInfo.RuntimeCompilerToolToolName, arguments, WorkingDirectory);
processor.CancellationToken = cancellationToken;
processor.ErrorDataReceived += ParserCompilation_ErrorDataReceived;
processor.OutputDataReceived += ParserCompilation_OutputDataReceived;
processor.Start();
Postprocess();
cancellationToken.ThrowIfCancellationRequested();
}
catch (Exception ex)
{
Result.AddDiagnosis(new ParserCompilationDiagnosis(ex));
}
finally
{
processor?.Dispose();
}
return Result;
}
protected abstract string PrepareFilesAndGetArguments();
protected virtual void Postprocess()
{
}
protected string CreateHelperFile(StringBuilder stringBuilder)
{
string compileTestFileName = CurrentRuntimeInfo.Runtime + CompilerHelperFileName + "." +
CurrentRuntimeInfo.Extensions[0];
File.WriteAllText(Path.Combine(WorkingDirectory, compileTestFileName), stringBuilder.ToString());
return compileTestFileName;
}
protected string GetPhpAutoloadPath() =>
Helpers.RuntimesPath.Replace("\\", "/") + "/Php/vendor/autoload.php";
private void PreprocessGeneratedFiles()
{
var grammarMappedFragments = Result.ParserGeneratedState.MappedFragments;
foreach (var (generatedFileName, runtimeFileInfo) in Result.ParserGeneratedState.RuntimeFileInfos)
{
var generatedRawMappedFragments = new List<RawMappedFragment>();
var text = File.ReadAllText(runtimeFileInfo.FullName);
var textSpan = text.AsSpan();
StringBuilder? newTextBuilder = null;
var index = 0;
var beginMatch = FragmentMarkRegexBegin.Match(text, index);
while (beginMatch.Success)
{
newTextBuilder ??= new StringBuilder(text.Length);
if (!int.TryParse(beginMatch.Groups[1].Value, out var fragmentNumber))
throw new FormatException("Incorrect fragment number");
newTextBuilder.Append(textSpan.Slice(index, beginMatch.Index - index));
var fragmentIndex = newTextBuilder.Length;
index = beginMatch.Index + beginMatch.Length;
var endMatch = FragmentMarkRegexEnd.Match(text, index);
if (!endMatch.Success)
throw new FormatException("Every mark should have both begin and end part");
newTextBuilder.Append(textSpan.Slice(index, endMatch.Index - index));
index = endMatch.Index + endMatch.Length;
if (fragmentNumber < 0 || fragmentNumber >= grammarMappedFragments.Count)
throw new FormatException($"Fragment number {fragmentIndex} does not map to grammar fragment");
generatedRawMappedFragments.Add(new RawMappedFragment(fragmentIndex,
newTextBuilder.Length - fragmentIndex, grammarMappedFragments[fragmentNumber]));
beginMatch = FragmentMarkRegexBegin.Match(text, index);
}
Source source;
if (newTextBuilder != null)
{
// Grammar contains actions and predicates
newTextBuilder.Append(textSpan.Slice(index));
var newText = newTextBuilder.ToString();
File.WriteAllText(runtimeFileInfo.FullName, newText);
source = new Source(runtimeFileInfo.FullName, newText);
var generatedMappedFragments = new List<MappedFragment>(generatedRawMappedFragments.Count);
foreach (var rawMappedFragment in generatedRawMappedFragments)
generatedMappedFragments.Add(rawMappedFragment.ToMappedFragment(source));
_fragmentMappers.Add(generatedFileName,
new FragmentMapper(Result.ParserGeneratedState.Runtime, source, generatedMappedFragments));
}
else
{
source = new Source(runtimeFileInfo.FullName, text);
}
_runtimeFiles.Add(generatedFileName, (source, runtimeFileInfo));
}
}
private void CopyHelperFiles()
{
foreach (var (generatedFileName, runtimeFileInfo) in Result.ParserGeneratedState.RuntimeFileInfos)
{
if (runtimeFileInfo.Type == RuntimeFileType.Helper)
{
var outputFileName = Path.Combine(WorkingDirectory, generatedFileName);
File.Copy(runtimeFileInfo.FullName, outputFileName, true);
}
}
}
private void PrepareEntryPointCode()
{
string templateFile = Path.Combine(WorkingDirectory, CurrentRuntimeInfo.MainFile);
Runtime runtime = CurrentRuntimeInfo.Runtime;
string code = File.ReadAllText(Path.Combine(RuntimeDir, CurrentRuntimeInfo.MainFile));
string? packageName = Result.ParserGeneratedState.PackageName;
var grammarType = GrammarCheckedState.GrammarProjectType;
var lexerName = Result.ParserGeneratedState.LexerName;
if (lexerName != null)
code = code.Replace(TemplateLexerName, lexerName);
var parserName = Result.ParserGeneratedState.ParserName;
if (parserName != null)
code = code.Replace(TemplateParserName, parserName);
bool isPackageNameEmpty = string.IsNullOrWhiteSpace(packageName);
bool removePackageNameCode = isPackageNameEmpty;
if (!isPackageNameEmpty)
{
code = code.Replace(PackageName, packageName);
if (runtime == Runtime.Dart)
{
removePackageNameCode = grammarType != GrammarProjectType.Lexer;
}
}
if (runtime == Runtime.Php)
{
RemoveCodeWithinMarkOrRemoveMark(ref code,
new OpenCloseMark("PackageNameParser", CurrentRuntimeInfo),
isPackageNameEmpty || grammarType == GrammarProjectType.Lexer);
}
RemoveCodeWithinMarkOrRemoveMark(ref code, _packageNameMark, removePackageNameCode);
if (runtime == Runtime.Go)
{
var packageName2Mark = new SingleMark("PackageName2", CurrentRuntimeInfo);
code = code.Replace(packageName2Mark.ToString(), isPackageNameEmpty ? "" : packageName + ".");
}
else if (runtime == Runtime.Php)
{
code = code.Replace(RuntimesPath, GetPhpAutoloadPath());
}
else if (runtime == Runtime.Dart)
{
code = code.Replace(new SingleMark("Part", CurrentRuntimeInfo).ToString(),
grammarType == GrammarProjectType.Lexer && !isPackageNameEmpty
? $"part '{lexerName}.dart';" : "");
}
if (CaseInsensitiveType != CaseInsensitiveType.None)
{
string antlrInputStream = CurrentRuntimeInfo.AntlrInputStream;
string caseInsensitiveStream = "AntlrCaseInsensitiveInputStream";
if (runtime == Runtime.Java)
{
caseInsensitiveStream = "new " + caseInsensitiveStream;
}
else if (runtime == Runtime.Go)
{
caseInsensitiveStream = "New" + caseInsensitiveStream;
}
else if (runtime == Runtime.Php)
{
antlrInputStream = antlrInputStream + "::fromPath";
caseInsensitiveStream = caseInsensitiveStream + "::fromPath";
}
else if (runtime == Runtime.Dart)
{
antlrInputStream = antlrInputStream + ".fromPath";
caseInsensitiveStream = caseInsensitiveStream + ".fromPath";
}
var antlrInputStreamRegex = new Regex($@"{antlrInputStream}\(([^\)]+)\)");
string isLowerBool = (CaseInsensitiveType == CaseInsensitiveType.Lower).ToString();
if (runtime != Runtime.Python)
{
isLowerBool = isLowerBool.ToLowerInvariant();
}
code = antlrInputStreamRegex.Replace(code,
m => $"{caseInsensitiveStream}({m.Groups[1].Value}, {isLowerBool})");
if (runtime == Runtime.Python)
code = code.Replace("from antlr4.InputStream import InputStream", "");
}
RemoveCodeWithinMarkOrRemoveMark(ref code, _caseInsensitiveMark, CaseInsensitiveType == CaseInsensitiveType.None);
if (runtime == Runtime.Dart)
{
RemoveCodeWithinMarkOrRemoveMark(ref code, _lexerIncludeMark, !isPackageNameEmpty);
}
RemoveCodeWithinMarkOrRemoveMark(ref code, _parserIncludeMark, grammarType == GrammarProjectType.Lexer);
RemoveCodeWithinMarkOrRemoveMark(ref code, _parserPartMark, grammarType == GrammarProjectType.Lexer);
File.WriteAllText(templateFile, code);
}
private void RemoveCodeWithinMarkOrRemoveMark(ref string code, OpenCloseMark mark, bool removeCode)
{
var openMark = mark.OpenMark;
var closeMark = mark.CloseMark;
int parserStartIndex = code.IndexOf(openMark, StringComparison.Ordinal);
if (parserStartIndex == -1)
return;
int parserEndIndex = code.IndexOf(closeMark, parserStartIndex, StringComparison.Ordinal);
if (parserEndIndex == -1)
throw new FormatException($"Close mark not found for {openMark}");
var firstPart = code.Remove(parserStartIndex);
if (removeCode)
{
parserEndIndex += closeMark.Length;
var lastChar = code.ElementAtOrDefault(parserEndIndex);
if (lastChar == '\r' || lastChar == '\n')
parserEndIndex++;
if (code.ElementAtOrDefault(parserEndIndex) == '\n')
parserEndIndex++;
code = firstPart + code.Substring(parserEndIndex);
}
else
{
int parserStartIndexEnd = parserStartIndex + openMark.Length;
var middlePart = code.Substring(parserStartIndexEnd, parserEndIndex - parserStartIndexEnd);
code = firstPart + middlePart + code.Substring(parserEndIndex + closeMark.Length);
}
}
private void ParserCompilation_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
ProcessReceivedData(e.Data);
}
private void ParserCompilation_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
ProcessReceivedData(e.Data);
}
protected virtual void ProcessReceivedData(string data)
{
lock (_lockObject)
{
if (_ignoreDiagnosis)
return;
if (CurrentRuntimeInfo.Runtime.IsCSharpRuntime() && CSharpStopStringRegex.IsMatch(data))
_ignoreDiagnosis = true;
}
var match = ParserCompilerMessageRegex.Match(data);
if (match.Success)
{
var groups = match.Groups;
string codeFileName = Path.GetFileName(groups[FileMark].Value);
int.TryParse(groups[LineMark].Value, out int line);
if (!int.TryParse(groups[ColumnMark].Value, out int column))
column = LineColumnTextSpan.StartColumn;
string message = groups[MessageMark].Value;
var (simplifiedMessage, errorTextSpanLength) = SimplifyMessageAndSpecifyErrorTextSpanLength(message);
var diagnosisType = groups[TypeMark].Value.Contains("warning", StringComparison.OrdinalIgnoreCase)
? DiagnosisType.Warning
: DiagnosisType.Error;
if (CurrentRuntimeInfo.Runtime == Runtime.Java && message.StartsWith("[deprecation] ANTLRInputStream"))
return;
var diagnosis = CreateMappedGrammarDiagnosis(codeFileName, line, column, simplifiedMessage, diagnosisType);
AddDiagnosis(diagnosis);
}
}
protected virtual (string NewMessage, int ErrorTextSpanLength) SimplifyMessageAndSpecifyErrorTextSpanLength(string message)
{
return (message, 0);
}
protected ParserCompilationDiagnosis CreateMappedGrammarDiagnosis(string? codeFileName, int line, int column,
string message, DiagnosisType type)
{
if (codeFileName == null)
return new ParserCompilationDiagnosis(message, type);
if (_fragmentMappers.TryGetValue(codeFileName, out FragmentMapper fragmentMapper))
{
var mappedResult = fragmentMapper.Map(line, column);
return new ParserCompilationDiagnosis(mappedResult.TextSpanInGrammar, mappedResult.TextSpanInGenerated, message, type);
}
var source = _runtimeFiles[codeFileName].Item1;
var position = source.LineColumnToPosition(line, column);
return new ParserCompilationDiagnosis(null, new TextSpan(position, 0, source), message, type);
}
protected void AddToBuffer(string data)
{
lock (Buffer)
{
Buffer.Add(data);
}
}
protected void AddDiagnosis(Diagnosis diagnosis)
{
DiagnosisEvent?.Invoke(this, diagnosis);
Result.AddDiagnosis(diagnosis);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Hyak.Common;
using System;
using System.Net.Http;
namespace Microsoft.Azure.Management.Internal.Resources
{
public partial class AuthorizationClient : ServiceClient<AuthorizationClient>, IAuthorizationClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IManagementLockOperations _managementLocks;
/// <summary>
/// Operations for managing locks.
/// </summary>
public virtual IManagementLockOperations ManagementLocks
{
get { return this._managementLocks; }
}
/// <summary>
/// Initializes a new instance of the AuthorizationClient class.
/// </summary>
public AuthorizationClient()
: base()
{
this._managementLocks = new ManagementLockOperations(this);
this._apiVersion = "2015-01-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AuthorizationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AuthorizationClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AuthorizationClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationClient(HttpClient httpClient)
: base(httpClient)
{
this._managementLocks = new ManagementLockOperations(this);
this._apiVersion = "2015-01-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AuthorizationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// AuthorizationClient instance
/// </summary>
/// <param name='client'>
/// Instance of AuthorizationClient to clone to
/// </param>
protected override void Clone(ServiceClient<AuthorizationClient> client)
{
base.Clone(client);
if (client is AuthorizationClient)
{
AuthorizationClient clonedClient = ((AuthorizationClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// FieldValueResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Autopilot.V1.Assistant.FieldType
{
public class FieldValueResource : Resource
{
private static Request BuildFetchRequest(FetchFieldValueOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/FieldTypes/" + options.PathFieldTypeSid + "/FieldValues/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static FieldValueResource Fetch(FetchFieldValueOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<FieldValueResource> FetchAsync(FetchFieldValueOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// resource to fetch </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value to fetch </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static FieldValueResource Fetch(string pathAssistantSid,
string pathFieldTypeSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchFieldValueOptions(pathAssistantSid, pathFieldTypeSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// resource to fetch </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value to fetch </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<FieldValueResource> FetchAsync(string pathAssistantSid,
string pathFieldTypeSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchFieldValueOptions(pathAssistantSid, pathFieldTypeSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadFieldValueOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/FieldTypes/" + options.PathFieldTypeSid + "/FieldValues",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static ResourceSet<FieldValueResource> Read(ReadFieldValueOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<FieldValueResource>.FromJson("field_values", response.Content);
return new ResourceSet<FieldValueResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<ResourceSet<FieldValueResource>> ReadAsync(ReadFieldValueOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<FieldValueResource>.FromJson("field_values", response.Content);
return new ResourceSet<FieldValueResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// resources to read </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value to read </param>
/// <param name="language"> The ISO language-country tag that identifies the language of the value </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static ResourceSet<FieldValueResource> Read(string pathAssistantSid,
string pathFieldTypeSid,
string language = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadFieldValueOptions(pathAssistantSid, pathFieldTypeSid){Language = language, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// resources to read </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value to read </param>
/// <param name="language"> The ISO language-country tag that identifies the language of the value </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<ResourceSet<FieldValueResource>> ReadAsync(string pathAssistantSid,
string pathFieldTypeSid,
string language = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadFieldValueOptions(pathAssistantSid, pathFieldTypeSid){Language = language, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<FieldValueResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<FieldValueResource>.FromJson("field_values", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<FieldValueResource> NextPage(Page<FieldValueResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Autopilot)
);
var response = client.Request(request);
return Page<FieldValueResource>.FromJson("field_values", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<FieldValueResource> PreviousPage(Page<FieldValueResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Autopilot)
);
var response = client.Request(request);
return Page<FieldValueResource>.FromJson("field_values", response.Content);
}
private static Request BuildCreateRequest(CreateFieldValueOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/FieldTypes/" + options.PathFieldTypeSid + "/FieldValues",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static FieldValueResource Create(CreateFieldValueOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<FieldValueResource> CreateAsync(CreateFieldValueOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// new resource </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value </param>
/// <param name="language"> The ISO language-country tag that identifies the language of the value </param>
/// <param name="value"> The Field Value data </param>
/// <param name="synonymOf"> The string value that indicates which word the field value is a synonym of </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static FieldValueResource Create(string pathAssistantSid,
string pathFieldTypeSid,
string language,
string value,
string synonymOf = null,
ITwilioRestClient client = null)
{
var options = new CreateFieldValueOptions(pathAssistantSid, pathFieldTypeSid, language, value){SynonymOf = synonymOf};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// new resource </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value </param>
/// <param name="language"> The ISO language-country tag that identifies the language of the value </param>
/// <param name="value"> The Field Value data </param>
/// <param name="synonymOf"> The string value that indicates which word the field value is a synonym of </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<FieldValueResource> CreateAsync(string pathAssistantSid,
string pathFieldTypeSid,
string language,
string value,
string synonymOf = null,
ITwilioRestClient client = null)
{
var options = new CreateFieldValueOptions(pathAssistantSid, pathFieldTypeSid, language, value){SynonymOf = synonymOf};
return await CreateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteFieldValueOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/FieldTypes/" + options.PathFieldTypeSid + "/FieldValues/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static bool Delete(DeleteFieldValueOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete FieldValue parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteFieldValueOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// resources to delete </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value to delete </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FieldValue </returns>
public static bool Delete(string pathAssistantSid,
string pathFieldTypeSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteFieldValueOptions(pathAssistantSid, pathFieldTypeSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the FieldType associated with the
/// resources to delete </param>
/// <param name="pathFieldTypeSid"> The SID of the Field Type associated with the Field Value to delete </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FieldValue </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid,
string pathFieldTypeSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteFieldValueOptions(pathAssistantSid, pathFieldTypeSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a FieldValueResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> FieldValueResource object represented by the provided JSON </returns>
public static FieldValueResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<FieldValueResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The SID of the Field Type associated with the Field Value
/// </summary>
[JsonProperty("field_type_sid")]
public string FieldTypeSid { get; private set; }
/// <summary>
/// The ISO language-country tag that identifies the language of the value
/// </summary>
[JsonProperty("language")]
public string Language { get; private set; }
/// <summary>
/// The SID of the Assistant that is the parent of the FieldType associated with the resource
/// </summary>
[JsonProperty("assistant_sid")]
public string AssistantSid { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The Field Value data
/// </summary>
[JsonProperty("value")]
public string Value { get; private set; }
/// <summary>
/// The absolute URL of the FieldValue resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The word for which the field value is a synonym of
/// </summary>
[JsonProperty("synonym_of")]
public string SynonymOf { get; private set; }
private FieldValueResource()
{
}
}
}
| |
// Project: DungeonQuest, File: UIRenderer.cs
// Namespace: DungeonQuest.Graphics, Class: UIRenderer
// Path: C:\code\DungeonQuest\Graphics, Author: Abi
// Code lines: 1330, Size of file: 40,70 KB
// Creation date: 23.09.2006 09:57
// Last modified: 03.11.2006 08:41
// Generated with Commenter by abi.exDream.com
#region Using directives
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using DungeonQuest.GameLogic;
using DungeonQuest.Helpers;
using DungeonQuest.Shaders;
using DungeonQuest.GameScreens;
using DungeonQuest.Game;
#endregion
namespace DungeonQuest.Graphics
{
/// <summary>
/// Helper class to render all UI 2D stuff. Rendering textures is very easy
/// with XNA using the Sprite class, but we still have to create
/// SpriteBatches. This class helps and handles everything for us.
/// </summary>
public class UIRenderer : IDisposable
{
#region Constants
/// <summary>
/// Graphic rectangles for displaying UI stuff.
/// </summary>
public readonly static Rectangle
BackgroundGfxRect = new Rectangle(0, 0, 1024, 640),
RacingGameLogoGfxRect = new Rectangle(0, 1024 - 375, 1024, 374),
BottomLeftBorderGfxRect = new Rectangle(2, 984, 38, 37),
BottomRightBorderGfxRect = new Rectangle(42, 984, 38, 37),
PressStartGfxRect = new Rectangle(2, 1, 631, 45),
MicrosoftLogoGfxRect = new Rectangle(2, 52, 383, 68),
ExdreamLogoGfxRect = new Rectangle(517, 52, 433, 112),
WebsiteLogoGfxRect = new Rectangle(7, 139, 454, 52),
HeaderChooseCarGfxRect = new Rectangle(0, 212, 512, 100),
HeaderOptionsGfxRect = new Rectangle(512, 212, 512, 100),
HeaderSelectTrackGfxRect = new Rectangle(0, 312, 512, 100),
HeaderHelpGfxRect = new Rectangle(512, 312, 512, 100),
HeaderHighscoresGfxRect = new Rectangle(0, 412, 512, 100),
HeaderCreditsGfxRect = new Rectangle(512, 412, 512, 100),
BlackBarGfxRect = new Rectangle(99, 999, 1, 1),
OptionsRadioButtonGfxRect = new Rectangle(128, 980, 25, 25),
MenuButtonPlayGfxRect = new Rectangle(0, 0, 212, 212),
MenuButtonHighscoresGfxRect = new Rectangle(212, 0, 212, 212),
MenuButtonOptionsGfxRect = new Rectangle(2 * 212, 0, 212, 212),
MenuButtonHelpGfxRect = new Rectangle(3 * 212, 0, 212, 212),
MenuButtonCreditsGfxRect = new Rectangle(0, 240, 212, 212),
MenuButtonQuitGfxRect = new Rectangle(212, 240, 212, 212),
MenuButtonSelectionGfxRect = new Rectangle(3 * 212, 240, 212, 212),
MenuTextPlayGfxRect = new Rectangle(0, 214, 212, 24),
MenuTextHighscoresGfxRect = new Rectangle(212, 214, 212, 24),
MenuTextOptionsGfxRect = new Rectangle(2 * 212, 214, 212, 24),
MenuTextHelpGfxRect = new Rectangle(3 * 212, 214, 212, 24),
MenuTextCreditsGfxRect = new Rectangle(0, 240 + 214, 212, 24),
MenuTextQuitGfxRect = new Rectangle(212, 240 + 214, 212, 24),
BigArrowGfxRect = new Rectangle(867, 242, 127, 178),
TrackButtonBeginnerGfxRect = new Rectangle(0, 480, 212, 352),
TrackButtonAdvancedGfxRect = new Rectangle(212, 480, 212, 352),
TrackButtonExpertGfxRect = new Rectangle(2 * 212, 480, 212, 352),
TrackButtonSelectionGfxRect = new Rectangle(3 * 212, 480, 212, 352),
TrackTextBeginnerGfxRect = new Rectangle(0, 834, 212, 24),
TrackTextAdvancedGfxRect = new Rectangle(212, 834, 212, 24),
TrackTextExpertGfxRect = new Rectangle(2 * 212, 834, 212, 24),
BottomButtonSelectionGfxRect = new Rectangle(212 * 2, 240, 212, 92),
BottomButtonAButtonGfxRect = new Rectangle(0, 872, 212, 92),
BottomButtonBButtonGfxRect = new Rectangle(212, 872, 212, 92),
BottomButtonBackButtonGfxRect = new Rectangle(2 * 212, 872, 212, 92),
BottomButtonStartButtonGfxRect = new Rectangle(3 * 212, 872, 212, 92),
SelectionArrowGfxRect = new Rectangle(874, 426, 53, 39),
SelectionRadioButtonGfxRect = new Rectangle(935, 427, 39, 39);
/// <summary>
/// In game gfx rects. Tacho is our speedometer we see on the screen.
/// </summary>
public static readonly Rectangle
LapsGfxRect = new Rectangle(381, 132, 222, 160),
TachoGfxRect = new Rectangle(0, 0, 343, 341),
TachoArrowGfxRect = new Rectangle(347, 0, 28, 186),
TachoMphGfxRect = new Rectangle(184, 256, 148, 72),
TachoGearGfxRect = new Rectangle(286, 149, 52, 72),
CurrentAndBestGfxRect = new Rectangle(381, 2, 342, 128),
CurrentTimePosGfxRect = new Rectangle(540, 8, 170, 52),
BestTimePosGfxRect = new Rectangle(540, 72, 170, 52),
TrackNameGfxRect = new Rectangle(726, 2, 282, 62),
Best5GfxRect = new Rectangle(726, 66, 282, 62);
#endregion
#region Variables
/// <summary>
/// The 3 splash logos that are displayed when we start the game.
/// </summary>
Texture[] splashLogos = new Texture[3];
/// <summary>
/// Background
/// </summary>
Texture background;
/// <summary>
/// Buttons
/// </summary>
Texture buttons;
/// <summary>
/// Logos
/// </summary>
Texture logos;
/// <summary>
/// Help screen texture
/// </summary>
Texture helpScreen;
/// <summary>
/// Options screen texture
/// </summary>
Texture optionsScreen;
/// <summary>
/// Credits screen texture
/// </summary>
Texture creditsScreen;
/// <summary>
/// Mouse cursor
/// </summary>
Texture mouseCursor;
/// <summary>
/// Font
/// </summary>
TextureFont font;
/// <summary>
/// Post screen menu shader for cool screen effects like the TV effect,
/// stripes, a flash effect and some color correction.
/// </summary>
PostScreenMenu postScreenMenuShader;
/// <summary>
/// Post screen game shader for glow, color correction and motion blur
/// effects in the game.
/// </summary>
PostScreenGlow postScreenGameShader;
/// <summary>
/// Sky cube background rendering
/// </summary>
//PreScreenSkyCubeMapping skyCube = null;
/// <summary>
/// And finally the lens flare we render at the end.
/// </summary>
//LensFlare lensFlare = null;
/// <summary>
/// Ingame texture for the speed, gear, time, rank, laps, etc.
/// </summary>
Texture ingame = null;
/// <summary>
/// Trophies
/// </summary>
Texture trophy = null;
#endregion
#region Properties
/// <summary>
/// Splash logo
/// </summary>
/// <param name="number">Number</param>
/// <returns>Texture</returns>
public Texture SplashLogo(int number)
{
return splashLogos[number % splashLogos.Length];
} // SplashLogo(number)
/// <summary>
/// Buttons
/// </summary>
/// <returns>Texture</returns>
public Texture Buttons
{
get
{
return buttons;
} // get
} // Buttons
/// <summary>
/// Logos
/// </summary>
/// <returns>Texture</returns>
public Texture Logos
{
get
{
return logos;
} // get
} // Logos
/// <summary>
/// Help screen
/// </summary>
/// <returns>Texture</returns>
public Texture HelpScreen
{
get
{
return helpScreen;
} // get
} // HelpScreen
/// <summary>
/// Options screen
/// </summary>
/// <returns>Texture</returns>
public Texture OptionsScreen
{
get
{
return optionsScreen;
} // get
} // OptionsScreen
/// <summary>
/// Credits screen
/// </summary>
/// <returns>Texture</returns>
public Texture CreditsScreen
{
get
{
return creditsScreen;
} // get
} // CreditsScreen
/// <summary>
/// Ingame
/// </summary>
/// <returns>Texture</returns>
public Texture Ingame
{
get
{
return ingame;
} // get
} // Ingame
/// <summary>
/// Get trophy texture
/// </summary>
/// <param name="trophyType">Trophy type</param>
/// <returns>Texture</returns>
public Texture GetTrophyTexture()
{
return trophy;
} // GetTrophyTexture(trophyType)
/// <summary>
/// Post screen menu shader
/// </summary>
/// <returns>Post screen menu</returns>
public PostScreenMenu PostScreenMenuShader
{
get
{
return postScreenMenuShader;
} // get
} // PostScreenMenuShader
public PostScreenGlow PostScreenGlowShader
{
get
{
return postScreenGameShader;
} // get
} // PostScreenGlowShader
/*
/// <summary>
/// Sky cube map texture
/// </summary>
/// <returns>Texture cube</returns>
public TextureCube SkyCubeMapTexture
{
get
{
return skyCube.SkyCubeMapTexture;
} // get
} // SkyCubeMapTexture
*/
#endregion
#region Constructor
/// <summary>
/// Create user interface renderer
/// </summary>
public UIRenderer()
{
//splashLogos[0] = new Texture("logoonly_xna");
//splashLogos[1] = new Texture("logoonly_exdream");
//splashLogos[2] = new Texture("logoonly_microsoft");
background = new Texture("background.png");
buttons = new Texture("buttons.png");
//logos = new Texture("logos.png");
//helpScreen = new Texture("HelpScreen.png");
optionsScreen = new Texture("OptionsScreen.png");
//creditsScreen = new Texture("CreditsScreen.png");
mouseCursor = new Texture("MouseCursor.png");
//ingame = new Texture("Ingame.png");
//trophy = new Texture("pokal1");
font = new TextureFont();
postScreenMenuShader = new PostScreenMenu();
postScreenGameShader = new PostScreenGlow();
//skyCube = new PreScreenSkyCubeMapping();
//lensFlare = new LensFlare(LensFlare.DefaultSunPos);
//BaseGame.LightDirection = LensFlare.DefaultLightPos;
} // UIRenderer()
#endregion
#region Dispose
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
} // Dispose()
/// <summary>
/// Dispose
/// </summary>
/// <param name="disposing">Disposing</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
for (int num = 0; num < 3; num++)
splashLogos[num].Dispose();
if (background != null)
background.Dispose();
if (buttons != null)
buttons.Dispose();
if (logos != null)
logos.Dispose();
if (helpScreen != null)
helpScreen.Dispose();
if (optionsScreen != null)
optionsScreen.Dispose();
if (creditsScreen != null)
creditsScreen.Dispose();
if (mouseCursor != null)
mouseCursor.Dispose();
if (postScreenMenuShader != null)
postScreenMenuShader.Dispose();
if (postScreenGameShader != null)
postScreenGameShader.Dispose();
/*if (skyCube != null)
skyCube.Dispose();
if (lensFlare != null)
lensFlare.Dispose();*/
if (ingame != null)
ingame.Dispose();
} // if
} // Dispose(disposing)
#endregion
#region Add time fadeup effect
/// <summary>
/// Time fadeup modes
/// </summary>
public enum TimeFadeupMode
{
Plus,
Minus,
Normal,
} // enum TimeFadeupMode
class TimeFadeupText
{
public string text;
public Color color;
public float showTimeMs;
public const float MaxShowTimeMs = 2250;//3000;
public TimeFadeupText(string setText, Color setColor)
{
text = setText;
color = setColor;
showTimeMs = MaxShowTimeMs;
} // TimeFadeupText(setText, setShowTimeMs)
} // TimeFadeupText
List<TimeFadeupText> fadeupTexts = new List<TimeFadeupText>();
/// <summary>
/// Add time fadeup effect. Used in the game to show times, plus (green)
/// means we took longer for this checkpoint, minus (green) means we did
/// good.
/// </summary>
/// <param name="timeMilisec">Time</param>
/// <param name="mode">Mode</param>
public void AddTimeFadeupEffect(int timeMilliseconds, TimeFadeupMode mode)
{
string text =
//min
((timeMilliseconds / 1000) / 60) + ":" +
//sec
((timeMilliseconds / 1000) % 60).ToString("00") + "." +
//ms
((timeMilliseconds / 10) % 100).ToString("00");
Color col = Color.White;
if (mode == TimeFadeupMode.Plus)
{
text = "+ " + text;
col = Color.Red;
} // if
else if (mode == TimeFadeupMode.Minus)
{
text = "- " + text;
col = Color.Green;
} // else if
fadeupTexts.Add(new TimeFadeupText(text, col));
} // AddTimeFadeupEffect(timeMilisec, mode)
/// <summary>
/// Render all time fadeup effects, move them up and fade them out.
/// </summary>
public void RenderTimeFadeupEffects()
{
for (int num = 0; num < fadeupTexts.Count; num++)
{
TimeFadeupText fadeupText = fadeupTexts[num];
fadeupText.showTimeMs -= BaseGame.ElapsedTimeThisFrameInMs;
if (fadeupText.showTimeMs < 0)
{
fadeupTexts.Remove(fadeupText);
num--;
} // if
else
{
// Fade out
float alpha = 1.0f;
if (fadeupText.showTimeMs < 1500)
alpha = fadeupText.showTimeMs / 1500.0f;
// Move up
float moveUpAmount =
(TimeFadeupText.MaxShowTimeMs - fadeupText.showTimeMs) /
TimeFadeupText.MaxShowTimeMs;
// Calculate screen position
TextureFont.WriteTextCentered(BaseGame.Width / 2,
BaseGame.Height / 3 - (int)(moveUpAmount * BaseGame.Height / 3),
fadeupText.text,
ColorHelper.ApplyAlphaToColor(fadeupText.color, alpha),
2.25f);
} // else
} // for
} // RenderTimeFadeupEffects()
#endregion
#region Menu UI
#region Render game background
/// <summary>
/// Render game background
/// </summary>
public void RenderGameBackground()
{
// Show game background (sky and lensflare)
//skyCube.RenderSky();
// Render lens flare on top of 3d stuff
//if (Track.disableLensFlareInTunnel == false)
// lensFlare.Render(Color.White);
} // RenderGameBackground()
#endregion
#region Render menu background
//private float carTrackPos = 0;
private Vector3 oldCarForward = Vector3.Zero;
private Vector3 oldCarUp = Vector3.Zero;
//private float carMenuTime = 0.0f;
//private Vector3 carPos = GameManager.Player.CarPosition;
/*
/// <summary>
/// Render menu track background
/// </summary>
public void RenderMenuTrackBackground()
{
// Advance menu car preview time
carMenuTime += BaseGame.ElapsedTimeThisFrameInMilliseconds / 1000.0f;
if (carMenuTime > GameManager.Landscape.BestReplay.LapTime)
carMenuTime -= GameManager.Landscape.BestReplay.LapTime;
// Use data from replay
Matrix carMatrix =
GameManager.Landscape.BestReplay.GetCarMatrixAtTime(
carMenuTime);
// Interpolate carPos a little
carPos = carMatrix.Translation;
// Set carPos for camera (else the car will drive away from us ^^)
GameManager.Player.SetCarPosition(
carPos, carMatrix.Forward, carMatrix.Up);
// Put camera behind car, but make it move smoothly
Vector3 newCarForward = carMatrix.Forward;
Vector3 newCarUp = carMatrix.Up;
if (oldCarForward == Vector3.Zero)
oldCarForward = newCarForward;
if (oldCarUp == Vector3.Zero)
oldCarUp = newCarUp;
oldCarForward = oldCarForward * 0.95f + newCarForward * 0.05f;
oldCarUp = oldCarUp * 0.95f + newCarUp * 0.05f;
GameManager.Player.SetCameraPosition(
// Mix camera positions, interpolate slowly, much smoother camera!
carPos + oldCarForward * 13 - oldCarUp * 1.3f);
//carPos + carMatrix.Forward * 13 - carMatrix.Up * 1.3f);
// For rendering rotate car to stay correctly on the road
carMatrix =
Matrix.CreateRotationX(MathHelper.Pi / 2.0f) *
Matrix.CreateRotationZ(MathHelper.Pi) *
carMatrix;
GameManager.Player.Update();
GameManager.Landscape.Render();
GameManager.CarModel.RenderCar(false, carMatrix);
} // RenderMenuTrackBackground()
*/
/// <summary>
/// Render menu background
/// </summary>
public void RenderMenuBackground()
{
// Render game background
//RenderGameBackground();
// And show track
//RenderMenuTrackBackground();
// Render background with transparency
// The background itself should be rendered before this ^^
background.RenderOnScreen(
BaseGame.ResolutionRect, BackgroundGfxRect,
ColorHelper.ApplyAlphaToColor(Color.White, 0.85f));
// Show DungeonQuest logo
/*
background.RenderOnScreen(
BaseGame.CalcRectangle(352, 31, 621, 228),
RacingGameLogoGfxRect);
*/
// Bounce with the music
float bounceSize = 1.005f +
(float)Math.Sin(BaseGame.TotalTime / 0.46f) * 0.045f *
(float)Math.Cos(BaseGame.TotalTime / 0.285f);
background.RenderOnScreen(
BaseGame.CalcRectangleWithBounce(362, 36, 601, 218, bounceSize),
RacingGameLogoGfxRect);
//new Color(255, 255, 255, 45));
// Add bottom borders
buttons.RenderOnScreen(
BaseGame.CalcRectangleKeep4To3AlignBottom(6, 554, 38, 37),
BottomLeftBorderGfxRect,
ColorHelper.ApplyAlphaToColor(Color.White, 0.85f));
buttons.RenderOnScreen(
BaseGame.CalcRectangleKeep4To3AlignBottomRight(1019, 554, 38, 37),
BottomRightBorderGfxRect,
ColorHelper.ApplyAlphaToColor(Color.White, 0.85f));
} // RenderMenuBackground()
#endregion
#region RenderBlackBar
/// <summary>
/// Render black bar
/// </summary>
/// <param name="yPos">Y position</param>
/// <param name="height">Height</param>
public void RenderBlackBar(int yPos, int height)
{
buttons.RenderOnScreen(
BaseGame.CalcRectangle(0, yPos, 1024, height),
BlackBarGfxRect,
ColorHelper.ApplyAlphaToColor(Color.White, 0.85f));
} // RenderBlackBar(yPos, height)
#endregion
#region RenderLogos
/// <summary>
/// Render logos
/// </summary>
public void RenderLogos()
{
Rectangle microsoftRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
162, 590, 35, MicrosoftLogoGfxRect);
logos.RenderOnScreen(microsoftRect, MicrosoftLogoGfxRect);
#if !XBOX360
if (Input.MouseInBox(microsoftRect) &&
Input.MouseLeftButtonJustPressed)
Process.Start("http://www.Microsoft.com");
#endif
Rectangle websiteRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
512, 590, 28, WebsiteLogoGfxRect);
logos.RenderOnScreen(websiteRect, WebsiteLogoGfxRect);
#if !XBOX360
if (Input.MouseInBox(websiteRect) &&
Input.MouseLeftButtonJustPressed)
Process.Start("http://www.DungeonQuest.com");
#endif
Rectangle exDreamRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
1024-160, 590, 47, ExdreamLogoGfxRect);
logos.RenderOnScreen(exDreamRect, ExdreamLogoGfxRect);
#if !XBOX360
if (Input.MouseInBox(exDreamRect) &&
Input.MouseLeftButtonJustPressed)
Process.Start("http://www.exdream.com");
#endif
} // RenderLogos()
#endregion
#region RenderBottomButtons
public bool backButtonPressed = false;
/// <summary>
/// Render bottom buttons (select, back, etc.)
/// </summary>
/// <param name="onlyBack">Only back</param>
public bool RenderBottomButtons(bool onlyBack)
{
/*old, too close to the borders for the xbox 360
// Also show website
Rectangle websiteRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
166, 597, 28, WebsiteLogoGfxRect);
logos.RenderOnScreen(websiteRect, WebsiteLogoGfxRect);
Rectangle bButtonRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
0, 597, 52, BottomButtonBButtonGfxRect);
bButtonRect.X = BaseGame.Width - bButtonRect.Width - BaseGame.XToRes(25);
bool overBButton = Input.MouseInBox(bButtonRect);
int xAdd = BaseGame.XToRes(16);
int yAdd = BaseGame.YToRes(9);
if (overBButton)
bButtonRect = new Rectangle(
bButtonRect.X - xAdd / 2, bButtonRect.Y - yAdd / 2,
bButtonRect.Width + xAdd, bButtonRect.Height + yAdd);
buttons.RenderOnScreen(bButtonRect, BottomButtonBButtonGfxRect);
// Is mouse over button?
if (overBButton)
buttons.RenderOnScreen(bButtonRect, BottomButtonSelectionGfxRect);
// Store value if back button was pressed;
backButtonPressed = overBButton && Input.MouseLeftButtonJustPressed;
// Don't show button a if there is nothing to select here
if (onlyBack)
return false;
Rectangle aButtonRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
0, 597, 52, BottomButtonAButtonGfxRect);
aButtonRect.X = BaseGame.Width -
aButtonRect.Width * 2 - BaseGame.XToRes(55);
bool overAButton = Input.MouseInBox(aButtonRect);
if (overAButton)
aButtonRect = new Rectangle(
aButtonRect.X - xAdd / 2, aButtonRect.Y - yAdd / 2,
aButtonRect.Width + xAdd, aButtonRect.Height + yAdd);
buttons.RenderOnScreen(aButtonRect, BottomButtonAButtonGfxRect);
// Is mouse over button?
if (overAButton)
{
buttons.RenderOnScreen(aButtonRect, BottomButtonSelectionGfxRect);
if (Input.MouseLeftButtonJustPressed)
return true;
} // if (overAButton)
return false;
*/
// Also show website
Rectangle websiteRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
170, 587, 25, WebsiteLogoGfxRect);
logos.RenderOnScreen(websiteRect, WebsiteLogoGfxRect);
Rectangle bButtonRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
0, 587, 48, BottomButtonBButtonGfxRect);
bButtonRect.X = BaseGame.Width - bButtonRect.Width - BaseGame.XToRes(25+25);
bool overBButton = Input.MouseInBox(bButtonRect);
int xAdd = BaseGame.XToRes(16);
int yAdd = BaseGame.YToRes(9);
if (overBButton)
bButtonRect = new Rectangle(
bButtonRect.X - xAdd / 2, bButtonRect.Y - yAdd / 2,
bButtonRect.Width + xAdd, bButtonRect.Height + yAdd);
buttons.RenderOnScreen(bButtonRect, BottomButtonBButtonGfxRect);
// Is mouse over button?
if (overBButton)
buttons.RenderOnScreen(bButtonRect, BottomButtonSelectionGfxRect);
// Store value if back button was pressed;
backButtonPressed = overBButton && Input.MouseLeftButtonJustPressed;
// Don't show button a if there is nothing to select here
if (onlyBack)
return false;
Rectangle aButtonRect = BaseGame.CalcRectangleCenteredWithGivenHeight(
0, 587, 48, BottomButtonAButtonGfxRect);
aButtonRect.X = BaseGame.Width -
aButtonRect.Width * 2 - BaseGame.XToRes(55+25);
bool overAButton = Input.MouseInBox(aButtonRect);
if (overAButton)
aButtonRect = new Rectangle(
aButtonRect.X - xAdd / 2, aButtonRect.Y - yAdd / 2,
aButtonRect.Width + xAdd, aButtonRect.Height + yAdd);
buttons.RenderOnScreen(aButtonRect, BottomButtonAButtonGfxRect);
// Is mouse over button?
if (overAButton)
{
buttons.RenderOnScreen(aButtonRect, BottomButtonSelectionGfxRect);
if (Input.MouseLeftButtonJustPressed)
return true;
} // if (overAButton)
return false;
} // RenderBottomButtons(onlyBack)
#endregion
#endregion
#region Game UI
/*
/// <summary>
/// Render game user interface
/// </summary>
/// <param name="currentGameTime">Current game time</param>
/// <param name="bestLapTime">Best lap time</param>
/// <param name="lapNumber">Lap number</param>
/// <param name="speed">Speed</param>
/// <param name="gear">Gear</param>
/// <param name="trackName">Track name</param>
/// <param name="top5LapTimes">Top 5 lap times</param>
public void RenderGameUI(int currentGameTime, int bestLapTime,
int lapNumber, float speed, int gear, float acceleration,
string trackName, int[] top5LapTimes)
{
if (top5LapTimes == null)
throw new ArgumentNullException("top5LapTimes");
Color baseUIColor = Color.White;//ColorHelper.HalfAlpha;
// More distance to the screen borders on the Xbox 360 to fit better into
// the save region. Calculate all rectangles for each platform,
// then they will be used the same way on both platforms.
#if XBOX360
// Draw all boxes and background stuff
Rectangle lapsRect = BaseGame.CalcRectangle1600(
60, 46, LapsGfxRect.Width, LapsGfxRect.Height);
ingame.RenderOnScreen(lapsRect, LapsGfxRect, baseUIColor);
Rectangle timesRect = BaseGame.CalcRectangle1600(
60, 46, CurrentAndBestGfxRect.Width, CurrentAndBestGfxRect.Height);
timesRect.Y = BaseGame.Height-timesRect.Bottom;
ingame.RenderOnScreen(timesRect, CurrentAndBestGfxRect, baseUIColor);
Rectangle trackNameRect = BaseGame.CalcRectangle1600(
60, 46, TrackNameGfxRect.Width, TrackNameGfxRect.Height);
trackNameRect.X = BaseGame.Width-trackNameRect.Right;
ingame.RenderOnScreen(trackNameRect, TrackNameGfxRect, baseUIColor);
Rectangle top5Rect1 = BaseGame.CalcRectangle1600(
60, 4, Best5GfxRect.Width, Best5GfxRect.Height);
top5Rect1.X = trackNameRect.X;
int top5Distance = top5Rect1.Y;
top5Rect1.Y += trackNameRect.Bottom;
ingame.RenderOnScreen(top5Rect1, Best5GfxRect, baseUIColor);
Rectangle top5Rect2 = new Rectangle(top5Rect1.X,
top5Rect1.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect2, Best5GfxRect, baseUIColor);
Rectangle top5Rect3 = new Rectangle(top5Rect1.X,
top5Rect2.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect3, Best5GfxRect, baseUIColor);
Rectangle top5Rect4 = new Rectangle(top5Rect1.X,
top5Rect3.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect4, Best5GfxRect, baseUIColor);
Rectangle top5Rect5 = new Rectangle(top5Rect1.X,
top5Rect4.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect5, Best5GfxRect, baseUIColor);
Rectangle tachoRect = BaseGame.CalcRectangle1600(
60, 46, TachoGfxRect.Width, TachoGfxRect.Height);
tachoRect.X = BaseGame.Width-tachoRect.Right;
tachoRect.Y = BaseGame.Height-tachoRect.Bottom;
#else
// Draw all boxes and background stuff
Rectangle lapsRect = BaseGame.CalcRectangle1600(
10, 10, LapsGfxRect.Width, LapsGfxRect.Height);
ingame.RenderOnScreen(lapsRect, LapsGfxRect, baseUIColor);
Rectangle timesRect = BaseGame.CalcRectangle1600(
10, 10, CurrentAndBestGfxRect.Width, CurrentAndBestGfxRect.Height);
timesRect.Y = BaseGame.Height-timesRect.Bottom;
ingame.RenderOnScreen(timesRect, CurrentAndBestGfxRect, baseUIColor);
Rectangle trackNameRect = BaseGame.CalcRectangle1600(
10, 10, TrackNameGfxRect.Width, TrackNameGfxRect.Height);
trackNameRect.X = BaseGame.Width-trackNameRect.Right;
ingame.RenderOnScreen(trackNameRect, TrackNameGfxRect, baseUIColor);
Rectangle top5Rect1 = BaseGame.CalcRectangle1600(
10, 4, Best5GfxRect.Width, Best5GfxRect.Height);
top5Rect1.X = trackNameRect.X;
int top5Distance = top5Rect1.Y;
top5Rect1.Y += trackNameRect.Bottom;
ingame.RenderOnScreen(top5Rect1, Best5GfxRect, baseUIColor);
Rectangle top5Rect2 = new Rectangle(top5Rect1.X,
top5Rect1.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect2, Best5GfxRect, baseUIColor);
Rectangle top5Rect3 = new Rectangle(top5Rect1.X,
top5Rect2.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect3, Best5GfxRect, baseUIColor);
Rectangle top5Rect4 = new Rectangle(top5Rect1.X,
top5Rect3.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect4, Best5GfxRect, baseUIColor);
Rectangle top5Rect5 = new Rectangle(top5Rect1.X,
top5Rect4.Bottom+top5Distance, top5Rect1.Width, top5Rect1.Height);
ingame.RenderOnScreen(top5Rect5, Best5GfxRect, baseUIColor);
Rectangle tachoRect = BaseGame.CalcRectangle1600(
10, 10, TachoGfxRect.Width, TachoGfxRect.Height);
tachoRect.X = BaseGame.Width-tachoRect.Right;
tachoRect.Y = BaseGame.Height-tachoRect.Bottom;
#endif
// Rest can stay the same because we use the rectangles from now on
ingame.RenderOnScreen(tachoRect, TachoGfxRect, baseUIColor);
// Ok, now add the numbers, text and speed values
TextureFontBigNumbers.WriteNumber(
lapsRect.X+BaseGame.XToRes1600(15),
lapsRect.Y+BaseGame.YToRes1200(12),
Math.Min(3, lapNumber));
// Current and best game times
Color highlightColor = new Color(255, 185, 80);
int blockHeight = BaseGame.YToRes1200(74);//59);
TextureFont.WriteGameTime(
timesRect.X+BaseGame.XToRes1600(154),
timesRect.Y + blockHeight / 2 - TextureFont.Height / 2,
currentGameTime,
highlightColor);
TextureFont.WriteGameTime(
timesRect.X+BaseGame.XToRes1600(154),
timesRect.Y + timesRect.Height / 2 + blockHeight / 2 -
TextureFont.Height / 2,
bestLapTime,
Color.White);
// Track name
TextureFont.WriteTextCentered(
trackNameRect.X+trackNameRect.Width/2,
trackNameRect.Y+blockHeight/2,
trackName);
// Top 5
// Possible improvement: Show currentRank here (insert us)
Color rankColor =
bestLapTime == top5LapTimes[0] ?
highlightColor : Color.White;
TextureFont.WriteTextCentered(
top5Rect1.X + BaseGame.XToRes(32) / 2,
top5Rect1.Y + blockHeight / 2,
"1.", rankColor, 1.0f);
TextureFont.WriteGameTime(
top5Rect1.X + BaseGame.XToRes(35 + 15),
top5Rect1.Y + blockHeight / 2 - TextureFont.Height / 2,
top5LapTimes[0], rankColor);
rankColor =
bestLapTime == top5LapTimes[1] ?
highlightColor : Color.White;
TextureFont.WriteTextCentered(
top5Rect2.X + BaseGame.XToRes(32) / 2,
top5Rect2.Y + blockHeight / 2,
"2.", rankColor, 1.0f);
TextureFont.WriteGameTime(
top5Rect2.X + BaseGame.XToRes(35 + 15),
top5Rect2.Y + blockHeight / 2 - TextureFont.Height / 2,
top5LapTimes[1], rankColor);
rankColor =
bestLapTime == top5LapTimes[2] ?
highlightColor : Color.White;
TextureFont.WriteTextCentered(
top5Rect3.X + BaseGame.XToRes(32) / 2,
top5Rect3.Y + blockHeight / 2,
"3.", rankColor, 1.0f);
TextureFont.WriteGameTime(
top5Rect3.X + BaseGame.XToRes(35 + 15),
top5Rect3.Y + blockHeight / 2 - TextureFont.Height / 2,
top5LapTimes[2], rankColor);
rankColor =
bestLapTime == top5LapTimes[3] ?
highlightColor : Color.White;
TextureFont.WriteTextCentered(
top5Rect4.X + BaseGame.XToRes(32) / 2,
top5Rect4.Y + blockHeight / 2,
"4.", rankColor, 1.0f);
TextureFont.WriteGameTime(
top5Rect4.X + BaseGame.XToRes(35 + 15),
top5Rect4.Y + blockHeight / 2 - TextureFont.Height / 2,
top5LapTimes[3], rankColor);
rankColor =
bestLapTime == top5LapTimes[4] ?
highlightColor : Color.White;
TextureFont.WriteTextCentered(
top5Rect5.X + BaseGame.XToRes(32) / 2,
top5Rect5.Y + blockHeight / 2,
"5.", rankColor, 1.0f);
TextureFont.WriteGameTime(
top5Rect5.X + BaseGame.XToRes(35 + 15),
top5Rect5.Y + blockHeight / 2 - TextureFont.Height / 2,
top5LapTimes[4], rankColor);
// Acceleration
Point tachoPoint = new Point(
tachoRect.X +
BaseGame.XToRes1600(194),
tachoRect.Y +
BaseGame.YToRes1200(194));
//ingame.RenderOnScreenWithRotation(
// tachoPoint, TachoArrowGfxRect, -acceleration*2);
if (acceleration < 0)
acceleration = 0;
if (acceleration > 1)
acceleration = 1;
float rotation = -2.33f + acceleration * 2.5f;
int tachoArrowWidth = BaseGame.XToRes1600(TachoArrowGfxRect.Width);
int tachoArrowHeight = BaseGame.YToRes1200(TachoArrowGfxRect.Height);
Vector2 rotationPoint = new Vector2(
TachoArrowGfxRect.Width / 2,
TachoArrowGfxRect.Height - 13);
ingame.RenderOnScreenWithRotation(
new Rectangle(tachoPoint.X, tachoPoint.Y,
tachoArrowWidth, tachoArrowHeight),
TachoArrowGfxRect,
rotation, rotationPoint);
// Speed in mph
TextureFontBigNumbers.WriteNumber(
tachoRect.X + BaseGame.XToRes1600(TachoMphGfxRect.X),
tachoRect.Y + BaseGame.YToRes1200(TachoMphGfxRect.Y),
TachoMphGfxRect.Height,
(int)Math.Round(speed));
// Gear
TextureFontBigNumbers.WriteNumber(
tachoRect.X + BaseGame.XToRes1600(TachoGearGfxRect.X),
tachoRect.Y + BaseGame.YToRes1200(TachoGearGfxRect.Y),
TachoGearGfxRect.Height,
Math.Min(5, gear));
} // RenderGameUI(currentGameTime, bestLapTime, lapNumber)
*/
#endregion
#region Render
bool showFps =
#if DEBUG
true;//false;//true;
#else
false;
#endif
/// <summary>
/// Render all UI elements at the end of the frame, will also
/// render the mouse cursor if we got a mouse attached.
///
/// Render all ui elements that we collected this frame.
/// Flush user interface graphics, this are mainly all
/// Texture.RenderOnScreen calls we made this frame so far.
/// Used in UIRenderer.RenderTextsAndMouseCursor, but can also be
/// called to force rendering UI at a specific point in the code.
/// </summary>
public static void Render(LineManager2D lineManager2D)
{
if (lineManager2D == null)
throw new ArgumentNullException("lineManager2D");
// Disable depth buffer for UI
BaseGame.Device.RenderState.DepthBufferEnable = false;
// Overwrite the vertex declaration to make sure we don't use
// the old format anymore.
BaseGame.Device.VertexDeclaration = TangentVertex.VertexDeclaration;
// Draw all sprites
SpriteHelper.DrawAllSprites();
// Render all 2d lines
lineManager2D.Render();
} // Render()
/// <summary>
/// Render texts and mouse cursor, which is done at the very end
/// of our render loop.
/// </summary>
public void RenderTextsAndMouseCursor()
{
// Show fps
if (Input.KeyboardF1JustPressed ||
// Also allow toggeling with gamepad
(Input.GamePad.Buttons.LeftShoulder == ButtonState.Pressed &&
Input.GamePadYJustPressed))
showFps = !showFps;
#if XBOX360
if (showFps)
TextureFont.WriteText(
BaseGame.XToRes(32), BaseGame.YToRes(26),
"Fps: " + BaseGame.Fps + " " +
BaseGame.Width + "x" + BaseGame.Height);
#else
if (showFps)
TextureFont.WriteText(2, 2, "Fps: "+BaseGame.Fps);
#endif
// Render font texts
RenderTimeFadeupEffects();
font.WriteAll();
// Render mouse
// For the xbox, there is no mouse support, don't show cursor!
if (Input.MouseDetected &&
// Also don't show cursor in game!
DungeonQuestGame.ShowMouseCursor)
{
// Use our SpriteHelper logic to render the mouse cursor now!
mouseCursor.RenderOnScreen(Input.MousePos);
SpriteHelper.DrawAllSprites();
} // if (Input.MouseDetected)
} // RenderTextsAndMouseCursor()
#endregion
} // class UIRenderer
} // namespace DungeonQuest.Graphics
| |
namespace Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1
{
partial class MainTabUserControl
{
/// <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 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(MainTabUserControl));
this.consoleToolBar1 = new Microsoft.HomeServer.Controls.ConsoleToolBar();
this.ClearToolBarButton = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.RefreshToolBarButton = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.QuarantineToolBarButton = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.ScanDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.ScanMemoryToolBarButton = new System.Windows.Forms.ToolStripMenuItem();
this.ScanToolBarButton = new System.Windows.Forms.ToolStripMenuItem();
this.ScanSharesToolBarButton = new System.Windows.Forms.ToolStripMenuItem();
this.userDefinedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.shareToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UpdateToolBarButton = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.StopToolBarButton = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.ClamScanStatusLabel = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.ClamUpdateStatusLabel = new Microsoft.HomeServer.Controls.ConsoleToolBarButton();
this.ScanLogUpdateTimer = new System.Windows.Forms.Timer(this.components);
this.UpdateLogUpdateTimer = new System.Windows.Forms.Timer(this.components);
this.CheckClamAVComponentStatusTimer = new System.Windows.Forms.Timer(this.components);
this.ClamWinVerTabPage = new System.Windows.Forms.TabPage();
this.VersionPropertyPageNonEditableTextBoxField = new Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField();
this.ConfigFileTabPage = new System.Windows.Forms.TabPage();
this.ConfigFilePropertyPageNonEditableTextBoxField = new Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField();
this.LogUpdateTabPage = new System.Windows.Forms.TabPage();
this.LogUpdatePropertyPageNonEditableTextBoxField = new Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField();
this.LogScanTabPage = new System.Windows.Forms.TabPage();
this.LogScanPropertyPageNonEditableTextBoxField = new Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField();
this.LogTabControl = new Microsoft.HomeServer.Controls.CustomTabControl();
this.ScanBackupToolBarButton = new System.Windows.Forms.ToolStripMenuItem();
this.consoleToolBar1.SuspendLayout();
this.ClamWinVerTabPage.SuspendLayout();
this.ConfigFileTabPage.SuspendLayout();
this.LogUpdateTabPage.SuspendLayout();
this.LogScanTabPage.SuspendLayout();
this.LogTabControl.SuspendLayout();
this.SuspendLayout();
//
// consoleToolBar1
//
this.consoleToolBar1.AutoSize = false;
this.consoleToolBar1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("consoleToolBar1.BackgroundImage")));
this.consoleToolBar1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.consoleToolBar1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.consoleToolBar1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ClearToolBarButton,
this.RefreshToolBarButton,
this.QuarantineToolBarButton,
this.ScanDropDownButton,
this.UpdateToolBarButton,
this.StopToolBarButton,
this.toolStripSeparator1,
this.ClamScanStatusLabel,
this.ClamUpdateStatusLabel});
this.consoleToolBar1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.consoleToolBar1.Location = new System.Drawing.Point(0, 0);
this.consoleToolBar1.Name = "consoleToolBar1";
this.consoleToolBar1.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.consoleToolBar1.Size = new System.Drawing.Size(982, 31);
this.consoleToolBar1.TabIndex = 5;
this.consoleToolBar1.Text = "consoleToolBar1";
//
// ClearToolBarButton
//
this.ClearToolBarButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.ClearToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.DefaultToolBarIcon;
this.ClearToolBarButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ClearToolBarButton.Name = "ClearToolBarButton";
this.ClearToolBarButton.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.ClearToolBarButton.Size = new System.Drawing.Size(72, 28);
this.ClearToolBarButton.Text = "&Clear";
this.ClearToolBarButton.ToolTipText = "Clear Selected Log File";
this.ClearToolBarButton.Click += new System.EventHandler(this.ClearToolBarButton_Click);
//
// RefreshToolBarButton
//
this.RefreshToolBarButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.RefreshToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.RefreshIcon;
this.RefreshToolBarButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.RefreshToolBarButton.Name = "RefreshToolBarButton";
this.RefreshToolBarButton.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.RefreshToolBarButton.Size = new System.Drawing.Size(85, 28);
this.RefreshToolBarButton.Text = "&Refresh";
this.RefreshToolBarButton.ToolTipText = "Refresh Selected Tab";
this.RefreshToolBarButton.Click += new System.EventHandler(this.RefreshToolBarButton_Click);
//
// QuarantineToolBarButton
//
this.QuarantineToolBarButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.QuarantineToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.Control;
this.QuarantineToolBarButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.QuarantineToolBarButton.Name = "QuarantineToolBarButton";
this.QuarantineToolBarButton.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.QuarantineToolBarButton.Size = new System.Drawing.Size(101, 28);
this.QuarantineToolBarButton.Text = "&Quarantine";
this.QuarantineToolBarButton.ToolTipText = "View The Anti Virus Quarantine";
this.QuarantineToolBarButton.Click += new System.EventHandler(this.QuarantineToolBarButton_Click);
//
// ScanDropDownButton
//
this.ScanDropDownButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ScanMemoryToolBarButton,
this.ScanToolBarButton,
this.ScanSharesToolBarButton,
this.ScanBackupToolBarButton,
this.userDefinedToolStripMenuItem,
this.shareToolStripMenuItem});
this.ScanDropDownButton.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.ScanDropDownButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.Scan;
this.ScanDropDownButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ScanDropDownButton.Name = "ScanDropDownButton";
this.ScanDropDownButton.Size = new System.Drawing.Size(71, 28);
this.ScanDropDownButton.Text = "&Scan...";
this.ScanDropDownButton.ToolTipText = "Scanning Options";
this.ScanDropDownButton.Click += new System.EventHandler(this.ScanDropDownButton_Click);
//
// ScanMemoryToolBarButton
//
this.ScanMemoryToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.ScanMem;
this.ScanMemoryToolBarButton.Name = "ScanMemoryToolBarButton";
this.ScanMemoryToolBarButton.Size = new System.Drawing.Size(152, 22);
this.ScanMemoryToolBarButton.Text = "&Memory";
this.ScanMemoryToolBarButton.ToolTipText = "Scan Memory For Viruses";
this.ScanMemoryToolBarButton.Click += new System.EventHandler(this.ScanMemoryToolBarButton_Click);
//
// ScanToolBarButton
//
this.ScanToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.Scan;
this.ScanToolBarButton.Name = "ScanToolBarButton";
this.ScanToolBarButton.Size = new System.Drawing.Size(152, 22);
this.ScanToolBarButton.Text = "&System";
this.ScanToolBarButton.ToolTipText = "Scan System Drive For Viruses";
this.ScanToolBarButton.Click += new System.EventHandler(this.ScanToolBarButton_Click);
//
// ScanSharesToolBarButton
//
this.ScanSharesToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.Scan;
this.ScanSharesToolBarButton.Name = "ScanSharesToolBarButton";
this.ScanSharesToolBarButton.Size = new System.Drawing.Size(152, 22);
this.ScanSharesToolBarButton.Text = "&Data";
this.ScanSharesToolBarButton.ToolTipText = "Scan Data Drive For Viruses";
this.ScanSharesToolBarButton.Click += new System.EventHandler(this.ScanSharesToolBarButton_Click);
//
// userDefinedToolStripMenuItem
//
this.userDefinedToolStripMenuItem.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.Scan;
this.userDefinedToolStripMenuItem.Name = "userDefinedToolStripMenuItem";
this.userDefinedToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.userDefinedToolStripMenuItem.Text = "&User Defined";
this.userDefinedToolStripMenuItem.Click += new System.EventHandler(this.userDefinedToolStripMenuItem_Click);
//
// shareToolStripMenuItem
//
this.shareToolStripMenuItem.Name = "shareToolStripMenuItem";
this.shareToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.shareToolStripMenuItem.Text = "Share";
//
// UpdateToolBarButton
//
this.UpdateToolBarButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.UpdateToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.World;
this.UpdateToolBarButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.UpdateToolBarButton.Name = "UpdateToolBarButton";
this.UpdateToolBarButton.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.UpdateToolBarButton.Size = new System.Drawing.Size(82, 28);
this.UpdateToolBarButton.Text = "&Update";
this.UpdateToolBarButton.ToolTipText = "Update Virus Definition Files";
this.UpdateToolBarButton.Click += new System.EventHandler(this.UpdateToolBarButton_Click);
//
// StopToolBarButton
//
this.StopToolBarButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.StopToolBarButton.Image = ((System.Drawing.Image)(resources.GetObject("StopToolBarButton.Image")));
this.StopToolBarButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.StopToolBarButton.Name = "StopToolBarButton";
this.StopToolBarButton.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.StopToolBarButton.Size = new System.Drawing.Size(69, 28);
this.StopToolBarButton.Text = "&Stop";
this.StopToolBarButton.ToolTipText = "Stop All ClamWin Processes";
this.StopToolBarButton.Click += new System.EventHandler(this.StopToolBarButton_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 31);
//
// ClamScanStatusLabel
//
this.ClamScanStatusLabel.Enabled = false;
this.ClamScanStatusLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.ClamScanStatusLabel.Image = ((System.Drawing.Image)(resources.GetObject("ClamScanStatusLabel.Image")));
this.ClamScanStatusLabel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ClamScanStatusLabel.Name = "ClamScanStatusLabel";
this.ClamScanStatusLabel.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.ClamScanStatusLabel.Size = new System.Drawing.Size(104, 28);
this.ClamScanStatusLabel.Text = "Scan Status";
this.ClamScanStatusLabel.ToolTipText = "Shows status of WHSClamAV Scanning";
this.ClamScanStatusLabel.Visible = false;
//
// ClamUpdateStatusLabel
//
this.ClamUpdateStatusLabel.Enabled = false;
this.ClamUpdateStatusLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(251)))), ((int)(((byte)(255)))));
this.ClamUpdateStatusLabel.Image = ((System.Drawing.Image)(resources.GetObject("ClamUpdateStatusLabel.Image")));
this.ClamUpdateStatusLabel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ClamUpdateStatusLabel.Name = "ClamUpdateStatusLabel";
this.ClamUpdateStatusLabel.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0);
this.ClamUpdateStatusLabel.Size = new System.Drawing.Size(116, 28);
this.ClamUpdateStatusLabel.Text = "Update Status";
this.ClamUpdateStatusLabel.ToolTipText = "Shows status of WHSClamAV Updater";
this.ClamUpdateStatusLabel.Visible = false;
//
// ScanLogUpdateTimer
//
this.ScanLogUpdateTimer.Interval = 333;
this.ScanLogUpdateTimer.Tick += new System.EventHandler(this.ScanLogUpdateTimer_Tick);
//
// UpdateLogUpdateTimer
//
this.UpdateLogUpdateTimer.Interval = 333;
this.UpdateLogUpdateTimer.Tick += new System.EventHandler(this.UpdateLogUpdateTimer_Tick);
//
// CheckClamAVComponentStatusTimer
//
this.CheckClamAVComponentStatusTimer.Enabled = true;
this.CheckClamAVComponentStatusTimer.Interval = 5000;
this.CheckClamAVComponentStatusTimer.Tick += new System.EventHandler(this.CheckClamAVComponentStatusTimer_Tick);
//
// ClamWinVerTabPage
//
this.ClamWinVerTabPage.Controls.Add(this.VersionPropertyPageNonEditableTextBoxField);
this.ClamWinVerTabPage.Location = new System.Drawing.Point(4, 22);
this.ClamWinVerTabPage.Name = "ClamWinVerTabPage";
this.ClamWinVerTabPage.Padding = new System.Windows.Forms.Padding(3);
this.ClamWinVerTabPage.Size = new System.Drawing.Size(974, 505);
this.ClamWinVerTabPage.TabIndex = 3;
this.ClamWinVerTabPage.Text = "Version";
this.ClamWinVerTabPage.UseVisualStyleBackColor = true;
//
// VersionPropertyPageNonEditableTextBoxField
//
this.VersionPropertyPageNonEditableTextBoxField.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.VersionPropertyPageNonEditableTextBoxField.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.VersionPropertyPageNonEditableTextBoxField.Dock = System.Windows.Forms.DockStyle.Fill;
this.VersionPropertyPageNonEditableTextBoxField.Font = new System.Drawing.Font("Tahoma", 8F);
this.VersionPropertyPageNonEditableTextBoxField.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.VersionPropertyPageNonEditableTextBoxField.Location = new System.Drawing.Point(3, 3);
this.VersionPropertyPageNonEditableTextBoxField.Multiline = true;
this.VersionPropertyPageNonEditableTextBoxField.Name = "VersionPropertyPageNonEditableTextBoxField";
this.VersionPropertyPageNonEditableTextBoxField.ReadOnly = true;
this.VersionPropertyPageNonEditableTextBoxField.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.VersionPropertyPageNonEditableTextBoxField.Size = new System.Drawing.Size(968, 499);
this.VersionPropertyPageNonEditableTextBoxField.TabIndex = 0;
//
// ConfigFileTabPage
//
this.ConfigFileTabPage.Controls.Add(this.ConfigFilePropertyPageNonEditableTextBoxField);
this.ConfigFileTabPage.Location = new System.Drawing.Point(4, 22);
this.ConfigFileTabPage.Name = "ConfigFileTabPage";
this.ConfigFileTabPage.Padding = new System.Windows.Forms.Padding(3);
this.ConfigFileTabPage.Size = new System.Drawing.Size(974, 505);
this.ConfigFileTabPage.TabIndex = 2;
this.ConfigFileTabPage.Text = "Config File";
this.ConfigFileTabPage.UseVisualStyleBackColor = true;
//
// ConfigFilePropertyPageNonEditableTextBoxField
//
this.ConfigFilePropertyPageNonEditableTextBoxField.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.ConfigFilePropertyPageNonEditableTextBoxField.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ConfigFilePropertyPageNonEditableTextBoxField.Dock = System.Windows.Forms.DockStyle.Fill;
this.ConfigFilePropertyPageNonEditableTextBoxField.Font = new System.Drawing.Font("Tahoma", 8F);
this.ConfigFilePropertyPageNonEditableTextBoxField.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.ConfigFilePropertyPageNonEditableTextBoxField.Location = new System.Drawing.Point(3, 3);
this.ConfigFilePropertyPageNonEditableTextBoxField.Multiline = true;
this.ConfigFilePropertyPageNonEditableTextBoxField.Name = "ConfigFilePropertyPageNonEditableTextBoxField";
this.ConfigFilePropertyPageNonEditableTextBoxField.ReadOnly = true;
this.ConfigFilePropertyPageNonEditableTextBoxField.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.ConfigFilePropertyPageNonEditableTextBoxField.Size = new System.Drawing.Size(968, 499);
this.ConfigFilePropertyPageNonEditableTextBoxField.TabIndex = 0;
//
// LogUpdateTabPage
//
this.LogUpdateTabPage.Controls.Add(this.LogUpdatePropertyPageNonEditableTextBoxField);
this.LogUpdateTabPage.Location = new System.Drawing.Point(4, 22);
this.LogUpdateTabPage.Name = "LogUpdateTabPage";
this.LogUpdateTabPage.Padding = new System.Windows.Forms.Padding(3);
this.LogUpdateTabPage.Size = new System.Drawing.Size(974, 505);
this.LogUpdateTabPage.TabIndex = 1;
this.LogUpdateTabPage.Text = "Update Log";
this.LogUpdateTabPage.UseVisualStyleBackColor = true;
//
// LogUpdatePropertyPageNonEditableTextBoxField
//
this.LogUpdatePropertyPageNonEditableTextBoxField.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.LogUpdatePropertyPageNonEditableTextBoxField.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.LogUpdatePropertyPageNonEditableTextBoxField.Dock = System.Windows.Forms.DockStyle.Fill;
this.LogUpdatePropertyPageNonEditableTextBoxField.Font = new System.Drawing.Font("Tahoma", 8F);
this.LogUpdatePropertyPageNonEditableTextBoxField.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.LogUpdatePropertyPageNonEditableTextBoxField.Location = new System.Drawing.Point(3, 3);
this.LogUpdatePropertyPageNonEditableTextBoxField.Multiline = true;
this.LogUpdatePropertyPageNonEditableTextBoxField.Name = "LogUpdatePropertyPageNonEditableTextBoxField";
this.LogUpdatePropertyPageNonEditableTextBoxField.ReadOnly = true;
this.LogUpdatePropertyPageNonEditableTextBoxField.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.LogUpdatePropertyPageNonEditableTextBoxField.Size = new System.Drawing.Size(968, 499);
this.LogUpdatePropertyPageNonEditableTextBoxField.TabIndex = 1;
//
// LogScanTabPage
//
this.LogScanTabPage.Controls.Add(this.LogScanPropertyPageNonEditableTextBoxField);
this.LogScanTabPage.Location = new System.Drawing.Point(4, 22);
this.LogScanTabPage.Name = "LogScanTabPage";
this.LogScanTabPage.Padding = new System.Windows.Forms.Padding(3);
this.LogScanTabPage.Size = new System.Drawing.Size(974, 505);
this.LogScanTabPage.TabIndex = 0;
this.LogScanTabPage.Text = "Scanning Log";
this.LogScanTabPage.UseVisualStyleBackColor = true;
//
// LogScanPropertyPageNonEditableTextBoxField
//
this.LogScanPropertyPageNonEditableTextBoxField.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.LogScanPropertyPageNonEditableTextBoxField.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.LogScanPropertyPageNonEditableTextBoxField.Dock = System.Windows.Forms.DockStyle.Fill;
this.LogScanPropertyPageNonEditableTextBoxField.Font = new System.Drawing.Font("Tahoma", 8F);
this.LogScanPropertyPageNonEditableTextBoxField.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.LogScanPropertyPageNonEditableTextBoxField.Location = new System.Drawing.Point(3, 3);
this.LogScanPropertyPageNonEditableTextBoxField.Multiline = true;
this.LogScanPropertyPageNonEditableTextBoxField.Name = "LogScanPropertyPageNonEditableTextBoxField";
this.LogScanPropertyPageNonEditableTextBoxField.ReadOnly = true;
this.LogScanPropertyPageNonEditableTextBoxField.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.LogScanPropertyPageNonEditableTextBoxField.Size = new System.Drawing.Size(968, 499);
this.LogScanPropertyPageNonEditableTextBoxField.TabIndex = 0;
this.LogScanPropertyPageNonEditableTextBoxField.TextChanged += new System.EventHandler(this.LogScanPropertyPageNonEditableTextBoxField_TextChanged);
//
// LogTabControl
//
this.LogTabControl.Controls.Add(this.LogScanTabPage);
this.LogTabControl.Controls.Add(this.LogUpdateTabPage);
this.LogTabControl.Controls.Add(this.ConfigFileTabPage);
this.LogTabControl.Controls.Add(this.ClamWinVerTabPage);
this.LogTabControl.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed;
this.LogTabControl.HeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
this.LogTabControl.HeaderFont = new System.Drawing.Font("Tahoma", 8F);
this.LogTabControl.HeaderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.LogTabControl.Location = new System.Drawing.Point(0, 34);
this.LogTabControl.Name = "LogTabControl";
this.LogTabControl.SelectedIndex = 0;
this.LogTabControl.Size = new System.Drawing.Size(982, 531);
this.LogTabControl.TabHeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(235)))), ((int)(((byte)(243)))));
this.LogTabControl.TabIndex = 6;
this.LogTabControl.SelectedIndexChanged += new System.EventHandler(this.LogTabControl_SelectedIndexChanged);
//
// ScanBackupToolBarButton
//
this.ScanBackupToolBarButton.Image = global::Microsoft.HomeServer.HomeServerConsoleTab.Home_Server_Add_In1.Properties.Resources.Scan;
this.ScanBackupToolBarButton.Name = "ScanBackupToolBarButton";
this.ScanBackupToolBarButton.Size = new System.Drawing.Size(152, 22);
this.ScanBackupToolBarButton.Text = "&Backup";
this.ScanBackupToolBarButton.Click += new System.EventHandler(this.ScanBackupToolBarButton_Click);
//
// MainTabUserControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.LogTabControl);
this.Controls.Add(this.consoleToolBar1);
this.Name = "MainTabUserControl";
this.Size = new System.Drawing.Size(982, 565);
this.Load += new System.EventHandler(this.MainTabUserControl_Load);
this.consoleToolBar1.ResumeLayout(false);
this.consoleToolBar1.PerformLayout();
this.ClamWinVerTabPage.ResumeLayout(false);
this.ClamWinVerTabPage.PerformLayout();
this.ConfigFileTabPage.ResumeLayout(false);
this.ConfigFileTabPage.PerformLayout();
this.LogUpdateTabPage.ResumeLayout(false);
this.LogUpdateTabPage.PerformLayout();
this.LogScanTabPage.ResumeLayout(false);
this.LogScanTabPage.PerformLayout();
this.LogTabControl.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Microsoft.HomeServer.Controls.ConsoleToolBar consoleToolBar1;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton ClearToolBarButton;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton RefreshToolBarButton;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton QuarantineToolBarButton;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton UpdateToolBarButton;
private System.Windows.Forms.Timer ScanLogUpdateTimer;
private System.Windows.Forms.Timer UpdateLogUpdateTimer;
private System.Windows.Forms.Timer CheckClamAVComponentStatusTimer;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton StopToolBarButton;
private System.Windows.Forms.ToolStripDropDownButton ScanDropDownButton;
private System.Windows.Forms.ToolStripMenuItem ScanMemoryToolBarButton;
private System.Windows.Forms.ToolStripMenuItem ScanToolBarButton;
private System.Windows.Forms.ToolStripMenuItem ScanSharesToolBarButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton ClamScanStatusLabel;
private Microsoft.HomeServer.Controls.ConsoleToolBarButton ClamUpdateStatusLabel;
private System.Windows.Forms.ToolStripMenuItem userDefinedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem shareToolStripMenuItem;
private System.Windows.Forms.TabPage ClamWinVerTabPage;
private Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField VersionPropertyPageNonEditableTextBoxField;
private System.Windows.Forms.TabPage ConfigFileTabPage;
private Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField ConfigFilePropertyPageNonEditableTextBoxField;
private System.Windows.Forms.TabPage LogUpdateTabPage;
private Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField LogUpdatePropertyPageNonEditableTextBoxField;
private System.Windows.Forms.TabPage LogScanTabPage;
private Microsoft.HomeServer.Controls.PropertyPageNonEditableTextBoxField LogScanPropertyPageNonEditableTextBoxField;
private Microsoft.HomeServer.Controls.CustomTabControl LogTabControl;
private System.Windows.Forms.ToolStripMenuItem ScanBackupToolBarButton;
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// PkcsUtils.cs
//
namespace System.Security.Cryptography.Pkcs {
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Runtime.Versioning;
internal static class PkcsUtils {
private static volatile int m_cmsSupported = -1;
private struct I_CRYPT_ATTRIBUTE {
internal IntPtr pszObjId;
internal uint cValue;
internal IntPtr rgValue; // PCRYPT_ATTR_BLOB
}
internal static uint AlignedLength (uint length) {
return ((length + (uint) 7) & ((uint) 0xfffffff8));
}
[SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal static bool CmsSupported () {
if (m_cmsSupported == -1) {
using(SafeLibraryHandle hModule = CAPI.CAPISafe.LoadLibrary("Crypt32.dll")) {
if (!hModule.IsInvalid) {
IntPtr pFunc = CAPI.CAPISafe.GetProcAddress(hModule, "CryptMsgVerifyCountersignatureEncodedEx");
m_cmsSupported = pFunc == IntPtr.Zero ? 0 : 1;
}
}
}
return m_cmsSupported == 0 ? false : true;
}
[SecuritySafeCritical]
internal static RecipientInfoType GetRecipientInfoType (X509Certificate2 certificate) {
RecipientInfoType recipientInfoType = RecipientInfoType.Unknown;
if (certificate != null) {
CAPI.CERT_CONTEXT pCertContext = (CAPI.CERT_CONTEXT) Marshal.PtrToStructure(X509Utils.GetCertContext(certificate).DangerousGetHandle(), typeof(CAPI.CERT_CONTEXT));
CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));
uint algId = X509Utils.OidToAlgId(certInfo.SubjectPublicKeyInfo.Algorithm.pszObjId);
if (algId == CAPI.CALG_RSA_KEYX)
recipientInfoType = RecipientInfoType.KeyTransport;
else if (algId == CAPI.CALG_DH_SF || algId == CAPI.CALG_DH_EPHEM)
recipientInfoType = RecipientInfoType.KeyAgreement;
else
recipientInfoType = RecipientInfoType.Unknown;
}
return recipientInfoType;
}
[SecurityCritical]
internal static unsafe int GetMaxKeyLength (SafeCryptProvHandle safeCryptProvHandle, uint algId) {
uint enumFlag = CAPI.CRYPT_FIRST;
uint cbPeex = (uint) Marshal.SizeOf(typeof(CAPI.PROV_ENUMALGS_EX));
SafeLocalAllocHandle pPeex = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.PROV_ENUMALGS_EX))));
using (pPeex) {
while (CAPI.CAPISafe.CryptGetProvParam(safeCryptProvHandle, CAPI.PP_ENUMALGS_EX, pPeex.DangerousGetHandle(), new IntPtr(&cbPeex), enumFlag)) {
CAPI.PROV_ENUMALGS_EX peex = (CAPI.PROV_ENUMALGS_EX) Marshal.PtrToStructure(pPeex.DangerousGetHandle(), typeof(CAPI.PROV_ENUMALGS_EX));
if (peex.aiAlgid == algId)
return (int) peex.dwMaxLen;
enumFlag = 0;
}
}
throw new CryptographicException(CAPI.CRYPT_E_UNKNOWN_ALGO);
}
[SecurityCritical]
internal static unsafe uint GetVersion (SafeCryptMsgHandle safeCryptMsgHandle) {
uint dwVersion = 0;
uint cbCount = (uint) Marshal.SizeOf(typeof(uint));
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_VERSION_PARAM,
0,
new IntPtr(&dwVersion),
new IntPtr(&cbCount)))
checkErr(Marshal.GetLastWin32Error());
return dwVersion;
}
[SecurityCritical]
internal static unsafe uint GetMessageType (SafeCryptMsgHandle safeCryptMsgHandle) {
uint dwMsgType = 0;
uint cbMsgType = (uint) Marshal.SizeOf(typeof(uint));
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_TYPE_PARAM,
0,
new IntPtr(&dwMsgType),
new IntPtr(&cbMsgType)))
checkErr(Marshal.GetLastWin32Error());
return dwMsgType;
}
[SecurityCritical]
internal static unsafe AlgorithmIdentifier GetAlgorithmIdentifier (SafeCryptMsgHandle safeCryptMsgHandle) {
AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier();
uint cbAlgorithm = 0;
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_ENVELOPE_ALGORITHM_PARAM,
0,
IntPtr.Zero,
new IntPtr(&cbAlgorithm)))
checkErr(Marshal.GetLastWin32Error());
if (cbAlgorithm > 0) {
SafeLocalAllocHandle pbAlgorithm = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbAlgorithm));
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_ENVELOPE_ALGORITHM_PARAM,
0,
pbAlgorithm,
new IntPtr(&cbAlgorithm)))
checkErr(Marshal.GetLastWin32Error());
CAPI.CRYPT_ALGORITHM_IDENTIFIER cryptAlgorithmIdentifier = (CAPI.CRYPT_ALGORITHM_IDENTIFIER) Marshal.PtrToStructure(pbAlgorithm.DangerousGetHandle(), typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER));
algorithmIdentifier = new AlgorithmIdentifier(cryptAlgorithmIdentifier);
pbAlgorithm.Dispose();
}
return algorithmIdentifier;
}
[SecurityCritical]
internal static unsafe void GetParam (SafeCryptMsgHandle safeCryptMsgHandle,
uint paramType,
uint index,
out SafeLocalAllocHandle pvData,
out uint cbData) {
cbData = 0;
pvData = SafeLocalAllocHandle.InvalidHandle;
fixed (uint * pcbData = &cbData) {
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
paramType,
index,
pvData,
new IntPtr(pcbData)))
checkErr(Marshal.GetLastWin32Error());
if (cbData > 0) {
pvData = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(cbData));
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
paramType,
index,
pvData,
new IntPtr(pcbData)))
checkErr(Marshal.GetLastWin32Error());
}
}
}
[SecurityCritical]
internal static unsafe void GetParam (SafeCryptMsgHandle safeCryptMsgHandle,
uint paramType,
uint index,
out byte[] pvData,
out uint cbData) {
cbData = 0;
pvData = new byte[0];
fixed (uint * pcbData = &cbData) {
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
paramType,
index,
IntPtr.Zero,
new IntPtr(pcbData)))
checkErr(Marshal.GetLastWin32Error());
if (cbData > 0) {
pvData = new byte[cbData];
fixed (byte * ppvData = &pvData[0]) {
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
paramType,
index,
new IntPtr(ppvData),
new IntPtr(pcbData)))
checkErr(Marshal.GetLastWin32Error());
}
}
}
}
[SecurityCritical]
internal static unsafe X509Certificate2Collection GetCertificates (SafeCryptMsgHandle safeCryptMsgHandle) {
uint dwCount = 0;
uint cbCount = (uint) Marshal.SizeOf(typeof(uint));
X509Certificate2Collection certificates = new X509Certificate2Collection();
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_CERT_COUNT_PARAM,
0,
new IntPtr(&dwCount),
new IntPtr(&cbCount)))
checkErr(Marshal.GetLastWin32Error());
for (uint index = 0; index < dwCount; index++) {
uint cbEncoded = 0;
SafeLocalAllocHandle pbEncoded = SafeLocalAllocHandle.InvalidHandle;
GetParam(safeCryptMsgHandle, CAPI.CMSG_CERT_PARAM, index, out pbEncoded, out cbEncoded);
if (cbEncoded > 0) {
SafeCertContextHandle safeCertContextHandle = CAPI.CAPISafe.CertCreateCertificateContext(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
pbEncoded,
cbEncoded);
if (safeCertContextHandle == null || safeCertContextHandle.IsInvalid)
throw new CryptographicException(Marshal.GetLastWin32Error());
certificates.Add(new X509Certificate2(safeCertContextHandle.DangerousGetHandle()));
safeCertContextHandle.Dispose();
}
}
return certificates;
}
[SecurityCritical]
internal static byte[] GetContent (SafeCryptMsgHandle safeCryptMsgHandle) {
uint cbContent = 0;
byte[] content = new byte[0];
GetParam(safeCryptMsgHandle, CAPI.CMSG_CONTENT_PARAM, 0, out content, out cbContent);
return content;
}
[SecurityCritical]
internal static Oid GetContentType (SafeCryptMsgHandle safeCryptMsgHandle) {
uint cbContentType = 0;
byte[] contentType = new byte[0];
GetParam(safeCryptMsgHandle, CAPI.CMSG_INNER_CONTENT_TYPE_PARAM, 0, out contentType, out cbContentType);
if (contentType.Length > 0 && contentType[contentType.Length - 1] == 0) {
byte[] temp = new byte[contentType.Length - 1];
Array.Copy(contentType, 0, temp, 0, temp.Length);
contentType = temp;
}
return new Oid(Encoding.ASCII.GetString(contentType));
}
[SecurityCritical]
internal static byte[] GetMessage (SafeCryptMsgHandle safeCryptMsgHandle) {
uint cbMessage = 0;
byte[] message = new byte[0];
GetParam(safeCryptMsgHandle, CAPI.CMSG_ENCODED_MESSAGE, 0, out message, out cbMessage);
return message;
}
[SecurityCritical]
internal static unsafe int GetSignerIndex (SafeCryptMsgHandle safeCrytpMsgHandle, SignerInfo signerInfo, int startIndex) {
uint dwSigners = 0;
uint cbCount = (uint) Marshal.SizeOf(typeof(uint));
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle,
CAPI.CMSG_SIGNER_COUNT_PARAM,
0,
new IntPtr(&dwSigners),
new IntPtr(&cbCount)))
checkErr(Marshal.GetLastWin32Error());
for (int index = startIndex; index < (int) dwSigners; index++) {
uint cbCmsgSignerInfo = 0;
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle,
CAPI.CMSG_SIGNER_INFO_PARAM,
(uint)index,
IntPtr.Zero,
new IntPtr(&cbCmsgSignerInfo)))
checkErr(Marshal.GetLastWin32Error());
if (cbCmsgSignerInfo > 0) {
SafeLocalAllocHandle pbCmsgSignerInfo = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbCmsgSignerInfo));
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle,
CAPI.CMSG_SIGNER_INFO_PARAM,
(uint)index,
pbCmsgSignerInfo,
new IntPtr(&cbCmsgSignerInfo)))
checkErr(Marshal.GetLastWin32Error());
CAPI.CMSG_SIGNER_INFO cmsgSignerInfo1 = signerInfo.GetCmsgSignerInfo();
CAPI.CMSG_SIGNER_INFO cmsgSignerInfo2 = (CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
if (X509Utils.MemEqual((byte *) cmsgSignerInfo1.Issuer.pbData,
cmsgSignerInfo1.Issuer.cbData,
(byte *) cmsgSignerInfo2.Issuer.pbData,
cmsgSignerInfo2.Issuer.cbData) &&
X509Utils.MemEqual((byte *) cmsgSignerInfo1.SerialNumber.pbData,
cmsgSignerInfo1.SerialNumber.cbData,
(byte *) cmsgSignerInfo2.SerialNumber.pbData,
cmsgSignerInfo2.SerialNumber.cbData)) {
return index; // Signer's index is found.
}
// Keep alive.
pbCmsgSignerInfo.Dispose();
}
}
throw new CryptographicException(CAPI.CRYPT_E_SIGNER_NOT_FOUND);
}
[SecurityCritical]
internal static unsafe CryptographicAttributeObjectCollection GetUnprotectedAttributes (SafeCryptMsgHandle safeCryptMsgHandle) {
uint cbUnprotectedAttr = 0;
CryptographicAttributeObjectCollection attributes = new CryptographicAttributeObjectCollection();
SafeLocalAllocHandle pbUnprotectedAttr = SafeLocalAllocHandle.InvalidHandle;
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_UNPROTECTED_ATTR_PARAM,
0,
pbUnprotectedAttr,
new IntPtr(&cbUnprotectedAttr))) {
int lastWin32Error = Marshal.GetLastWin32Error();
if (lastWin32Error != CAPI.CRYPT_E_ATTRIBUTES_MISSING)
checkErr(Marshal.GetLastWin32Error());
}
if (cbUnprotectedAttr > 0) {
using (pbUnprotectedAttr = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(cbUnprotectedAttr))) {
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_UNPROTECTED_ATTR_PARAM,
0,
pbUnprotectedAttr,
new IntPtr(&cbUnprotectedAttr)))
checkErr(Marshal.GetLastWin32Error());
attributes = new CryptographicAttributeObjectCollection(pbUnprotectedAttr);
}
}
return attributes;
}
[SecurityCritical]
internal unsafe static X509IssuerSerial DecodeIssuerSerial (CAPI.CERT_ISSUER_SERIAL_NUMBER pIssuerAndSerial) {
SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle;
uint cbSize = CAPI.CAPISafe.CertNameToStrW(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
new IntPtr(&pIssuerAndSerial.Issuer),
CAPI.CERT_X500_NAME_STR | CAPI.CERT_NAME_STR_REVERSE_FLAG,
ptr,
0);
if (cbSize <= 1) // The API actually return 1 when It fails; which is not what the documentation says.
throw new CryptographicException(Marshal.GetLastWin32Error());
ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(checked(2 * cbSize)));
cbSize = CAPI.CAPISafe.CertNameToStrW(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
new IntPtr(&pIssuerAndSerial.Issuer),
CAPI.CERT_X500_NAME_STR | CAPI.CERT_NAME_STR_REVERSE_FLAG,
ptr,
cbSize);
if (cbSize <= 1)
throw new CryptographicException(Marshal.GetLastWin32Error());
X509IssuerSerial issuerSerial = new X509IssuerSerial();
issuerSerial.IssuerName = Marshal.PtrToStringUni(ptr.DangerousGetHandle());
byte[] serial = new byte[pIssuerAndSerial.SerialNumber.cbData];
Marshal.Copy(pIssuerAndSerial.SerialNumber.pbData, serial, 0, serial.Length);
issuerSerial.SerialNumber = X509Utils.EncodeHexStringFromInt(serial);
ptr.Dispose();
return issuerSerial;
}
[SecuritySafeCritical]
internal static string DecodeOctetString (byte[] encodedOctetString) {
uint cbDecoded = 0;
SafeLocalAllocHandle pbDecoded = null;
if (!CAPI.DecodeObject(new IntPtr(CAPI.X509_OCTET_STRING),
encodedOctetString,
out pbDecoded,
out cbDecoded))
throw new CryptographicException(Marshal.GetLastWin32Error());
if (cbDecoded == 0)
return String.Empty;
CAPI.CRYPTOAPI_BLOB decodedBlob = (CAPI.CRYPTOAPI_BLOB) Marshal.PtrToStructure(pbDecoded.DangerousGetHandle(), typeof(CAPI.CRYPTOAPI_BLOB));
if (decodedBlob.cbData == 0)
return String.Empty;
string octetString = Marshal.PtrToStringUni(decodedBlob.pbData);
pbDecoded.Dispose();
return octetString;
}
[SecuritySafeCritical]
internal static byte[] DecodeOctetBytes (byte[] encodedOctetString) {
uint cbDecoded = 0;
SafeLocalAllocHandle pbDecoded = null;
if (!CAPI.DecodeObject(new IntPtr(CAPI.X509_OCTET_STRING),
encodedOctetString,
out pbDecoded,
out cbDecoded))
throw new CryptographicException(Marshal.GetLastWin32Error());
if (cbDecoded == 0)
return new byte[0];
using (pbDecoded) {
return CAPI.BlobToByteArray(pbDecoded.DangerousGetHandle());
}
}
internal static byte[] EncodeOctetString (string octetString) {
// Marshal data to be encoded to unmanaged memory.
byte[] octets = new byte[2 * (octetString.Length + 1)];
Encoding.Unicode.GetBytes(octetString, 0, octetString.Length, octets, 0);
return EncodeOctetString(octets);
}
[SecuritySafeCritical]
internal static unsafe byte[] EncodeOctetString (byte[] octets) {
fixed (byte * pbOctets = octets) {
CAPI.CRYPTOAPI_BLOB octetsBlob = new CAPI.CRYPTOAPI_BLOB();
octetsBlob.cbData = (uint) octets.Length;
octetsBlob.pbData = new IntPtr(pbOctets);
// Encode data.
byte[] encodedOctets = new byte[0];
if (!CAPI.EncodeObject(new IntPtr((long) CAPI.X509_OCTET_STRING),
new IntPtr((long) &octetsBlob),
out encodedOctets)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return encodedOctets;
}
}
internal static string DecodeObjectIdentifier (byte[] encodedObjId, int offset) {
StringBuilder objId = new StringBuilder("");
if (0 < (encodedObjId.Length - offset)) {
byte b = encodedObjId[offset];
byte c = (byte) ((uint) b / 40);
objId.Append(c.ToString(null, null));
objId.Append(".");
c = (byte) ((uint) b % 40);
objId.Append(c.ToString(null, null));
ulong s = 0;
for (int index = offset + 1; index < encodedObjId.Length; index++) {
c = encodedObjId[index];
s = (s << 7) + (ulong) (c & 0x7f);
if (0 == (c & 0x80)) {
objId.Append(".");
objId.Append(s.ToString(null, null));
s = 0;
}
}
// s should be 0 at this point, otherwise we have a bad ASN.
if (0 != s) {
throw new CryptographicException(CAPI.CRYPT_E_BAD_ENCODE);
}
}
return objId.ToString();
}
internal static CmsRecipientCollection SelectRecipients (SubjectIdentifierType recipientIdentifierType) {
X509Store store = new X509Store("AddressBook");
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection certificates = new X509Certificate2Collection(store.Certificates);
foreach (X509Certificate2 certificate in store.Certificates) {
if (certificate.NotBefore <= DateTime.Now && certificate.NotAfter >= DateTime.Now) {
bool validUsages = true;
foreach (X509Extension extension in certificate.Extensions) {
if (String.Compare(extension.Oid.Value, CAPI.szOID_KEY_USAGE, StringComparison.OrdinalIgnoreCase) == 0) {
X509KeyUsageExtension keyUsage = new X509KeyUsageExtension();
keyUsage.CopyFrom(extension);
if ((keyUsage.KeyUsages & X509KeyUsageFlags.KeyEncipherment) == 0 &&
(keyUsage.KeyUsages & X509KeyUsageFlags.KeyAgreement) == 0) {
validUsages = false;
}
break;
}
}
if (validUsages) {
certificates.Add(certificate);
}
}
}
if (certificates.Count < 1)
throw new CryptographicException(CAPI.CRYPT_E_RECIPIENT_NOT_FOUND);
X509Certificate2Collection recipients = X509Certificate2UI.SelectFromCollection(certificates, null, null, X509SelectionFlag.MultiSelection);
if (recipients.Count < 1)
throw new CryptographicException(CAPI.ERROR_CANCELLED);
return new CmsRecipientCollection(recipientIdentifierType, recipients);
}
internal static X509Certificate2 SelectSignerCertificate () {
X509Store store = new X509Store();
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly | OpenFlags.IncludeArchived);
X509Certificate2Collection certificates = new X509Certificate2Collection();
foreach (X509Certificate2 certificate in store.Certificates) {
if (certificate.HasPrivateKey && certificate.NotBefore <= DateTime.Now && certificate.NotAfter >= DateTime.Now) {
bool validUsages = true;
foreach (X509Extension extension in certificate.Extensions) {
if (String.Compare(extension.Oid.Value, CAPI.szOID_KEY_USAGE, StringComparison.OrdinalIgnoreCase) == 0) {
X509KeyUsageExtension keyUsage = new X509KeyUsageExtension();
keyUsage.CopyFrom(extension);
if ((keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) == 0 &&
(keyUsage.KeyUsages & X509KeyUsageFlags.NonRepudiation) == 0) {
validUsages = false;
}
break;
}
}
if (validUsages) {
certificates.Add(certificate);
}
}
}
if (certificates.Count < 1)
throw new CryptographicException(CAPI.CRYPT_E_SIGNER_NOT_FOUND);
certificates = X509Certificate2UI.SelectFromCollection(certificates, null, null, X509SelectionFlag.SingleSelection);
if (certificates.Count < 1)
throw new CryptographicException(CAPI.ERROR_CANCELLED);
Debug.Assert(certificates.Count == 1);
return certificates[0];
}
[SecuritySafeCritical]
internal static AsnEncodedDataCollection GetAsnEncodedDataCollection (CAPI.CRYPT_ATTRIBUTE cryptAttribute) {
AsnEncodedDataCollection list = new AsnEncodedDataCollection();
Oid oid = new Oid(cryptAttribute.pszObjId);
string szOid = oid.Value;
for (uint index = 0; index < cryptAttribute.cValue; index++) {
checked {
IntPtr pAttributeBlob = new IntPtr((long)cryptAttribute.rgValue + (index * Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB))));
Pkcs9AttributeObject attribute = new Pkcs9AttributeObject(oid, CAPI.BlobToByteArray(pAttributeBlob));
Pkcs9AttributeObject customAttribute = CryptoConfig.CreateFromName(szOid) as Pkcs9AttributeObject;
if (customAttribute != null) {
customAttribute.CopyFrom(attribute);
attribute = customAttribute;
}
list.Add(attribute);
}
}
return list;
}
[SecurityCritical]
internal static AsnEncodedDataCollection GetAsnEncodedDataCollection (CAPI.CRYPT_ATTRIBUTE_TYPE_VALUE cryptAttribute) {
AsnEncodedDataCollection list = new AsnEncodedDataCollection();
list.Add(new Pkcs9AttributeObject(new Oid(cryptAttribute.pszObjId), CAPI.BlobToByteArray(cryptAttribute.Value)));
return list;
}
[SecurityCritical]
internal static unsafe IntPtr CreateCryptAttributes (CryptographicAttributeObjectCollection attributes) {
attributes = attributes.DeepCopy();
// NULL if no attribute.
if (attributes.Count == 0)
return IntPtr.Zero;
//
// The goal here is to compute the size needed for the attributes we are passing to CMSG_SIGNER_ENCODE_INFO
// The unmanaged memory structure we are creating here has the following layout:
//
// Let cAttr = number of attributes.
//
// This to create the array of CRYPT_ATTRIBUTE
// for i = 0 to cAttr {
// CRYPT_ATTRRIBUTE[i] // pszObjId | cValue | rgValue
// }
//
// This is to fill in the data for each entry of CRYPT_ATTRIBUTE array above.
// for i = 0 to cAttr {
// objId[i] // Value of the Oid, i.e "1.2.3.4"
// for j = 0 to CRYPT_ATTRIBUTE[i].cValue - 1 { // Array of CRYPTOAPI_BLOB
// CRYPT_ATTRIBUTE[i].rgValue[j].cbData // Data size
// CRYPT_ATTRIBUTE[i].rgValue[j].pbData // Pointer to data
// }
// for j = 0 to CRYPT_ATTRIBUTE[i].cValue - 1 { // Data for each entry of the CRYPTOAPI_BLOB array above.
// *CRYPT_ATTRIBUTE[i].rgValue[j].pbData // The actual data
// }
// }
checked {
uint totalLength = 0;
uint cryptAttrSize = AlignedLength((uint) Marshal.SizeOf(typeof(I_CRYPT_ATTRIBUTE)));
uint cryptBlobSize = AlignedLength((uint) Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB)));
// First compute the total serialized unmanaged memory size needed.
// For each attribute, we add the CRYPT_ATTRIBUTE size, the size
// needed for the ObjId, and the size needed for all the values
// inside each attribute which is computed in inner loop.
foreach (CryptographicAttributeObject attribute in attributes) {
totalLength += cryptAttrSize; // sizeof(CRYPT_ATTRIBUTE)
totalLength += AlignedLength((uint) (attribute.Oid.Value.Length + 1)); // strlen(pszObjId) + 1
// For each value within the attribute, we add the CRYPT_ATTR_BLOB size and
// the actual size needed for the data.
foreach (AsnEncodedData attributeValue in attribute.Values) {
totalLength += cryptBlobSize; // Add CRYPT_ATTR_BLOB size
totalLength += AlignedLength((uint) attributeValue.RawData.Length); // Data size
}
}
// Allocate the unmanaged memory blob to hold the entire serialized CRYPT_ATTRIBUTE array.
SafeLocalAllocHandle pCryptAttributes = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(totalLength));
// Now fill up unmanaged memory with data from the managed side.
I_CRYPT_ATTRIBUTE * pCryptAttribute = (I_CRYPT_ATTRIBUTE *) pCryptAttributes.DangerousGetHandle();
IntPtr pAttrData = new IntPtr((long) pCryptAttributes.DangerousGetHandle() + (cryptAttrSize * attributes.Count));
foreach (CryptographicAttributeObject attribute in attributes) {
byte * pszObjId = (byte *) pAttrData;
byte[] objId = new byte[attribute.Oid.Value.Length + 1];
CAPI.CRYPTOAPI_BLOB * pDataBlob = (CAPI.CRYPTOAPI_BLOB *) (pszObjId + AlignedLength((uint) objId.Length));
// CRYPT_ATTRIBUTE.pszObjId
pCryptAttribute->pszObjId = (IntPtr) pszObjId;
// CRYPT_ATTRIBUTE.cValue
pCryptAttribute->cValue = (uint) attribute.Values.Count;
// CRYPT_ATTRIBUTE.rgValue
pCryptAttribute->rgValue = (IntPtr) pDataBlob;
// ObjId - The actual dotted value of the OID.
Encoding.ASCII.GetBytes(attribute.Oid.Value, 0, attribute.Oid.Value.Length, objId, 0);
Marshal.Copy(objId, 0, pCryptAttribute->pszObjId, objId.Length);
// cValue of CRYPT_ATTR_BLOBs followed by cValue of actual data.
IntPtr pbEncodedData = new IntPtr((long) pDataBlob + (attribute.Values.Count * cryptBlobSize));
foreach (AsnEncodedData value in attribute.Values) {
// Retrieve encoded data.
byte[] encodedData = value.RawData;
// Write data
if (encodedData.Length > 0) {
// CRYPT_ATTR_BLOB.cbData
pDataBlob->cbData = (uint) encodedData.Length;
// CRYPT_ATTR_BLOB.pbData
pDataBlob->pbData = pbEncodedData;
Marshal.Copy(encodedData, 0, pbEncodedData, encodedData.Length);
pbEncodedData = new IntPtr((long) pbEncodedData + AlignedLength((uint) encodedData.Length));
}
// Advance pointer.
pDataBlob++;
}
// Advance pointers.
pCryptAttribute++;
pAttrData = pbEncodedData;
}
// Since we are returning IntPtr, we MUST supress finalizer, otherwise
// the GC can collect the memory underneath us!!!
GC.SuppressFinalize(pCryptAttributes);
return pCryptAttributes.DangerousGetHandle();
}
}
internal static CAPI.CMSG_SIGNER_ENCODE_INFO CreateSignerEncodeInfo (CmsSigner signer) {
return CreateSignerEncodeInfo(signer, false);
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[SecuritySafeCritical]
internal static unsafe CAPI.CMSG_SIGNER_ENCODE_INFO CreateSignerEncodeInfo (CmsSigner signer, bool silent) {
CAPI.CMSG_SIGNER_ENCODE_INFO cmsSignerEncodeInfo = new CAPI.CMSG_SIGNER_ENCODE_INFO(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)));
SafeCryptProvHandle safeCryptProvHandle = SafeCryptProvHandle.InvalidHandle;
uint keySpec = 0;
bool freeCsp = false;
cmsSignerEncodeInfo.HashAlgorithm.pszObjId = signer.DigestAlgorithm.Value;
if (0 == String.Compare(
signer.Certificate.PublicKey.Oid.Value,
CAPI.szOID_X957_DSA,
StringComparison.Ordinal))
{
cmsSignerEncodeInfo.HashEncryptionAlgorithm.pszObjId = CAPI.szOID_X957_sha1DSA;
}
cmsSignerEncodeInfo.cAuthAttr = (uint) signer.SignedAttributes.Count;
cmsSignerEncodeInfo.rgAuthAttr = CreateCryptAttributes(signer.SignedAttributes);
cmsSignerEncodeInfo.cUnauthAttr = (uint) signer.UnsignedAttributes.Count;
cmsSignerEncodeInfo.rgUnauthAttr = CreateCryptAttributes(signer.UnsignedAttributes);
if (signer.SignerIdentifierType == SubjectIdentifierType.NoSignature) {
cmsSignerEncodeInfo.HashEncryptionAlgorithm.pszObjId = CAPI.szOID_PKIX_NO_SIGNATURE;
cmsSignerEncodeInfo.pCertInfo = IntPtr.Zero;
cmsSignerEncodeInfo.dwKeySpec = keySpec;
// If the HashEncryptionAlgorithm is set to szOID_PKIX_NO_SIGNATURE, then,
// the signature value only contains the hash octets. hCryptProv must still
// be specified. However, since a private key isn't used the hCryptProv can be
// acquired using CRYPT_VERIFYCONTEXT.
if (!CAPI.CryptAcquireContext(ref safeCryptProvHandle,
null,
null,
CAPI.PROV_RSA_FULL,
CAPI.CRYPT_VERIFYCONTEXT)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
cmsSignerEncodeInfo.hCryptProv = safeCryptProvHandle.DangerousGetHandle();
GC.SuppressFinalize(safeCryptProvHandle);
// Fake up the SignerId so our server can recognize it
// dwIdChoice
cmsSignerEncodeInfo.SignerId.dwIdChoice = CAPI.CERT_ID_ISSUER_SERIAL_NUMBER;
// Issuer
X500DistinguishedName dummyName = new X500DistinguishedName(CAPI.DummySignerCommonName);
dummyName.Oid = Oid.FromOidValue(CAPI.szOID_RDN_DUMMY_SIGNER, OidGroup.ExtensionOrAttribute);
cmsSignerEncodeInfo.SignerId.Value.IssuerSerialNumber.Issuer.cbData = (uint)dummyName.RawData.Length;
SafeLocalAllocHandle pbDataIssuer =
CAPI.LocalAlloc(CAPI.LPTR,
new IntPtr(cmsSignerEncodeInfo.SignerId.Value.IssuerSerialNumber.Issuer.cbData));
Marshal.Copy(dummyName.RawData, 0, pbDataIssuer.DangerousGetHandle(), dummyName.RawData.Length);
cmsSignerEncodeInfo.SignerId.Value.IssuerSerialNumber.Issuer.pbData = pbDataIssuer.DangerousGetHandle();
GC.SuppressFinalize(pbDataIssuer);
// SerialNumber
cmsSignerEncodeInfo.SignerId.Value.IssuerSerialNumber.SerialNumber.cbData = (uint)1;
SafeLocalAllocHandle pbDataSerialNumber =
CAPI.LocalAlloc(CAPI.LPTR,
new IntPtr(cmsSignerEncodeInfo.SignerId.Value.IssuerSerialNumber.SerialNumber.cbData));
byte * pSerialNumber = (byte *)pbDataSerialNumber.DangerousGetHandle();
*pSerialNumber = 0x00;
cmsSignerEncodeInfo.SignerId.Value.IssuerSerialNumber.SerialNumber.pbData =
pbDataSerialNumber.DangerousGetHandle();
GC.SuppressFinalize(pbDataSerialNumber);
return cmsSignerEncodeInfo;
}
SafeCertContextHandle safeCertContextHandle = X509Utils.GetCertContext(signer.Certificate);
if (!CAPI.CAPISafe.CryptAcquireCertificatePrivateKey(safeCertContextHandle,
(silent?
CAPI.CRYPT_SILENT | CAPI.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG | CAPI.CRYPT_ACQUIRE_COMPARE_KEY_FLAG:
CAPI.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG | CAPI.CRYPT_ACQUIRE_COMPARE_KEY_FLAG),
IntPtr.Zero,
ref safeCryptProvHandle,
ref keySpec,
ref freeCsp))
throw new CryptographicException(Marshal.GetLastWin32Error());
cmsSignerEncodeInfo.dwKeySpec = keySpec;
cmsSignerEncodeInfo.hCryptProv = safeCryptProvHandle.DangerousGetHandle();
// Since we are storing only IntPtr in CMSG_SIGNER_ENCODE_INFO.hCryptProv, we MUST then
// supress the finalizer, otherwise the GC can collect the resource underneath us!!!
GC.SuppressFinalize(safeCryptProvHandle);
CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
cmsSignerEncodeInfo.pCertInfo = pCertContext.pCertInfo;
// If CMS, then fill in the Subject Key Identifier (SKI) or SignerId.
if (signer.SignerIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier) {
uint cbData = 0;
SafeLocalAllocHandle pbData = SafeLocalAllocHandle.InvalidHandle;
if (!CAPI.CAPISafe.CertGetCertificateContextProperty(safeCertContextHandle,
CAPI.CERT_KEY_IDENTIFIER_PROP_ID,
pbData,
ref cbData))
throw new CryptographicException(Marshal.GetLastWin32Error());
if (cbData > 0) {
pbData = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(cbData));
if (!CAPI.CAPISafe.CertGetCertificateContextProperty(safeCertContextHandle,
CAPI.CERT_KEY_IDENTIFIER_PROP_ID,
pbData,
ref cbData))
throw new CryptographicException(Marshal.GetLastWin32Error());
cmsSignerEncodeInfo.SignerId.dwIdChoice = CAPI.CERT_ID_KEY_IDENTIFIER;
cmsSignerEncodeInfo.SignerId.Value.KeyId.cbData = cbData;
cmsSignerEncodeInfo.SignerId.Value.KeyId.pbData = pbData.DangerousGetHandle();
// Since we are storing only IntPtr in CMSG_SIGNER_ENCODE_INFO.SignerId.KeyId.pbData,
// we MUST supress finalizer, otherwise the GC can collect the resource underneath us!!!
GC.SuppressFinalize(pbData);
}
}
return cmsSignerEncodeInfo;
}
[SecuritySafeCritical]
internal static X509Certificate2Collection CreateBagOfCertificates (CmsSigner signer) {
X509Certificate2Collection certificates = new X509Certificate2Collection();
//
// First add extra bag of certs.
//
certificates.AddRange(signer.Certificates);
//
// Then include chain option.
//
if (signer.IncludeOption != X509IncludeOption.None) {
if (signer.IncludeOption == X509IncludeOption.EndCertOnly) {
certificates.Add(signer.Certificate);
}
else {
int cCerts = 1;
X509Chain chain = new X509Chain();
chain.Build(signer.Certificate);
// Can't honor the option if we only have a partial chain.
if ((chain.ChainStatus.Length > 0) &&
((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
throw new CryptographicException(CAPI.CERT_E_CHAINING);
if (signer.IncludeOption == X509IncludeOption.WholeChain) {
cCerts = chain.ChainElements.Count;
}
else {
// Default to ExcludeRoot.
if (chain.ChainElements.Count > 1) {
cCerts = chain.ChainElements.Count - 1;
}
}
for (int i = 0; i < cCerts; i++) {
certificates.Add(chain.ChainElements[i].Certificate);
}
}
}
return certificates;
}
[SecurityCritical]
internal static unsafe SafeLocalAllocHandle CreateEncodedCertBlob (X509Certificate2Collection certificates) {
SafeLocalAllocHandle certBlob = SafeLocalAllocHandle.InvalidHandle;
certificates = new X509Certificate2Collection(certificates);
if (certificates.Count > 0) {
checked {
certBlob = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(certificates.Count * Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB))));
CAPI.CRYPTOAPI_BLOB * pCertBlob = (CAPI.CRYPTOAPI_BLOB * ) certBlob.DangerousGetHandle();
foreach (X509Certificate2 certificate in certificates) {
SafeCertContextHandle safeCertContextHandle = X509Utils.GetCertContext(certificate);
CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
pCertBlob->cbData = pCertContext.cbCertEncoded;
pCertBlob->pbData = pCertContext.pbCertEncoded;
pCertBlob++;
}
}
}
return certBlob;
}
[SecuritySafeCritical]
internal static unsafe uint AddCertsToMessage (SafeCryptMsgHandle safeCryptMsgHandle, X509Certificate2Collection bagOfCerts, X509Certificate2Collection chainOfCerts) {
uint certsAdded = 0;
foreach (X509Certificate2 certificate in chainOfCerts) {
// Skip it if already in the bag of certs.
X509Certificate2Collection foundCerts = bagOfCerts.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false);
if (foundCerts.Count == 0) {
SafeCertContextHandle safeCertContextHandle = X509Utils.GetCertContext(certificate);
CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
CAPI.CRYPTOAPI_BLOB certBlob = new CAPI.CRYPTOAPI_BLOB();
certBlob.cbData = pCertContext.cbCertEncoded;
certBlob.pbData = pCertContext.pbCertEncoded;
if (!CAPI.CryptMsgControl(safeCryptMsgHandle,
0,
CAPI.CMSG_CTRL_ADD_CERT,
new IntPtr((long) &certBlob)))
throw new CryptographicException(Marshal.GetLastWin32Error());
certsAdded++;
}
}
return certsAdded;
}
internal static X509Certificate2 FindCertificate (SubjectIdentifier identifier, X509Certificate2Collection certificates) {
X509Certificate2 certificate = null;
if (certificates != null && certificates.Count > 0) {
X509Certificate2Collection filters;
switch (identifier.Type) {
case SubjectIdentifierType.IssuerAndSerialNumber:
filters = certificates.Find(X509FindType.FindByIssuerDistinguishedName, ((X509IssuerSerial) identifier.Value).IssuerName, false);
if (filters.Count > 0) {
filters = filters.Find(X509FindType.FindBySerialNumber, ((X509IssuerSerial) identifier.Value).SerialNumber, false);
if (filters.Count > 0)
certificate = filters[0];
}
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
filters = certificates.Find(X509FindType.FindBySubjectKeyIdentifier, identifier.Value, false);
if (filters.Count > 0)
certificate = filters[0];
break;
}
}
return certificate;
}
private static void checkErr (int err) {
if (CAPI.CRYPT_E_INVALID_MSG_TYPE != err)
throw new CryptographicException(err);
}
// for Key ID signing only
[SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal static unsafe X509Certificate2 CreateDummyCertificate (CspParameters parameters) {
SafeCertContextHandle handle = SafeCertContextHandle.InvalidHandle;
// hProv
SafeCryptProvHandle hProv = SafeCryptProvHandle.InvalidHandle;
UInt32 dwFlags = 0;
if (0 != (parameters.Flags & CspProviderFlags.UseMachineKeyStore))
{
dwFlags |= CAPI.CRYPT_MACHINE_KEYSET;
}
if (0 != (parameters.Flags & CspProviderFlags.UseDefaultKeyContainer))
{
dwFlags |= CAPI.CRYPT_VERIFYCONTEXT;
}
if (0 != (parameters.Flags & CspProviderFlags.NoPrompt))
{
dwFlags |= CAPI.CRYPT_SILENT;
}
bool rc = CAPI.CryptAcquireContext(ref hProv,
parameters.KeyContainerName,
parameters.ProviderName,
(uint)parameters.ProviderType,
dwFlags);
if (!rc)
throw new CryptographicException(Marshal.GetLastWin32Error());
// pKeyProvInfo
CAPI.CRYPT_KEY_PROV_INFO KeyProvInfo = new CAPI.CRYPT_KEY_PROV_INFO();
KeyProvInfo.pwszProvName = parameters.ProviderName;
KeyProvInfo.pwszContainerName = parameters.KeyContainerName;
KeyProvInfo.dwProvType = (uint)parameters.ProviderType;
KeyProvInfo.dwKeySpec = (uint)parameters.KeyNumber ;
KeyProvInfo.dwFlags = (uint)((parameters.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore ? CAPI.CRYPT_MACHINE_KEYSET : 0);
SafeLocalAllocHandle pKeyProvInfo = CAPI.LocalAlloc(CAPI.LPTR,
new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPT_KEY_PROV_INFO))));
Marshal.StructureToPtr(KeyProvInfo, pKeyProvInfo.DangerousGetHandle(), false);
// Signature
CAPI.CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm = new CAPI.CRYPT_ALGORITHM_IDENTIFIER();
SignatureAlgorithm.pszObjId = CAPI.szOID_OIWSEC_sha1RSASign;
SafeLocalAllocHandle pSignatureAlgorithm = CAPI.LocalAlloc(CAPI.LPTR,
new IntPtr( Marshal.SizeOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER))));
Marshal.StructureToPtr(SignatureAlgorithm, pSignatureAlgorithm.DangerousGetHandle(), false);
// pSubjectIssuerBlob
X500DistinguishedName subjectName = new X500DistinguishedName("cn=CMS Signer Dummy Certificate");
fixed (byte * pbOctets = subjectName.RawData) {
CAPI.CRYPTOAPI_BLOB SubjectIssuerBlob = new CAPI.CRYPTOAPI_BLOB();
SubjectIssuerBlob.cbData = (uint)subjectName.RawData.Length;
SubjectIssuerBlob.pbData = new IntPtr(pbOctets);
handle = CAPI.CAPIUnsafe.CertCreateSelfSignCertificate(hProv,
new IntPtr(&SubjectIssuerBlob),
1,
pKeyProvInfo.DangerousGetHandle(),
pSignatureAlgorithm.DangerousGetHandle(),
IntPtr.Zero, //StartTime
IntPtr.Zero, //EndTime
IntPtr.Zero); //Extensions
}
Marshal.DestroyStructure(pKeyProvInfo.DangerousGetHandle(), typeof(CAPI.CRYPT_KEY_PROV_INFO));
pKeyProvInfo.Dispose();
Marshal.DestroyStructure(pSignatureAlgorithm.DangerousGetHandle(), typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER));
pSignatureAlgorithm.Dispose();
if (handle == null || handle.IsInvalid)
throw new CryptographicException(Marshal.GetLastWin32Error());
X509Certificate2 certificate = new X509Certificate2(handle.DangerousGetHandle());
handle.Dispose();
return certificate;
}
}
}
| |
// 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.Memory.Tests;
using System.MemoryTests;
using Microsoft.Xunit.Performance;
using Xunit;
namespace System.Buffers.Tests
{
public class Perf_ReadOnlySequence_First
{
private const int InnerCount = 100_000;
volatile static int _volatileInt = 0;
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_Array(int bufSize, int bufOffset)
{
var buffer = new ReadOnlySequence<byte>(new byte[bufSize], bufOffset, bufSize - 2 * bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<byte> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_Memory(int bufSize, int bufOffset)
{
var manager = new CustomMemoryForTest<byte>(new byte[bufSize], bufOffset, bufSize - 2 * bufOffset);
var buffer = new ReadOnlySequence<byte>(manager.Memory);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<byte> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_SingleSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<byte>(new byte[bufSize]);
var buffer = new ReadOnlySequence<byte>(segment1, bufOffset, segment1, bufSize - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<byte> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_MultiSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<byte>(new byte[bufSize / 10]);
BufferSegment<byte> segment2 = segment1;
for (int j = 0; j < 10; j++)
segment2 = segment2.Append(new byte[bufSize / 10]);
var buffer = new ReadOnlySequence<byte>(segment1, bufOffset, segment2, bufSize / 10 - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<byte> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Byte_Empty()
{
ReadOnlySequence<byte> buffer = ReadOnlySequence<byte>.Empty;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<byte> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Byte_Default()
{
ReadOnlySequence<byte> buffer = default;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<byte> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_Array(int bufSize, int bufOffset)
{
var buffer = new ReadOnlySequence<char>(new char[bufSize], bufOffset, bufSize - 2 * bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_Memory(int bufSize, int bufOffset)
{
var manager = new CustomMemoryForTest<char>(new char[bufSize], bufOffset, bufSize - 2 * bufOffset);
var buffer = new ReadOnlySequence<char>(manager.Memory);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_SingleSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<char>(new char[bufSize]);
var buffer = new ReadOnlySequence<char>(segment1, bufOffset, segment1, bufSize - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_MultiSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<char>(new char[bufSize / 10]);
BufferSegment<char> segment2 = segment1;
for (int j = 0; j < 10; j++)
segment2 = segment2.Append(new char[bufSize / 10]);
var buffer = new ReadOnlySequence<char>(segment1, bufOffset, segment2, bufSize / 10 - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void String(int bufSize, int bufOffset)
{
ReadOnlyMemory<char> memory = new string('a', bufSize).AsMemory();
memory = memory.Slice(bufOffset, bufSize - 2 * bufOffset);
var buffer = new ReadOnlySequence<char>(memory);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Char_Empty()
{
ReadOnlySequence<char> buffer = ReadOnlySequence<char>.Empty;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Char_Default()
{
ReadOnlySequence<char> buffer = default;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
ReadOnlyMemory<char> first = buffer.First;
localInt ^= first.Length;
}
}
_volatileInt = localInt;
}
}
}
}
| |
//http://stackoverflow.com/questions/6893302/decode-rgb-value-to-single-float-without-bit-shift-in-glsl
//why this stupid assert on the blendstate. just set one by default, geeze.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using sd = System.Drawing;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace BizHawk.Bizware.BizwareGL
{
/// <summary>
/// A simple renderer useful for rendering GUI stuff.
/// When doing GUI rendering, run everything through here (if you need a GL feature not done through here, run it through here first)
/// Call Begin, then draw, then End, and dont use other Renderers or GL calls in the meantime, unless you know what youre doing.
/// This can perform batching (well.. maybe not yet), which is occasionally necessary for drawing large quantities of things.
/// </summary>
public class GuiRenderer : IDisposable, IGuiRenderer
{
public GuiRenderer(IGL owner)
{
Owner = owner;
VertexLayout = owner.CreateVertexLayout();
VertexLayout.DefineVertexAttribute("aPosition", 0, 2, VertexAttribPointerType.Float, AttributeUsage.Position, false, 32, 0);
VertexLayout.DefineVertexAttribute("aTexcoord", 1, 2, VertexAttribPointerType.Float, AttributeUsage.Texcoord0, false, 32, 8);
VertexLayout.DefineVertexAttribute("aColor", 2, 4, VertexAttribPointerType.Float, AttributeUsage.Texcoord1, false, 32, 16);
VertexLayout.Close();
_Projection = new MatrixStack();
_Modelview = new MatrixStack();
string psProgram, vsProgram;
if (owner.API == "D3D9")
{
vsProgram = DefaultShader_d3d9;
psProgram = DefaultShader_d3d9;
}
else
{
vsProgram = DefaultVertexShader_gl;
psProgram = DefaultPixelShader_gl;
}
var vs = Owner.CreateVertexShader(false, vsProgram, "vsmain", true);
var ps = Owner.CreateFragmentShader(false, psProgram, "psmain", true);
CurrPipeline = DefaultPipeline = Owner.CreatePipeline(VertexLayout, vs, ps, true, "xgui");
}
OpenTK.Graphics.Color4[] CornerColors = new OpenTK.Graphics.Color4[4] {
new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f),new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f),new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f),new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f)
};
public void SetCornerColor(int which, OpenTK.Graphics.Color4 color)
{
Flush(); //dont really need to flush with current implementation. we might as well roll modulate color into it too.
CornerColors[which] = color;
}
public void SetCornerColors(OpenTK.Graphics.Color4[] colors)
{
Flush(); //dont really need to flush with current implementation. we might as well roll modulate color into it too.
if (colors.Length != 4) throw new ArgumentException("array must be size 4", "colors");
for (int i = 0; i < 4; i++)
CornerColors[i] = colors[i];
}
public void Dispose()
{
DefaultPipeline.Dispose();
}
public void SetPipeline(Pipeline pipeline)
{
if (IsActive)
throw new InvalidOperationException("Can't change pipeline while renderer is running!");
Flush();
CurrPipeline = pipeline;
//clobber state cache
sTexture = null;
//save the modulate color? user beware, I guess, for now.
}
public void SetDefaultPipeline()
{
SetPipeline(DefaultPipeline);
}
public void SetModulateColorWhite()
{
SetModulateColor(sd.Color.White);
}
public void SetModulateColor(sd.Color color)
{
Flush();
CurrPipeline["uModulateColor"].Set(new Vector4(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f));
}
public void SetBlendState(IBlendState rsBlend)
{
#if DEBUG
BlendStateSet = true;
#endif
Flush();
Owner.SetBlendState(rsBlend);
}
MatrixStack _Projection, _Modelview;
public MatrixStack Projection
{
get { return _Projection; }
set
{
_Projection = value;
_Projection.IsDirty = true;
}
}
public MatrixStack Modelview
{
get { return _Modelview; }
set
{
_Modelview = value;
_Modelview.IsDirty = true;
}
}
public void Begin(sd.Size size) { Begin(size.Width, size.Height); }
public void Begin(int width, int height)
{
Begin();
Projection = Owner.CreateGuiProjectionMatrix(width, height);
Modelview = Owner.CreateGuiViewMatrix(width, height);
Owner.SetViewport(width, height);
}
public void Begin()
{
//uhhmmm I want to throw an exception if its already active, but its annoying.
if (CurrPipeline == null)
throw new InvalidOperationException("Pipeline hasn't been set!");
IsActive = true;
Owner.BindPipeline(CurrPipeline);
//clear state cache
sTexture = null;
CurrPipeline["uSamplerEnable"].Set(false);
Modelview.Clear();
Projection.Clear();
SetModulateColorWhite();
#if DEBUG
BlendStateSet = false;
#endif
}
public void Flush()
{
//no batching, nothing to do here yet
}
public void End()
{
if (!IsActive)
throw new InvalidOperationException("GuiRenderer is not active!");
IsActive = false;
}
public void RectFill(float x, float y, float w, float h)
{
PrepDrawSubrectInternal(null);
EmitRectangleInternal(x, y, w, h, 0, 0, 0, 0);
}
public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
DrawSubrectInternal(tex, x, y, w, h, u0, v0, u1, v1);
}
public void Draw(Art art) { DrawInternal(art, 0, 0, art.Width, art.Height, false, false); }
public void Draw(Art art, float x, float y) { DrawInternal(art, x, y, art.Width, art.Height, false, false); }
public void Draw(Art art, float x, float y, float width, float height) { DrawInternal(art, x, y, width, height, false, false); }
public void Draw(Art art, Vector2 pos) { DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); }
public void Draw(Texture2d tex) { DrawInternal(tex, 0, 0, tex.Width, tex.Height); }
public void Draw(Texture2d tex, float x, float y) { DrawInternal(tex, x, y, tex.Width, tex.Height); }
public void DrawFlipped(Art art, bool xflip, bool yflip) { DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); }
public void Draw(Texture2d art, float x, float y, float width, float height)
{
DrawInternal(art, x, y, width, height);
}
unsafe void DrawInternal(Texture2d tex, float x, float y, float w, float h)
{
Art art = new Art(null);
art.Width = w;
art.Height = h;
art.u0 = art.v0 = 0;
art.u1 = art.v1 = 1;
art.BaseTexture = tex;
DrawInternal(art, x, y, w, h, false, tex.IsUpsideDown);
}
unsafe void DrawInternal(Art art, float x, float y, float w, float h, bool fx, bool fy)
{
//TEST: d3d shouldnt ever use this, it was a gl hack. maybe we can handle it some other way in gl (fix the projection? take a render-to-texture arg to the gui view transforms?)
fy = false;
float u0, v0, u1, v1;
if (fx) { u0 = art.u1; u1 = art.u0; }
else { u0 = art.u0; u1 = art.u1; }
if (fy) { v0 = art.v1; v1 = art.v0; }
else { v0 = art.v0; v1 = art.v1; }
float[] data = new float[32] {
x,y, u0,v0, CornerColors[0].R, CornerColors[0].G, CornerColors[0].B, CornerColors[0].A,
x+art.Width,y, u1,v0, CornerColors[1].R, CornerColors[1].G, CornerColors[1].B, CornerColors[1].A,
x,y+art.Height, u0,v1, CornerColors[2].R, CornerColors[2].G, CornerColors[2].B, CornerColors[2].A,
x+art.Width,y+art.Height, u1,v1, CornerColors[3].R, CornerColors[3].G, CornerColors[3].B, CornerColors[3].A,
};
Texture2d tex = art.BaseTexture;
PrepDrawSubrectInternal(tex);
fixed (float* pData = &data[0])
{
Owner.BindArrayData(pData);
Owner.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
}
}
unsafe void PrepDrawSubrectInternal(Texture2d tex)
{
if (sTexture != tex)
{
sTexture = tex;
CurrPipeline["uSampler0"].Set(tex);
if (sTexture == null)
{
CurrPipeline["uSamplerEnable"].Set(false);
}
else
{
CurrPipeline["uSamplerEnable"].Set(true);
}
}
if (_Projection.IsDirty)
{
CurrPipeline["um44Projection"].Set(ref _Projection.Top, false);
_Projection.IsDirty = false;
}
if (_Modelview.IsDirty)
{
CurrPipeline["um44Modelview"].Set(ref _Modelview.Top, false);
_Modelview.IsDirty = false;
}
}
unsafe void EmitRectangleInternal(float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
float* pData = stackalloc float[32];
pData[0] = x;
pData[1] = y;
pData[2] = u0;
pData[3] = v0;
pData[4] = CornerColors[0].R;
pData[5] = CornerColors[0].G;
pData[6] = CornerColors[0].B;
pData[7] = CornerColors[0].A;
pData[8] = x + w;
pData[9] = y;
pData[10] = u1;
pData[11] = v0;
pData[12] = CornerColors[1].R;
pData[13] = CornerColors[1].G;
pData[14] = CornerColors[1].B;
pData[15] = CornerColors[1].A;
pData[16] = x;
pData[17] = y + h;
pData[18] = u0;
pData[19] = v1;
pData[20] = CornerColors[2].R;
pData[21] = CornerColors[2].G;
pData[22] = CornerColors[2].B;
pData[23] = CornerColors[2].A;
pData[24] = x + w;
pData[25] = y + h;
pData[26] = u1;
pData[27] = v1;
pData[28] = CornerColors[3].R;
pData[29] = CornerColors[3].G;
pData[30] = CornerColors[3].B;
pData[31] = CornerColors[3].A;
Owner.BindArrayData(pData);
Owner.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
#if DEBUG
Debug.Assert(BlendStateSet);
#endif
}
unsafe void DrawSubrectInternal(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
PrepDrawSubrectInternal(tex);
EmitRectangleInternal(x, y, w, h, u0, v0, u1, v1);
}
public bool IsActive { get; private set; }
public IGL Owner { get; private set; }
VertexLayout VertexLayout;
Pipeline CurrPipeline, DefaultPipeline;
//state cache
Texture2d sTexture;
#if DEBUG
bool BlendStateSet;
#endif
//shaders are hand-coded for each platform to make sure they stay as fast as possible
public readonly string DefaultShader_d3d9 = @"
//vertex shader uniforms
float4x4 um44Modelview, um44Projection;
float4 uModulateColor;
//pixel shader uniforms
bool uSamplerEnable;
texture2D texture0, texture1;
sampler uSampler0 = sampler_state { Texture = (texture0); };
struct VS_INPUT
{
float2 aPosition : POSITION;
float2 aTexcoord : TEXCOORD0;
float4 aColor : TEXCOORD1;
};
struct VS_OUTPUT
{
float4 vPosition : POSITION;
float2 vTexcoord0 : TEXCOORD0;
float4 vCornerColor : COLOR0;
};
struct PS_INPUT
{
float2 vTexcoord0 : TEXCOORD0;
float4 vCornerColor : COLOR0;
};
VS_OUTPUT vsmain(VS_INPUT src)
{
VS_OUTPUT dst;
float4 temp = float4(src.aPosition,0,1);
dst.vPosition = mul(um44Projection,mul(um44Modelview,temp));
dst.vTexcoord0 = src.aTexcoord;
dst.vCornerColor = src.aColor * uModulateColor;
return dst;
}
float4 psmain(PS_INPUT src) : COLOR
{
float4 temp = src.vCornerColor;
if(uSamplerEnable) temp *= tex2D(uSampler0,src.vTexcoord0);
return temp;
}
";
public readonly string DefaultVertexShader_gl = @"
#version 110 //opengl 2.0 ~ 2004
uniform mat4 um44Modelview, um44Projection;
uniform vec4 uModulateColor;
//attribute vec2 aPosition : gl_Vertex;
//attribute vec2 aTexcoord : gl_MultiTexCoord0;
//attribute vec4 aColor : gl_Color;
#define aPosition vec2(gl_Vertex.xy)
#define aTexcoord vec2(gl_MultiTexCoord0.xy)
#define aColor gl_Color
varying vec2 vTexcoord0;
varying vec4 vCornerColor;
void main()
{
vec4 temp = vec4(aPosition,0,1);
gl_Position = um44Projection * (um44Modelview * temp);
vTexcoord0 = aTexcoord;
vCornerColor = aColor * uModulateColor;
}";
public readonly string DefaultPixelShader_gl = @"
#version 110 //opengl 2.0 ~ 2004
uniform bool uSamplerEnable;
uniform sampler2D uSampler0;
varying vec2 vTexcoord0;
varying vec4 vCornerColor;
void main()
{
vec4 temp = vCornerColor;
if(uSamplerEnable) temp *= texture2D(uSampler0,vTexcoord0);
gl_FragColor = temp;
}";
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model.
*/
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
namespace AWSSDK_DotNet35.UnitTests.TestTools
{
[TestClass]
public class IdentityManagementServiceConstructorCustomizationsTests
{
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void AddUserToGroupRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.AddUserToGroupRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void CreateAccessKeyRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void CreateAccountAliasRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.CreateAccountAliasRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void CreateGroupRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.CreateGroupRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void CreateLoginProfileRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.CreateLoginProfileRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void CreateUserRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.CreateUserRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeactivateMFADeviceRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeactivateMFADeviceRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteAccessKeyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteAccessKeyRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteAccountAliasRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteAccountAliasRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteGroupRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteGroupRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteGroupPolicyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteGroupPolicyRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteLoginProfileRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteLoginProfileRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteServerCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteServerCertificateRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteSigningCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteSigningCertificateRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteUserRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteUserRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void DeleteUserPolicyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.DeleteUserPolicyRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void GetGroupRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.GetGroupRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void GetGroupPolicyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.GetGroupPolicyRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void GetLoginProfileRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.GetLoginProfileRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void GetServerCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.GetServerCertificateRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void GetUserRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void GetUserPolicyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.GetUserPolicyRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListAccessKeysRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListAccountAliasesRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListGroupPoliciesRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.ListGroupPoliciesRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListGroupsRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListGroupsForUserRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.ListGroupsForUserRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListMFADevicesRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.ListMFADevicesRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListServerCertificatesRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListSigningCertificatesRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListUserPoliciesRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.ListUserPoliciesRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void ListUsersRequestConstructorTests()
{
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void PutGroupPolicyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.PutGroupPolicyRequest), new System.Type[] { typeof(string), typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void PutUserPolicyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.PutUserPolicyRequest), new System.Type[] { typeof(string), typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void RemoveUserFromGroupRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.RemoveUserFromGroupRequest), new System.Type[] { typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UpdateAccessKeyRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UpdateAccessKeyRequest), new System.Type[] { typeof(string), typeof(StatusType), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UpdateGroupRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UpdateGroupRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UpdateLoginProfileRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UpdateLoginProfileRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UpdateServerCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UpdateServerCertificateRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UpdateSigningCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UpdateSigningCertificateRequest), new System.Type[] { typeof(string), typeof(StatusType), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UpdateUserRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UpdateUserRequest), new System.Type[] { typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UploadServerCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UploadServerCertificateRequest), new System.Type[] { typeof(string), typeof(string), typeof(string), });
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Constructors"), TestCategory("IdentityManagementService")]
public void UploadSigningCertificateRequestConstructorTests()
{
EnsureConstructorExists(typeof(Amazon.IdentityManagement.Model.UploadSigningCertificateRequest), new System.Type[] { typeof(string), });
}
void EnsureConstructorExists(System.Type type, System.Type[] constructorParams)
{
Assert.IsNotNull(type.GetConstructor(constructorParams));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_UpdateTests
{
[Theory]
[InlineData("normal.zip", "normal")]
[InlineData("fake64.zip", "small")]
[InlineData("empty.zip", "empty")]
[InlineData("appended.zip", "small")]
[InlineData("prepended.zip", "small")]
[InlineData("emptydir.zip", "emptydir")]
[InlineData("small.zip", "small")]
[InlineData("unicode.zip", "unicode")]
public static async Task UpdateReadNormal(string zipFile, string zipFolder)
{
ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile(zipFile)), ZipTest.zfolder(zipFolder), ZipArchiveMode.Update, false, false);
}
[Fact]
public static async Task UpdateReadTwice()
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("small.zip")), ZipArchiveMode.Update))
{
ZipArchiveEntry entry = archive.Entries[0];
String contents1, contents2;
using (StreamReader s = new StreamReader(entry.Open()))
{
contents1 = s.ReadToEnd();
}
using (StreamReader s = new StreamReader(entry.Open()))
{
contents2 = s.ReadToEnd();
}
Assert.Equal(contents1, contents2);
}
}
[InlineData("normal")]
[InlineData("empty")]
[InlineData("unicode")]
public static async Task UpdateCreate(string zipFolder)
{
var zs = new LocalMemoryStream();
await ZipTest.CreateFromDir(ZipTest.zfolder(zipFolder), zs, ZipArchiveMode.Update);
ZipTest.IsZipSameAsDir(zs.Clone(), ZipTest.zfolder(zipFolder), ZipArchiveMode.Read, false, false);
}
[Theory]
[InlineData(ZipArchiveMode.Create)]
[InlineData(ZipArchiveMode.Update)]
public static void EmptyEntryTest(ZipArchiveMode mode)
{
String data1 = "test data written to file.";
String data2 = "more test data written to file.";
DateTimeOffset lastWrite = new DateTimeOffset(1992, 4, 5, 12, 00, 30, new TimeSpan(-5, 0, 0));
var baseline = new LocalMemoryStream();
using (ZipArchive archive = new ZipArchive(baseline, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
using (Stream s = e.Open()) { }
ZipTest.AddEntry(archive, "data2.txt", data2, lastWrite);
}
var test = new LocalMemoryStream();
using (ZipArchive archive = new ZipArchive(test, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
ZipTest.AddEntry(archive, "data2.txt", data2, lastWrite);
}
//compare
Assert.True(ZipTest.ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match");
//second test, this time empty file at end
baseline = baseline.Clone();
using (ZipArchive archive = new ZipArchive(baseline, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
using (Stream s = e.Open()) { }
}
test = test.Clone();
using (ZipArchive archive = new ZipArchive(test, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
}
//compare
Assert.True(ZipTest.ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match after update");
}
[Fact]
public static async Task DeleteAndMoveEntries()
{
//delete and move
var testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
ZipArchiveEntry toBeDeleted = archive.GetEntry("binary.wmv");
toBeDeleted.Delete();
toBeDeleted.Delete(); //delete twice should be okay
ZipArchiveEntry moved = archive.CreateEntry("notempty/secondnewname.txt");
ZipArchiveEntry orig = archive.GetEntry("notempty/second.txt");
using (Stream origMoved = orig.Open(), movedStream = moved.Open())
{
origMoved.CopyTo(movedStream);
}
moved.LastWriteTime = orig.LastWriteTime;
orig.Delete();
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("deleteMove"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AppendToEntry()
{
//append
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
ZipArchiveEntry e = archive.GetEntry("first.txt");
using (StreamWriter s = new StreamWriter(e.Open()))
{
s.BaseStream.Seek(0, SeekOrigin.End);
s.Write("\r\n\r\nThe answer my friend, is blowin' in the wind.");
}
var file = FileData.GetFile(ZipTest.zmodified(Path.Combine("append", "first.txt")));
e.LastWriteTime = file.LastModifiedDate;
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("append"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task OverwriteEntry()
{
//Overwrite file
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
String fileName = ZipTest.zmodified(Path.Combine("overwrite", "first.txt"));
ZipArchiveEntry e = archive.GetEntry("first.txt");
var file = FileData.GetFile(fileName);
e.LastWriteTime = file.LastModifiedDate;
using (var stream = await StreamHelpers.CreateTempCopyStream(fileName))
{
using (Stream es = e.Open())
{
es.SetLength(0);
stream.CopyTo(es);
}
}
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("overwrite"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AddFileToArchive()
{
//add file
var testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified ("addFile"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AddFileToArchive_AfterReading()
{
//add file and read entries before
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
var x = archive.Entries;
await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("addFile"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AddFileToArchive_ThenReadEntries()
{
//add file and read entries after
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
var x = archive.Entries;
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("addFile"), ZipArchiveMode.Read, false, false);
}
private static async Task updateArchive(ZipArchive archive, String installFile, String entryName)
{
ZipArchiveEntry e = archive.CreateEntry(entryName);
var file = FileData.GetFile(installFile);
e.LastWriteTime = file.LastModifiedDate;
Assert.Equal(e.LastWriteTime, file.LastModifiedDate);
using (var stream = await StreamHelpers.CreateTempCopyStream(installFile))
{
using (Stream es = e.Open())
{
es.SetLength(0);
stream.CopyTo(es);
}
}
}
[Fact]
public static async Task UpdateModeInvalidOperations()
{
using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(ZipTest.zfile("normal.zip")))
{
ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, true);
ZipArchiveEntry edeleted = target.GetEntry("first.txt");
Stream s = edeleted.Open();
//invalid ops while entry open
Assert.Throws<IOException>(() => edeleted.Open());
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
Assert.Throws<IOException>(() => edeleted.Delete());
s.Dispose();
//invalid ops on stream after entry closed
Assert.Throws<ObjectDisposedException>(() => s.ReadByte());
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
edeleted.Delete();
//invalid ops while entry deleted
Assert.Throws<InvalidOperationException>(() => edeleted.Open());
Assert.Throws<InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); });
ZipArchiveEntry e = target.GetEntry("notempty/second.txt");
target.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var x = target.Entries; });
Assert.Throws<ObjectDisposedException>(() => target.CreateEntry("dirka"));
Assert.Throws<ObjectDisposedException>(() => e.Open());
Assert.Throws<ObjectDisposedException>(() => e.Delete());
Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); });
}
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
#endif
#if WPF
using System.Windows;
using System.Windows.Media;
#endif
using PdfSharp.Internal;
using PdfSharp.Fonts;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Advanced;
// WPFHACK
#pragma warning disable 162
namespace PdfSharp.Drawing
{
/// <summary>
/// Defines an object used to draw text.
/// </summary>
[DebuggerDisplay("'{Name}', {Size}")]
public class XFont
{
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="emSize">The em size.</param>
public XFont(string familyName, double emSize)
{
this.familyName = familyName;
this.emSize = emSize;
this.style = XFontStyle.Regular;
this.pdfOptions = new XPdfFontOptions();
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
public XFont(string familyName, double emSize, XFontStyle style)
{
this.familyName = familyName;
this.emSize = emSize;
this.style = style;
this.pdfOptions = new XPdfFontOptions();
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(string familyName, double emSize, XFontStyle style, XPdfFontOptions pdfOptions)
{
this.familyName = familyName;
this.emSize = emSize;
this.style = style;
this.pdfOptions = pdfOptions;
Initialize();
}
#if GDI // #PFC
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="family">The font family.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(System.Drawing.FontFamily family, double emSize, XFontStyle style, XPdfFontOptions pdfOptions /*,
XPrivateFontCollection privateFontCollection*/
)
{
this.familyName = null;
this.gdifamily = family;
this.emSize = emSize;
this.style = style;
this.pdfOptions = pdfOptions;
Initialize();
}
#endif
#if GDI
#if UseGdiObjects
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.Font.
/// </summary>
/// <param name="font">A System.Drawing.Font.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(Font font, XPdfFontOptions pdfOptions)
{
if (font.Unit != GraphicsUnit.World)
throw new ArgumentException("Font must use GraphicsUnit.World.");
this.font = font;
this.familyName = font.Name;
this.emSize = font.Size;
this.style = FontStyleFrom(font);
this.pdfOptions = pdfOptions;
Initialize();
}
#endif
#endif
/// <summary>
/// Connects the specifications of a font from XFont to a real glyph type face.
/// </summary>
void Initialize()
{
XFontMetrics fm = null;
#if DEBUG___
FontData[] fontDataArray = FontDataStock.Global.GetFontDataList();
if (fontDataArray.Length > 0)
{
//// GetType();
////#if GDI
//// var x = XPrivateFontCollection.global.GlobalPrivateFontCollection;
//// families = x.Families;
//// bool fff = families[0].IsStyleAvailable(System.Drawing.FontStyle.Regular);
//// fff.GetType();
//// this.font = new Font(families[0].Name, 12, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);
//// this.font = new Font("Oblivious", 12, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);
//// this.font = new Font(families[0], 12, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);
//// System.Drawing.FontFamily f = new System.Drawing.FontFamily(families[0].Name);
//// f.GetType();
////#endif
}
#endif
#if GDI
if (this.font == null)
{
if (this.gdifamily != null)
{
this.font = new Font(this.gdifamily, (float)this.emSize, (System.Drawing.FontStyle)this.style, GraphicsUnit.World);
this.familyName = this.gdifamily.Name; // Do we need this???
}
else
{
// First check private fonts
this.font = XPrivateFontCollection.TryFindPrivateFont(this.familyName, this.emSize, (System.Drawing.FontStyle)this.style) ??
new Font(this.familyName, (float)this.emSize, (System.Drawing.FontStyle)this.style, GraphicsUnit.World);
}
#if DEBUG
// new Font returns MSSansSerif if the requested font was not found ...
//Debug.Assert(this.familyName == this.font.FontFamily.Name);
#endif
}
fm = Metrics;
System.Drawing.FontFamily fontFamily = this.font.FontFamily;
this.unitsPerEm = fm.UnitsPerEm;
System.Drawing.FontFamily fontFamily2 = this.font.FontFamily;
this.cellSpace = fontFamily2.GetLineSpacing(font.Style);
//Debug.Assert(this.cellSpace == fm.Ascent + Math.Abs(fm.Descent) + fm.Leading, "Value differs from information retrieved from font image.");
this.cellAscent = fontFamily.GetCellAscent(font.Style);
#pragma warning disable 1030
#warning delTHHO
//!!!delTHHO 14.08.2008 Debug.Assert(this.cellAscent == fm.Ascent, "Value differs from information retrieved from font image.");
//Debug.Assert(this.cellAscent == fm.Ascent, "Value differs from information retrieved from font image.");
this.cellDescent = fontFamily.GetCellDescent(font.Style);
#if DEBUG
int desc = Math.Abs(fm.Descent);
if (this.cellDescent != desc)
Debug.Assert(false, "Value differs from information retrieved from font image.");
#endif
#endif
#if WPF
#if !SILVERLIGHT
if (this.family == null)
{
Debug.Assert(this.typeface == null);
this.typeface = XPrivateFontCollection.TryFindTypeface(Name, this.style, out this.family);
#if true
if (this.typeface != null)
{
GlyphTypeface glyphTypeface;
ICollection<Typeface> list = this.family.GetTypefaces();
foreach (Typeface tf in list)
{
if (!tf.TryGetGlyphTypeface(out glyphTypeface))
Debugger.Break();
}
if (!this.typeface.TryGetGlyphTypeface(out glyphTypeface))
throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(Name));
}
#endif
}
if (this.family == null)
this.family = new System.Windows.Media.FontFamily(Name);
if (typeface == null)
this.typeface = FontHelper.CreateTypeface(this.family, style);
fm = Metrics;
Debug.Assert(this.unitsPerEm == 0 || this.unitsPerEm == fm.UnitsPerEm);
this.unitsPerEm = fm.UnitsPerEm;
//Debug.Assert(this.cellSpace == 0 || this.cellSpace == fm.Ascent + Math.Abs(fm.Descent) + fm.Leading);
this.cellSpace = fm.Ascent + Math.Abs(fm.Descent) + fm.Leading;
Debug.Assert(this.cellAscent == 0 || this.cellAscent == fm.Ascent);
this.cellAscent = fm.Ascent;
Debug.Assert(this.cellDescent == 0 || this.cellDescent == Math.Abs(fm.Descent));
this.cellDescent = Math.Abs(fm.Descent);
#else
if (fm != null)
fm.GetType();
#endif
#endif
}
#if GDI
// Fonts can be created from familyName or from family!
//string familyName;
/// <summary>
/// Gets the GDI family.
/// </summary>
/// <value>The GDI family.</value>
public System.Drawing.FontFamily GdiFamily
{
get { return this.gdifamily; }
//set { this.gdifamily = value; }
}
System.Drawing.FontFamily gdifamily;
#endif
#if GDI
internal static XFontStyle FontStyleFrom(Font font)
{
return
(font.Bold ? XFontStyle.Bold : 0) |
(font.Italic ? XFontStyle.Italic : 0) |
(font.Strikeout ? XFontStyle.Strikeout : 0) |
(font.Underline ? XFontStyle.Underline : 0);
}
#endif
//// Methods
//public Font(Font prototype, FontStyle newStyle);
//public Font(FontFamily family, float emSize);
//public Font(string familyName, float emSize);
//public Font(FontFamily family, float emSize, FontStyle style);
//public Font(FontFamily family, float emSize, GraphicsUnit unit);
//public Font(string familyName, float emSize, FontStyle style);
//public Font(string familyName, float emSize, GraphicsUnit unit);
//public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit);
//public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit);
////public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet);
////public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet);
////public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont);
////public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont);
//public object Clone();
//private static FontFamily CreateFontFamilyWithFallback(string familyName);
//private void Dispose(bool disposing);
//public override bool Equals(object obj);
//protected override void Finalize();
//public static Font FromHdc(IntPtr hdc);
//public static Font FromHfont(IntPtr hfont);
//public static Font FromLogFont(object lf);
//public static Font FromLogFont(object lf, IntPtr hdc);
//public override int GetHashCode();
/// <summary>
/// Returns the line spacing, in pixels, of this font. The line spacing is the vertical distance
/// between the base lines of two consecutive lines of text. Thus, the line spacing includes the
/// blank space between lines along with the height of the character itself.
/// </summary>
public double GetHeight()
{
#if GDI
RealizeGdiFont();
double gdiValue = this.font.GetHeight();
#if DEBUG
float myValue = (float)(this.cellSpace * this.emSize / this.unitsPerEm);
//Debug.Assert(DoubleUtil.AreClose((float)value, myValue), "Check formula.");
Debug.Assert(DoubleUtil.AreRoughlyEqual(gdiValue, myValue, 5), "Check formula.");
//// 2355*(0.3/2048)*96 = 33.11719
//double myValue = this.cellSpace * (this.size / 72 / this.unitsPerEm) * 96;
//double myValue2 = (float)(this.cellSpace * (this.size / /*72 /*/ this.unitsPerEm) /* 72*/);
//Int64 i1 = (Int64)(value * 1000 + .5);
//Int64 i2 = (Int64)(myValue2 * 1000 + .5);
//Debug.Assert(i1 == i2, "??");
#endif
return gdiValue;
#endif
#if WPF
double value = this.cellSpace * this.emSize / this.unitsPerEm;
return value;
#endif
}
/// <summary>
/// Returns the line spacing, in the current unit of a specified Graphics object, of this font.
/// The line spacing is the vertical distance between the base lines of two consecutive lines of
/// text. Thus, the line spacing includes the blank space between lines along with the height of
/// </summary>
public double GetHeight(XGraphics graphics)
{
#if GDI && !WPF
RealizeGdiFont();
double value = this.font.GetHeight(graphics.gfx);
Debug.Assert(value == this.font.GetHeight(graphics.gfx.DpiY));
double value2 = this.cellSpace * this.emSize / this.unitsPerEm;
Debug.Assert(value - value2 < 1e-3, "??");
return this.font.GetHeight(graphics.gfx);
#endif
#if WPF && !GDI
double value = this.cellSpace * this.emSize / this.unitsPerEm;
return value;
#endif
#if GDI && WPF
if (graphics.targetContext == XGraphicTargetContext.GDI)
{
RealizeGdiFont();
#if DEBUG
double value = this.font.GetHeight(graphics.gfx);
// 2355*(0.3/2048)*96 = 33.11719
double myValue = this.cellSpace * (this.emSize / (96 * this.unitsPerEm)) * 96;
myValue = this.cellSpace * this.emSize / this.unitsPerEm;
//Debug.Assert(value == myValue, "??");
//Debug.Assert(value - myValue < 1e-3, "??");
#endif
return this.font.GetHeight(graphics.gfx);
}
else if (graphics.targetContext == XGraphicTargetContext.WPF)
{
double value = this.cellSpace * this.emSize / this.unitsPerEm;
return value;
}
Debug.Assert(false);
return 0;
#endif
}
//public float GetHeight(float dpi);
//public IntPtr ToHfont();
//public void ToLogFont(object logFont);
//public void ToLogFont(object logFont, Graphics graphics);
//public override string ToString();
// Properties
/// <summary>
/// Gets the XFontFamily object associated with this XFont object.
/// </summary>
[Browsable(false)]
public XFontFamily FontFamily
{
get
{
if (this.fontFamily == null)
{
#if GDI
RealizeGdiFont();
this.fontFamily = new XFontFamily(this.font.FontFamily);
#endif
#if WPF
#if !SILVERLIGHT
Debug.Assert(this.family != null);
this.fontFamily = new XFontFamily(this.family);
#else
// AGHACK
#endif
#endif
}
return this.fontFamily;
}
}
XFontFamily fontFamily;
/// <summary>
/// Gets the face name of this Font object.
/// </summary>
public string Name
{
get
{
#if GDI
RealizeGdiFont();
return this.font.Name;
#endif
#if WPF || SILVERLIGHT
//RealizeGdiFont();
return this.familyName;
#endif
}
}
/// <summary>
/// Gets the em-size of this Font object measured in the unit of this Font object.
/// </summary>
public double Size
{
get { return this.emSize; }
}
double emSize;
/// <summary>
/// Gets the line spacing of this font.
/// </summary>
[Browsable(false)]
public int Height
{
// Implementation from System.Drawing.Font.cs
get { return (int)Math.Ceiling(GetHeight()); }
// DELETE
// {
//#if GDI && !WPF
// RealizeGdiFont();
// return this.font.Height;
//#endif
//#if WPF && !GDI
// return (int)this.size;
//#endif
//#if GDI && WPF
// // netmassdownloader -d "C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5" -output G:\dotnet-massdownload\SourceCode -v
// RealizeGdiFont();
// int gdiHeight = this.font.Height;
// double wpfHeight1 = this.cellSpace * this.size / this.unitsPerEm;
// //int wpfHeight = (int)wpfHeight1+Math.Round(wpfHeight1,
// int wpfHeight = Convert.ToInt32(wpfHeight1 + 0.5);
// Debug.Assert(gdiHeight == wpfHeight);
// return gdiHeight;
//#endif
// }
}
/// <summary>
/// Gets style information for this Font object.
/// </summary>
[Browsable(false)]
public XFontStyle Style
{
get { return this.style; }
}
XFontStyle style;
/// <summary>
/// Indicates whether this XFont object is bold.
/// </summary>
public bool Bold
{
get { return (this.style & XFontStyle.Bold) == XFontStyle.Bold; }
}
/// <summary>
/// Indicates whether this XFont object is italic.
/// </summary>
public bool Italic
{
get { return (this.style & XFontStyle.Italic) == XFontStyle.Italic; }
}
/// <summary>
/// Indicates whether this XFont object is stroke out.
/// </summary>
public bool Strikeout
{
get { return (this.style & XFontStyle.Strikeout) == XFontStyle.Strikeout; }
}
/// <summary>
/// Indicates whether this XFont object is underlined.
/// </summary>
public bool Underline
{
get { return (this.style & XFontStyle.Underline) == XFontStyle.Underline; }
}
/// <summary>
/// Temporary HACK for XPS to PDF converter.
/// </summary>
internal bool IsVertical
{
get { return this.isVertical; }
set { this.isVertical = value; }
}
bool isVertical;
/// <summary>
/// Gets the PDF options of the font.
/// </summary>
public XPdfFontOptions PdfOptions
{
get
{
if (this.pdfOptions == null)
this.pdfOptions = new XPdfFontOptions();
return this.pdfOptions;
}
}
XPdfFontOptions pdfOptions;
/// <summary>
/// Indicates whether this XFont is encoded as Unicode.
/// </summary>
internal bool Unicode
{
get { return this.pdfOptions != null ? this.pdfOptions.FontEncoding == PdfFontEncoding.Unicode : false; }
}
/// <summary>
/// Gets the metrics.
/// </summary>
/// <value>The metrics.</value>
public XFontMetrics Metrics
{
get
{
if (this.fontMetrics == null)
{
FontDescriptor descriptor = FontDescriptorStock.NewInstance.CreateDescriptor(this);
this.fontMetrics = descriptor.FontMetrics;
}
return this.fontMetrics;
}
}
XFontMetrics fontMetrics;
#if GDI
#if UseGdiObjects
/// <summary>
/// Implicit conversion form Font to XFont
/// </summary>
public static implicit operator XFont(Font font)
{
//XFont xfont = new XFont(font.Name, font.Size, FontStyleFrom(font));
XFont xfont = new XFont(font, null);
return xfont;
}
#endif
internal Font RealizeGdiFont()
{
//if (this.font == null)
// this.font = new Font(this.familyName, this.size, (FontStyle)this.style);
return this.font;
}
internal Font font;
#endif
#if WPF && !SILVERLIGHT
internal Typeface RealizeWpfTypeface()
{
return this.typeface;
}
internal System.Windows.Media.FontFamily family;
internal Typeface typeface;
#endif
internal string familyName;
internal int unitsPerEm;
internal int cellSpace;
internal int cellAscent;
internal int cellDescent;
/// <summary>
/// Cache PdfFontTable.FontSelector to speed up finding the right PdfFont
/// if this font is used more than once.
/// </summary>
internal PdfFontTable.FontSelector selector;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace NetSiege.Api
{
/// <summary>
/// All the configurable settings for one test.
/// </summary>
public class TestSettings
{
#region Properties
/// <summary>
/// The minimum time to wait before issueing a new request
/// on one thread. Default = 1 second.
/// </summary>
public double MinPause = 1.0;
/// <summary>
/// The maximum time to wait before issueing a new request
/// on one thread. Default = 10 seconds.
/// </summary>
public double MaxPause = 10.0;
/// <summary>
/// The number of threads to test with. Default = 5 threads.
/// </summary>
public int ThreadCount = 5;
/// <summary>
/// The total duration of the test, in seconds. Default = 5 minutes.
/// </summary>
public double TestSeconds = 60*5;
/// <summary>
/// The set of URLs to randomly hit during tests.
/// </summary>
public readonly List<string> Urls = new List<string>();
/// <summary>
/// True iff the console app should output the usage documentation
/// </summary>
public bool ShowHelp = false;
/// <summary>
/// True iff the version string should be printed.
/// </summary>
public bool ShowVersion = false;
#endregion
#region Methods
/// <summary>
/// Creates a TestSettings instance from the command line arguments,
/// throwing exceptions for any invalid options.
/// </summary>
public static TestSettings ParseCmdArguments(string[] args)
{
// create settings object with default options
var settings = new TestSettings ();
string urlfile = null;
foreach (var arg in args)
{
if (arg.StartsWith ("-"))
{
// check all long versions without parameters
if (arg == "-version")
{
settings.ShowVersion = true;
} else if (arg == "-help")
{
settings.ShowHelp = true;
} else if (arg.StartsWith ("-concurrent="))
{
settings.ThreadCount = (int)ParseNumber (arg, "-concurrent=".Length);
} else if (arg.StartsWith ("-time="))
{
settings.TestSeconds = ParseTime (arg, "-time=".Length);
} else if (arg.StartsWith ("-delay="))
{
settings.MaxPause = ParseNumber (arg, "-delay=".Length);
} else if (arg.StartsWith ("-mindelay="))
{
settings.MinPause = ParseNumber (arg, "-mindelay=".Length);
}
// check all short versions
else if (arg == "-V")
{
settings.ShowVersion = true;
} else if (arg == "-h")
{
settings.ShowHelp = true;
} else if (arg.StartsWith ("-c"))
{
settings.ThreadCount = (int)ParseNumber (arg, "-c".Length);
} else if (arg.StartsWith ("-t"))
{
settings.TestSeconds = ParseTime (arg, "-t".Length);
} else if (arg.StartsWith ("-d"))
{
settings.MaxPause = ParseNumber (arg, "-d".Length);
} else if (arg.StartsWith ("-D"))
{
settings.MinPause = ParseNumber (arg, "-D".Length);
}
// invalid
else
{
throw new ArgumentException ("Unrecognized option " + arg);
}
}
else
{
if (urlfile != null)
{
throw new ArgumentException ("Only one UrlFile may be specified");
}
urlfile = arg;
}
}
// load UrlFile
if (urlfile == null)
{
throw new ArgumentException ("UrlFile is required");
}
settings.Urls.AddRange (File.ReadAllLines (urlfile));
return settings;
}
/// <summary>
/// Returns a list of command line arguments handled by ParseCmdArguments()
/// as a string of individual lines, optionally inserting some tabs before
/// each line.
/// </summary>
/// <param name="tabs">(optional) number of tabs to put at the start of each line</param>
public static string ListCmdArguments(int tabs = 0)
{
var sb = new StringBuilder ();
AddArg (sb, tabs, "-version", "-V", "Prints version information to the screen");
AddArg (sb, tabs, "-help", "-h", "Prints program help");
AddArg (sb, tabs, "-concurrent=NUM", "-c NUM", "Sets the number threads to use for a test (default: 5)");
AddArg (sb, tabs, "-time=NUMm", "-t NUMm", "Sets the time period for the test, where NUM is a number an m is a unit such as -t3600S, -t60M, or -t1H (default 3M");
AddArg (sb, tabs, "-delay=NUM", "-d NUM", "The random number of seconds to wait between requests (default: 10)");
AddArg (sb, tabs, "-mindelay=NUM", "-D NUM", "The minimum number of seconds to wait between requests (default: 1)");
return sb.ToString ();
}
#endregion
#region Private
/// <summary>
/// Parses a time with a unit of S, M, or H.
/// </summary>
private static double ParseTime(string arg, int i) {
string unit = ""+arg [arg.Length - 1];
string s = arg.Substring (i, arg.Length - (i + 1));
double d;
if (double.TryParse (s, out d))
{
switch (unit.ToUpper ())
{
case "S":
return d;
case "M":
return d * 60;
case "H":
return d * 60 * 60;
default:
throw new ArgumentException ("Invalid unit in argument " + arg);
}
} else
{
throw new ArgumentException ("Invalid time argument " + arg);
}
}
/// <summary>
/// Parses a number.
/// </summary>
private static double ParseNumber(string arg, int i) {
double d;
if (double.TryParse (arg.Substring (i), out d))
{
return d;
} else
{
throw new ArgumentException ("Invalid number argument " + arg);
}
}
/// <summary>
/// Adds one argument to the StringBuilder building usage information.
/// </summary>
private static void AddArg(StringBuilder sb, int tabs, string arg, string altArg, string description)
{
for (var i = 0; i < tabs; i++)
{
sb.Append ("\t");
}
sb.Append (altArg.PadRight(8));
sb.Append (arg.PadRight (20));
sb.Append (description);
sb.AppendLine ();
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in January 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using DotSpatial.Data.MiscUtil;
using DotSpatial.Projections;
namespace DotSpatial.Data
{
/// <summary>
/// This basically demonstrates how you would combine a type with a calculator in order to
/// construct a Binary Raster for the Integer type. It is effectively the same as
/// constructing a new BinaryRaster and specifying the parameter types int and IntCalculator.
/// </summary>
internal class BinaryRaster<T> : Raster<T> where T : struct, IEquatable<T>, IComparable<T>
{
public static readonly T MaxValue = ReadStaticField("MaxValue");
public static readonly T MinValue = ReadStaticField("MinValue");
#region Constructors
/// <summary>
/// Creates a completely empty raster that can be custom configured
/// </summary>
public BinaryRaster()
{
// This is basically an empty place holder until someone calls an Open or something.
}
/// <summary>
/// Creates a new BinaryRaster with the specified rows and columns.
/// If if the raster is less than 64 Million cells, it will be created only in memory,
/// and a Save method should be called when ready to save it to a file. Otherwise, it creates a blank file with
/// NoData values...which start out as 0.
/// </summary>
/// <param name="fileName">The fileName to write to</param>
/// <param name="numRows">Integer number of rows</param>
/// <param name="numColumns">Integer number of columns</param>
public BinaryRaster(string fileName, int numRows, int numColumns) :
this(fileName, numRows, numColumns, true)
{
// this just forces the inRam to default to true.
}
/// <summary>
/// Creates a new BinaryRaster with the specified rows and columns.
/// If inRam is true and the raster is less than 64 Million cells, it will be created only in memory,
/// and a Save method should be called when ready to save it to a file. Otherwise, it creates a blank file with
/// NoData values.
/// </summary>
/// <param name="fileName">The fileName to write to</param>
/// <param name="numRows">Integer number of rows</param>
/// <param name="numColumns">Integer number of columns</param>
/// <param name="inRam">If this is true and the raster is small enough, it will load this into memory and not save anything to the file.</param>
public BinaryRaster(string fileName, int numRows, int numColumns, bool inRam)
{
if (File.Exists(fileName))
base.Filename = fileName;
if (inRam && numColumns * numRows < 64000000)
base.IsInRam = true;
else
base.IsInRam = false;
base.NumRows = numRows;
base.NumColumns = numColumns;
Initialize();
}
#endregion
#region Methods
/// <summary>
/// Creates a duplicate version of this file. If copyValues is set to false, then a raster of NoData values is created
/// that has the same georeferencing information as the source file of this Raster, even if this raster is just a window.
/// If the specified fileName exists, rather than throwing an exception or taking an "overwrite" parameter, this
/// will throw the FileExists event, and cancel the copy if the cancel argument is set to true.
/// </summary>
/// <param name="fileName">The string fileName specifying where to create the new file.</param>
/// <param name="copyValues">If this is false, the same size and georeferencing values are used, but they are all set to NoData.</param>
public override void Copy(string fileName, bool copyValues)
{
if (fileName == Filename)
throw new ArgumentException(DataStrings.CannotCopyToSelf_S.Replace("%S", fileName));
if (File.Exists(fileName))
{
if (OnFileExists(fileName))
return; // The copy event was cancelled
// The copy event was not cancelled, so overwrite the file
File.Delete(fileName);
}
if (copyValues)
{
// this should be faster than copying values in code
File.Copy(Filename, fileName);
}
else
{
// since at this point, there is no file, a blank file will be created with empty values.
Write(fileName);
}
}
/// <summary>
/// This creates a completely new raster from the windowed domain on the original raster. This new raster
/// will have a separate source file, and values like NumRowsInFile will correspond to the newly created file.
/// All the values will be copied to the new source file. If inRam = true and the new raster is small enough,
/// the raster values will be loaded into memory.
/// </summary>
/// <param name="fileName"></param>
/// <param name="startRow">The 0 based integer index of the top row to copy from this raster. If this raster is itself a window, 0 represents the startRow from the file.</param>
/// <param name="endRow">The integer index of the bottom row to copy from this raster. The largest allowed value is NumRows - 1.</param>
/// <param name="startColumn">The 0 based integer index of the leftmost column to copy from this raster. If this raster is a window, 0 represents the startColumn from the file.</param>
/// <param name="endColumn">The 0 based integer index of the rightmost column to copy from this raster. The largest allowed value is NumColumns - 1</param>
/// <param name="copyValues">If this is true, the values are saved to the file. If this is false and the data can be loaded into Ram, no file handling is done. Otherwise, a file of NoData values is created.</param>
/// <param name="inRam">Boolean. If this is true and the window is small enough, a copy of the values will be loaded into memory.</param>
/// <returns>An implementation of IRaster</returns>
public new IRaster CopyWindow(string fileName, int startRow, int endRow, int startColumn, int endColumn,
bool copyValues, bool inRam)
{
int numCols = endColumn - startColumn + 1;
int numRows = endRow - startRow + 1;
var result = new BinaryRaster<T>(fileName, numCols, numRows, inRam) {Projection = Projection};
// The affine coefficients defining the world file are the same except that they are translated over. Only the position of the
// upper left corner changes. Everything else is the same as the previous raster.
var ac = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow);
result.Bounds = new RasterBounds(result.NumRows, result.NumColumns, ac);
if (IsInRam)
{
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, numRows);
// copy values directly using both data structures
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
result.Data[row][col] = Data[startRow + row][startColumn + col];
}
pm.CurrentValue = row;
}
pm.Reset();
if (result.IsInRam == false)
{
// Force the result raster to write itself to a file and then purge its memory.
result.Write(fileName);
result.Data = null;
}
}
else
{
if (result.IsInRam)
{
// the source is not in memory, so we just read the values from the file as if opening it directly from the file.
result.OpenWindow(Filename, startRow, endRow, startColumn, endColumn, true);
}
else
{
// Both sources are file based so we basically copy rows of bytes from one to the other.
FileStream source = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read);
result.WriteHeader(fileName);
FileStream dest = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None);
source.Seek(HeaderSize, SeekOrigin.Begin);
BinaryReader bReader = new BinaryReader(source);
BinaryWriter bWriter = new BinaryWriter(dest);
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, numRows);
// copy values directly using both data structures
source.Seek(NumColumnsInFile * startRow * ByteSize, SeekOrigin.Current);
for (int row = 0; row < numRows; row++)
{
source.Seek(numCols * ByteSize, SeekOrigin.Current);
byte[] rowData = bReader.ReadBytes(ByteSize * numCols);
bWriter.Write(rowData);
source.Seek(NumColumnsInFile - endColumn + 1, SeekOrigin.Current);
bWriter.Flush();
pm.CurrentValue = row;
}
pm.Reset();
}
}
return result;
}
/// <summary>
/// Gets the statistics for the entire file, not just the window portion specified for this raster.
/// </summary>
public override void GetStatistics()
{
if (IsInRam && this.IsFullyWindowed())
{
// The in-memory version of this is a little faster, so use it, but only if we can.
base.GetStatistics();
return;
}
// If we get here, we either need to check the file because no data is in memory or because
// the window that is in memory does not have all the values.
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
fs.Seek(HeaderSize, SeekOrigin.Begin);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
"Calculating Statistics for the entire raster " + Filename,
NumRowsInFile);
int count = 0;
T min = MinValue;
T max = MaxValue;
double total = 0;
double sqrTotal = 0;
T noDataValue = ConvertTo<T>(NoDataValue);
for (int row = 0; row < NumRowsInFile; row++)
{
for (int col = 0; col < NumColumnsInFile; col++)
{
T val = br.Read<T>();
if (!EqualityComparer<T>.Default.Equals(val, noDataValue))
{
if (Operator.GreaterThan(val, max)) max = val;
if (Operator.LessThan(val, min)) min = val;
double valAsDouble = Convert.ToDouble(val);
total += valAsDouble;
sqrTotal += valAsDouble * valAsDouble;
count++;
}
}
pm.CurrentValue = row;
}
Value.Updated = false;
Minimum = Convert.ToDouble(min);
Maximum = Convert.ToDouble(max);
Mean = total / count;
NumValueCells = count;
StdDeviation = (float)Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells));
br.Close();
}
/// <summary>
/// This creates a window from this raster. The window will still save to the same
/// source file, but only has access to a small window of data, so it can be loaded like a buffer.
/// The georeferenced extents will be for the new window, not the original raster. startRow and endRow
/// will exist in the new raster, however, so that it knows how to copy values back to the original raster.
/// </summary>
/// <param name="startRow">The 0 based integer index of the top row to get from this raster. If this raster is itself a window, 0 represents the startRow from the file.</param>
/// <param name="endRow">The integer index of the bottom row to get from this raster. The largest allowed value is NumRows - 1.</param>
/// <param name="startColumn">The 0 based integer index of the leftmost column to get from this raster. If this raster is a window, 0 represents the startColumn from the file.</param>
/// <param name="endColumn">The 0 based integer index of the rightmost column to get from this raster. The largest allowed value is NumColumns - 1</param>
/// <param name="inRam">Boolean. If this is true and the window is small enough, a copy of the values will be loaded into memory.</param>
/// <returns>An implementation of IRaster</returns>
public new IRaster GetWindow(int startRow, int endRow, int startColumn, int endColumn, bool inRam)
{
int numCols = endColumn - startColumn + 1;
int numRows = endRow - startRow + 1;
var result = new BinaryRaster<T>
{
Filename = Filename,
Projection = Projection,
DataType = typeof (int),
NumRows = endRow - startRow + 1,
NumColumns = endColumn - startColumn + 1,
NumRowsInFile = NumRowsInFile,
NumColumnsInFile = NumColumnsInFile,
NoDataValue = NoDataValue,
StartColumn = startColumn + StartColumn,
StartRow = startRow + StartRow,
EndColumn = endColumn + StartColumn,
EndRow = EndRow + StartRow
};
// Reposition the "raster" so that it matches the window, not the whole raster
var ac = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow);
result.Bounds = new RasterBounds(result.NumRows, result.NumColumns, ac);
// Now we can copy any values currently in memory.
if (IsInRam)
{
//result.ReadHeader(Filename);
result.Data = new T[numRows][];
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, endRow)
{
StartValue = startRow
};
// copy values directly using both data structures
for (int row = 0; row < numRows; row++)
{
result.Data[row] = new T[numCols];
for (int col = 0; col < numCols; col++)
{
result.Data[row][col] = Data[startRow + row][startColumn + col];
}
pm.CurrentValue = row;
}
pm.Reset();
}
else
result.OpenWindow(Filename, startRow, endRow, startColumn, endColumn, inRam);
result.Value = new ValueGrid<T>(result);
return result;
}
/// <summary>
/// Obtains only the statistics for the small window specified by startRow, endRow etc.
/// </summary>
public new void GetWindowStatistics()
{
if (IsInRam)
{
// don't bother to do file calculations if the whole raster is in memory
base.GetWindowStatistics();
return;
}
// The window was not in memory, so go ahead and get statistics for the window from the file.
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, NumColumns * ByteSize);
BinaryReader br = new BinaryReader(fs);
fs.Seek(HeaderSize, SeekOrigin.Begin);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
"Calculating Statistics for the entire raster " + Filename, NumRows);
double total = 0;
double sqrTotal = 0;
int count = 0;
int byteSize = ByteSize; // cache this for faster calcs
int min = int.MaxValue;
int max = int.MinValue;
fs.Seek(StartRow * ByteSize * NumColumnsInFile, SeekOrigin.Current); // To top edge of the Window
int noDataValue = Convert.ToInt32(NoDataValue);
for (int row = 0; row < NumRows; row++)
{
fs.Seek(StartColumn * byteSize, SeekOrigin.Current); // to the left edge of the window
for (int col = 0; col < NumColumns; col++)
{
int val = br.ReadInt32();
if (val == noDataValue || val <= -100000) continue;
if (val > max) max = val;
if (val < min) min = val;
double dblVal = val;
total += dblVal;
sqrTotal += dblVal * dblVal;
count++;
}
fs.Seek(NumColumnsInFile - EndRow - 1, SeekOrigin.Current); // skip to the end of this row.
pm.CurrentValue = row;
}
Minimum = min;
Maximum = max;
NumValueCells = count;
StdDeviation = (float)Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells));
br.Close();
}
/// <summary>
/// Opens the specified file into this raster.
/// </summary>
public override void Open()
{
Open(Filename, true);
}
/// <summary>
/// Opens a new instance of the BinaryRaster
/// </summary>
/// <param name="fileName">The string fileName of the raster file to open</param>
/// <param name="inRam">Boolean, indicates whether or not the values for the raster should be loaded into memory</param>
public virtual void Open(string fileName, bool inRam)
{
Filename = fileName;
ReadHeader(fileName);
if (inRam)
{
if (NumRowsInFile * NumColumnsInFile < 64000000)
{
IsInRam = true;
Read();
}
}
Value = new ValueGrid<T>(this);
}
/// <summary>
/// This converts this object into a raster defined by the specified window dimensions.
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <param name="startRow">The integer row index to become the first row to load into this raster.</param>
/// <param name="endRow">The 0 based integer row index to become the last row included in this raster.</param>
/// <param name="startColumn">The 0 based integer column index for the first column of the raster.</param>
/// <param name="endColumn">The 0 based integer column index for the last column to include in this raster.</param>
/// <param name="inRam">Boolean. If this is true and the window is small enough, this will load the window into ram.</param>
public virtual void OpenWindow(string fileName, int startRow, int endRow, int startColumn, int endColumn,
bool inRam)
{
Filename = fileName;
ReadHeader(fileName);
NumRows = endRow - startRow + 1;
NumColumns = endColumn - startColumn + 1;
StartColumn = startColumn;
StartRow = startRow;
EndColumn = endColumn;
EndRow = EndRow;
// Reposition the "raster" so that it matches the window, not the whole raster
Bounds.AffineCoefficients = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow);
if (inRam)
{
if (NumRows * NumColumns < 64000000)
{
IsInRam = true;
Read();
}
}
Value = new ValueGrid<T>(this);
}
/// <summary>
/// Copies the contents from the specified sourceRaster into this sourceRaster. If both rasters are InRam, this does not affect the files.
/// </summary>
/// <param name="sourceRaster">The raster of values to paste into this raster. If the CellWidth and CellHeight values do not match between the files,
/// an exception will be thrown. If the sourceRaster overlaps with the edge of this raster, only the intersecting region will be
/// pasted.</param>
/// <param name="startRow">Specifies the row in this raster where the top row of the sourceRaster will be pasted </param>
/// <param name="startColumn">Specifies the column in this raster where the left column of the sourceRaster will be pasted.</param>
public void PasteRaster(Raster<T> sourceRaster, int startRow, int startColumn)
{
int byteSize = ByteSize;
if (sourceRaster.DataType != typeof(int))
{
throw new ArgumentException(
DataStrings.ArgumentOfWrongType_S1_S2.Replace("%S1", "sourceRaster").Replace("%S2", "BinaryRaster"));
}
if (startRow + sourceRaster.NumRows <= 0) return; // sourceRaster is above this raster
if (startColumn + sourceRaster.NumColumns <= 0) return; // sourceRaster is left of this raster
if (startRow > NumRows) return; // sourceRaster is below this raster
if (startColumn > NumColumns) return; // sourceRaster is to the right of this raster
if (sourceRaster.CellWidth != CellWidth || sourceRaster.CellHeight != CellHeight)
throw new ArgumentException(DataStrings.RastersNeedSameCellSize);
// These are specified in coordinates that match the source raster
int sourceStartColumn = 0;
int sourceStartRow = 0;
int destStartColumn = startColumn;
int destStartRow = startRow;
int numPasteColumns = sourceRaster.NumColumns;
int numPasteRows = sourceRaster.NumRows;
// adjust range to cover only the overlapping sections
if (startColumn < 0)
{
sourceStartColumn = -startColumn;
destStartColumn = 0;
}
if (startRow < 0)
{
sourceStartRow = -startRow;
destStartRow = 0;
}
if (numPasteRows + destStartRow > NumRows) numPasteRows = (NumRows - destStartRow);
if (numPasteColumns + destStartColumn > NumColumns) numPasteColumns = (NumColumns - destStartRow);
if (IsInRam)
{
// ---------------------- RAM BASED ------------------------------------------------------
if (sourceRaster.IsInRam)
{
// both members are inram, so directly copy values.
for (int row = 0; row < numPasteRows; row++)
{
for (int col = 0; col < numPasteColumns; col++)
{
// since we are copying direct, we don't have to do a type check on T
Data[destStartRow + row][destStartColumn + col] =
sourceRaster.Data[sourceStartRow + row][sourceStartColumn + col];
}
}
}
else
{
FileStream fs = new FileStream(sourceRaster.Filename, FileMode.Open, FileAccess.Write,
FileShare.None, (numPasteColumns) * byteSize);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
DataStrings.ReadingValuesFrom_S.Replace("%S",
sourceRaster.
Filename),
numPasteRows);
fs.Seek(HeaderSize, SeekOrigin.Begin);
// Position the binary reader at the top of the "sourceRaster"
fs.Seek(sourceStartRow * sourceRaster.NumColumnsInFile * byteSize, SeekOrigin.Current);
BinaryReader br = new BinaryReader(fs);
for (int row = 0; row < numPasteRows; row++)
{
// Position the binary reader at the beginning of the sourceRaster
fs.Seek(byteSize * sourceStartColumn, SeekOrigin.Current);
for (int col = 0; col < numPasteColumns; col++)
{
Data[destStartRow + row][destStartColumn + col] = br.Read<T>();
}
pm.CurrentValue = row;
fs.Seek(byteSize * (NumColumnsInFile - sourceStartColumn - numPasteColumns), SeekOrigin.Current);
}
br.Close();
}
// The statistics will have changed with the newly pasted data involved
GetStatistics();
}
else
{
// ----------------------------------------- FILE BASED ---------------------------------
FileStream writefs = new FileStream(Filename, FileMode.Open, FileAccess.Write, FileShare.None,
NumColumns * byteSize);
BinaryWriter bWriter = new BinaryWriter(writefs);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
DataStrings.WritingValues_S.Replace("%S", Filename),
numPasteRows);
writefs.Seek(HeaderSize, SeekOrigin.Begin);
writefs.Seek(destStartRow * NumColumnsInFile * byteSize, SeekOrigin.Current);
// advance to top of paste window area
if (sourceRaster.IsInRam)
{
// we can just write values
for (int row = 0; row < numPasteColumns; row++)
{
// Position the binary reader at the beginning of the sourceRaster
writefs.Seek(byteSize * destStartColumn, SeekOrigin.Current);
for (int col = 0; col < numPasteColumns; col++)
{
T val = sourceRaster.Data[sourceStartRow + row][sourceStartColumn + col];
bWriter.Write(val);
}
pm.CurrentValue = row;
writefs.Seek(byteSize * (NumColumnsInFile - destStartColumn - numPasteColumns), SeekOrigin.Current);
}
}
else
{
// Since everything is handled from a file, we don't have to type check. Just copy the bytes.
FileStream readfs = new FileStream(sourceRaster.Filename, FileMode.Open, FileAccess.Read,
FileShare.Read, numPasteColumns * byteSize);
BinaryReader bReader = new BinaryReader(readfs);
readfs.Seek(HeaderSize, SeekOrigin.Begin);
readfs.Seek(sourceStartRow * sourceRaster.NumColumnsInFile * byteSize, SeekOrigin.Current);
// advances to top of paste window area
for (int row = 0; row < numPasteRows; row++)
{
readfs.Seek(sourceStartColumn * byteSize, SeekOrigin.Current);
writefs.Seek(destStartColumn * byteSize, SeekOrigin.Current);
byte[] rowData = bReader.ReadBytes(numPasteColumns * byteSize);
bWriter.Write(rowData);
readfs.Seek(sourceRaster.NumColumnsInFile - sourceStartColumn - numPasteColumns,
SeekOrigin.Current);
writefs.Seek(NumColumnsInFile - destStartColumn - numPasteColumns, SeekOrigin.Current);
}
bReader.Close();
}
bWriter.Close();
}
}
private U ConvertTo<U>(double value)
{
// we don't consider whether the current culture might cause an incorrect conversion.
object ret = null;
if (typeof(U) == typeof(Byte))
ret = Convert.ToByte(value);
else if (typeof(U) == typeof(Double))
ret = Convert.ToDouble(value);
else if (typeof(U) == typeof(Decimal))
ret = Convert.ToDecimal(value);
else if (typeof(U) == typeof(Int16))
ret = Convert.ToInt16(value);
else if (typeof(U) == typeof(Int32))
ret = Convert.ToInt32(value);
else if (typeof(U) == typeof(Int64))
ret = Convert.ToInt64(value);
else if (typeof(U) == typeof(Single))
ret = Convert.ToSingle(value);
else if (typeof(U) == typeof(Boolean))
ret = Convert.ToBoolean(value);
if (ret == null)
throw new NotSupportedException("Unable to convert type - " + typeof(U));
return (U)ret;
}
/// <summary>
/// Reads the the contents for the "window" specified by the start and end values
/// for the rows and columns.
/// </summary>
public void Read()
{
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, NumColumns * ByteSize);
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.ReadingValuesFrom_S.Replace("%S", Filename), NumRows);
fs.Seek(HeaderSize, SeekOrigin.Begin);
// Position the binary reader at the top of the "window"
fs.Seek(StartRow * NumColumnsInFile * ByteSize, SeekOrigin.Current);
BinaryReader br = new BinaryReader(fs);
Data = new T[NumRows][];
T min = MinValue;
T max = MaxValue;
double total = 0;
double sqrTotal = 0;
T noDataValue = ConvertTo<T>(NoDataValue);
for (int row = 0; row < NumRows; row++)
{
Data[row] = new T[NumColumns];
// Position the binary reader at the beginning of the window
fs.Seek(4 * StartColumn, SeekOrigin.Current);
for (int col = 0; col < NumColumns; col++)
{
T val = br.Read<T>();
if (!EqualityComparer<T>.Default.Equals(val, noDataValue))
{
if (Operator.GreaterThan(val, max)) max = val;
if (Operator.LessThan(val, min)) min = val;
double valAsDouble = Convert.ToDouble(val);
total += valAsDouble;
sqrTotal += valAsDouble * valAsDouble;
NumValueCells++;
}
Data[row][col] = val;
}
pm.CurrentValue = row;
fs.Seek(ByteSize * (NumColumnsInFile - EndColumn - 1), SeekOrigin.Current);
}
Maximum = Convert.ToDouble(max);
Minimum = Convert.ToDouble(min);
StdDeviation = Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells));
br.Close();
}
// http://stackoverflow.com/questions/4418636/c-sharp-generics-how-to-use-x-maxvalue-x-minvalue-int-float-double-in-a
private static T ReadStaticField(string name)
{
FieldInfo field = typeof(T).GetField(name, BindingFlags.Public | BindingFlags.Static);
if (field == null)
{
// There's no TypeArgumentException, unfortunately.
throw new InvalidOperationException("Invalid type argument: " + typeof(T).Name);
}
return (T)field.GetValue(null);
}
/// <summary>
/// Writes the header, regardless of which subtype of binary raster this is written for
/// </summary>
/// <param name="fileName">The string fileName specifying what file to load</param>
public void ReadHeader(string fileName)
{
BinaryReader br = new BinaryReader(new FileStream(fileName, FileMode.Open));
StartColumn = 0;
NumColumns = br.ReadInt32();
NumColumnsInFile = NumColumns;
EndColumn = NumColumns - 1;
StartRow = 0;
NumRows = br.ReadInt32();
NumRowsInFile = NumRows;
EndRow = NumRows - 1;
Bounds = new RasterBounds(NumRows, NumColumns, new[] { 0.0, 1.0, 0.0, NumRows, 0.0, -1.0 });
CellWidth = br.ReadDouble();
Bounds.AffineCoefficients[5] = -br.ReadDouble(); // dy
Xllcenter = br.ReadDouble();
Yllcenter = br.ReadDouble();
RasterDataType dataType = (RasterDataType)br.ReadInt32();
if (dataType != RasterDataType.INTEGER)
{
throw new ArgumentException(
DataStrings.ArgumentOfWrongType_S1_S2.Replace("%S1", fileName).Replace("%S2", "BinaryShortRaster"));
}
NoDataValue = br.ReadInt32();
string proj = Encoding.ASCII.GetString(br.ReadBytes(255)).Replace('\0', ' ').Trim();
Projection = ProjectionInfo.FromProj4String(proj);
Notes = Encoding.ASCII.GetString(br.ReadBytes(255)).Replace('\0', ' ').Trim();
if (Notes.Length == 0) Notes = null;
br.Close();
}
/// <summary>
/// The string fileName where this will begin to write data by clearing the existing file
/// </summary>
/// <param name="fileName">a fileName to write data to</param>
public void WriteHeader(string fileName)
{
using (var bw = new BinaryWriter(new FileStream(fileName, FileMode.OpenOrCreate)))
{
bw.Write(NumColumnsInFile);
bw.Write(NumRowsInFile);
bw.Write(CellWidth);
bw.Write(CellHeight);
bw.Write(Xllcenter);
bw.Write(Yllcenter);
bw.Write((int) RasterDataType.INTEGER);
bw.Write(Convert.ToInt32(NoDataValue));
// These are each 256 bytes because they are ASCII encoded, not the standard DotNet Unicode
byte[] proj = new byte[255];
if (Projection != null)
{
byte[] temp = Encoding.ASCII.GetBytes(Projection.ToProj4String());
int len = Math.Min(temp.Length, 255);
for (int i = 0; i < len; i++)
{
proj[i] = temp[i];
}
}
bw.Write(proj);
byte[] note = new byte[255];
if (Notes != null)
{
byte[] temp = Encoding.ASCII.GetBytes(Notes);
int len = Math.Min(temp.Length, 255);
for (int i = 0; i < len; i++)
{
note[i] = temp[i];
}
}
bw.Write(note);
}
}
/// <summary>
/// This would be a horrible choice for any kind of serious process, but is provided as
/// a way to write values directly to the file.
/// </summary>
/// <param name="row">The 0 based integer row index for the file to write to.</param>
/// <param name="column">The 0 based column index for the file to write to.</param>
/// <param name="value">The actual value to write.</param>
public void WriteValue(int row, int column, int value)
{
using (var fs = new FileStream(Filename, FileMode.Open, FileAccess.Write, FileShare.None))
{
fs.Seek(HeaderSize, SeekOrigin.Begin);
fs.Seek(row*NumColumnsInFile*ByteSize, SeekOrigin.Current);
fs.Seek(column*ByteSize, SeekOrigin.Current);
using (var bw = new BinaryWriter(fs))
{
bw.Write(value);
}
}
}
/// <summary>
/// Saves the values in memory to the disk.
/// </summary>
public override void Save()
{
Write(Filename);
}
/// <summary>
/// If no file exists, this writes the header and no-data values. If a file exists, it will assume
/// that data already has been filled in the file and will attempt to insert the data values
/// as a window into the file. If you want to create a copy of the file and values, just use
/// System.IO.File.Copy, it almost certainly would be much more optimized.
/// </summary>
/// <param name="fileName">The string fileName to write values to.</param>
public void Write(string fileName)
{
FileStream fs;
BinaryWriter bw;
ProgressMeter pm = new ProgressMeter(ProgressHandler, "Writing values to " + fileName, NumRows);
long expectedByteCount = NumRows * NumColumns * ByteSize;
if (expectedByteCount < 1000000) pm.StepPercent = 5;
if (expectedByteCount < 5000000) pm.StepPercent = 10;
if (expectedByteCount < 100000) pm.StepPercent = 50;
if (File.Exists(fileName))
{
FileInfo fi = new FileInfo(fileName);
// if the following test fails, then the target raster doesn't fit the bill for pasting into, so clear it and write a new one.
if (fi.Length == HeaderSize + ByteSize * NumColumnsInFile * NumRowsInFile)
{
WriteHeader(fileName);
// assume that we already have a file set up for us, and just write the window of values into the appropriate place.
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None,
ByteSize * NumColumns);
fs.Seek(HeaderSize, SeekOrigin.Begin);
fs.Seek(ByteSize * StartRow, SeekOrigin.Current);
bw = new BinaryWriter(fs); // encoding doesn't matter because we don't have characters
for (int row = 0; row < NumRows; row++)
{
fs.Seek(StartColumn * ByteSize, SeekOrigin.Current);
for (int col = 0; col < NumColumns; col++)
{
// this is the only line that is type dependant, but I don't want to type check on every value
bw.Write(Data[row][col]);
}
fs.Flush(); // Since I am buffering, make sure that I write the buffered data before seeking
fs.Seek((NumColumnsInFile - EndColumn - 1) * ByteSize, SeekOrigin.Current);
pm.CurrentValue = row;
}
pm.Reset();
bw.Close();
return;
}
// If we got here, either the file didn't exist or didn't match the specifications correctly, so write a new one.
Debug.WriteLine("The size of the file was " + fi.Length + " which didn't match the expected " +
HeaderSize + ByteSize * NumColumnsInFile * NumRowsInFile);
File.Delete(fileName);
}
if (File.Exists(fileName)) File.Delete(fileName);
WriteHeader(fileName);
// Open as append and it will automatically skip the header for us.
fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None, ByteSize * NumColumnsInFile);
bw = new BinaryWriter(fs);
// the row and column counters here are relative to the whole file, not just the window that is currently in memory.
pm.EndValue = NumRowsInFile;
int noDataValue = Convert.ToInt32(NoDataValue);
for (int row = 0; row < NumRowsInFile; row++)
{
for (int col = 0; col < NumColumnsInFile; col++)
{
if (row < StartRow || row > EndRow || col < StartColumn || col > EndColumn)
bw.Write(Convert.ToInt32(noDataValue));
else
bw.Write(Data[row - StartRow][col - StartColumn]);
}
pm.CurrentValue = row;
}
fs.Flush(); // flush anything that hasn't gotten written yet.
pm.Reset();
bw.Close();
}
#endregion
#region Properties
/// <summary>
/// Returns the size of T in bytes. This should be overridden, but
/// exists as a "just-in-case" implementation that works for structs,
/// but definitely won't work correctly for objects.
/// </summary>
public override int ByteSize
{
get { return Marshal.SizeOf(typeof(T)); }
}
/// <summary>
/// All the binary rasters use the Binary file type
/// </summary>
public override RasterFileType FileType
{
get { return RasterFileType.BINARY; }
}
/// <summary>
/// This is always 1 band
/// </summary>
public override int NumBands
{
get { return 1; }
}
/// <summary>
/// Gets the size of the header. There is one no-data value in the header.
/// </summary>
public virtual int HeaderSize
{
get { return 554 + ByteSize; }
}
#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.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoAll
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // P/Invoke to Win32 function
public void TestAllCultures()
{
Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed");
Assert.All(cultures, Validate);
}
private void Validate(CultureInfo ci)
{
Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME));
// si-LK has some special case when running on Win7 so we just ignore this one
if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase))
{
Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName);
}
// zh-Hans and zh-Hant has different behavior on different platform
Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase);
Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME));
ValidateDTFI(ci);
ValidateNFI(ci);
ValidateRegionInfo(ci);
}
private void ValidateDTFI(CultureInfo ci)
{
DateTimeFormatInfo dtfi = ci.DateTimeFormat;
Calendar cal = dtfi.Calendar;
int calId = GetCalendarId(cal);
Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(calId, GetDefaultcalendar(ci));
Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK)));
Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR));
Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true));
Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern);
Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern);
Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern);
string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0];
string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE));
string longTimePattern1 = GetTimeFormats(ci, 0)[0];
string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT));
string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1;
string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2;
Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 });
Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 });
Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 });
Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) });
Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) });
Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) });
int eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
}
private void ValidateNFI(CultureInfo ci)
{
NumberFormatInfo nfi = ci.NumberFormat;
Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol);
}
private void ValidateRegionInfo(CultureInfo ci)
{
if (ci.Name.Length == 0) // no region for invariant
return;
RegionInfo ri = new RegionInfo(ci.Name);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol);
Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name
ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name
Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase);
}
private int[] ConvertWin32GroupString(string win32Str)
{
// None of these cases make any sense
if (win32Str == null || win32Str.Length == 0)
{
return (new int[] { 3 });
}
if (win32Str[0] == '0')
{
return (new int[] { 0 });
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[win32Str.Length - 1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[(win32Str.Length / 2)];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[values.Length - 1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return (values);
}
private List<string> _timePatterns;
private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam)
{
_timePatterns.Add(ReescapeWin32String(lpTimeFormatString));
return true;
}
private string[] GetTimeFormats(CultureInfo ci, uint flags)
{
_timePatterns = new List<string>();
Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), string.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags));
return _timePatterns.ToArray();
}
internal string ReescapeWin32String(string str)
{
// If we don't have data, then don't try anything
if (str == null)
return null;
StringBuilder result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
if (result != null)
result.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[13];
for (uint i = 0; i < 13; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i, false);
}
return names;
}
private int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
private string[] GetDayNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[7];
for (uint i = 1; i < 7; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true);
}
names[0] = GetCalendarInfo(ci, calendar, calType + 6, true);
return names;
}
private int GetCalendarId(Calendar cal)
{
int calId = 0;
if (cal is System.Globalization.GregorianCalendar)
{
calId = (int)(cal as GregorianCalendar).CalendarType;
}
else if (cal is System.Globalization.JapaneseCalendar)
{
calId = CAL_JAPAN;
}
else if (cal is System.Globalization.TaiwanCalendar)
{
calId = CAL_TAIWAN;
}
else if (cal is System.Globalization.KoreanCalendar)
{
calId = CAL_KOREA;
}
else if (cal is System.Globalization.HijriCalendar)
{
calId = CAL_HIJRI;
}
else if (cal is System.Globalization.ThaiBuddhistCalendar)
{
calId = CAL_THAI;
}
else if (cal is System.Globalization.HebrewCalendar)
{
calId = CAL_HEBREW;
}
else if (cal is System.Globalization.UmAlQuraCalendar)
{
calId = CAL_UMALQURA;
}
else if (cal is System.Globalization.PersianCalendar)
{
calId = CAL_PERSIAN;
}
else
{
throw new KeyNotFoundException(string.Format("Got a calendar {0} which we cannot map its Id", cal));
}
return calId;
}
internal bool EnumLocales(string name, uint dwFlags, IntPtr param)
{
CultureInfo ci = new CultureInfo(name);
if (!ci.IsNeutralCulture)
cultures.Add(ci);
return true;
}
private string GetLocaleInfo(CultureInfo ci, uint lctype)
{
Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, string.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci));
return sb.ToString();
}
private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail)
{
if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0)
{
Assert.False(throwInFail, string.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar));
return "";
}
return ReescapeWin32String(sb.ToString());
}
private List<int> _optionalCals = new List<int>();
private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_optionalCals.Add(calendar);
return true;
}
private int[] GetOptionalCalendars(CultureInfo ci)
{
_optionalCals = new List<int>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed.");
return _optionalCals.ToArray();
}
private List<string> _calPatterns;
private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_calPatterns.Add(ReescapeWin32String(lpCalendarInfoString));
return true;
}
private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType)
{
_calPatterns = new List<string>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo.");
return _calPatterns.ToArray();
}
private int GetDefaultcalendar(CultureInfo ci)
{
int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE);
if (calId != 0)
return calId;
int[] cals = GetOptionalCalendars(ci);
Assert.True(cals.Length > 0);
return cals[0];
}
private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType)
{
int data = 0;
Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, string.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType));
return data;
}
internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param);
internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam);
internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam);
internal static StringBuilder sb = new StringBuilder(400);
internal static List<CultureInfo> cultures = new List<CultureInfo>();
internal const uint LOCALE_WINDOWS = 0x00000001;
internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072;
internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073;
internal const uint LOCALE_SPARENT = 0x0000006d;
internal const uint LOCALE_SISO639LANGNAME = 0x00000059;
internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM"
internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM"
internal const uint LOCALE_ICALENDARTYPE = 0x00001009;
internal const uint LOCALE_RETURN_NUMBER = 0x20000000;
internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D;
internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
internal const uint LOCALE_SLONGDATE = 0x00000020;
internal const uint LOCALE_STIMEFORMAT = 0x00001003;
internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000;
internal const uint LOCALE_SSHORTDATE = 0x0000001F;
internal const uint LOCALE_SSHORTTIME = 0x00000079;
internal const uint LOCALE_SYEARMONTH = 0x00001006;
internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign
internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign
internal const uint LOCALE_SDECIMAL = 0x0000000E;
internal const uint LOCALE_STHOUSAND = 0x0000000F;
internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017;
internal const uint LOCALE_SMONDECIMALSEP = 0x00000016;
internal const uint LOCALE_SCURRENCY = 0x00000014;
internal const uint LOCALE_IDIGITS = 0x00000011;
internal const uint LOCALE_ICURRDIGITS = 0x00000019;
internal const uint LOCALE_ICURRENCY = 0x0000001B;
internal const uint LOCALE_INEGCURR = 0x0000001C;
internal const uint LOCALE_INEGNUMBER = 0x00001010;
internal const uint LOCALE_SMONGROUPING = 0x00000018;
internal const uint LOCALE_SNAN = 0x00000069;
internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity
internal const uint LOCALE_SGROUPING = 0x00000010;
internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074;
internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075;
internal const uint LOCALE_SPERCENT = 0x00000076;
internal const uint LOCALE_SPERMILLE = 0x00000077;
internal const uint LOCALE_SPOSINFINITY = 0x0000006a;
internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002;
internal const uint LOCALE_IMEASURE = 0x0000000D;
internal const uint LOCALE_SINTLSYMBOL = 0x00000015;
internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008;
internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e;
internal const uint CAL_SMONTHNAME1 = 0x00000015;
internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
internal const uint CAL_ICALINTVALUE = 0x00000001;
internal const uint CAL_SDAYNAME1 = 0x00000007;
internal const uint CAL_SLONGDATE = 0x00000006;
internal const uint CAL_SMONTHDAY = 0x00000038;
internal const uint CAL_SSHORTDATE = 0x00000005;
internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031;
internal const uint CAL_SYEARMONTH = 0x0000002f;
internal const uint CAL_SERASTRING = 0x00000004;
internal const uint CAL_SABBREVERASTRING = 0x00000039;
internal const uint ENUM_ALL_CALENDARS = 0xffffffff;
internal const uint TIME_NOSECONDS = 0x00000002;
internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar
internal const int CAL_TAIWAN = 4; // Taiwan Era calendar
internal const int CAL_KOREA = 5; // Korean Tangun Era calendar
internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar
internal const int CAL_THAI = 7; // Thai calendar
internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar
internal const int CAL_PERSIAN = 22;
internal const int CAL_UMALQURA = 23;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);
public static IEnumerable<object[]> CultureInfo_TestData()
{
yield return new object[] { "en" , 0x0009, "en-US", "eng", "ENU", "en" , "en-US" };
yield return new object[] { "ar" , 0x0001, "ar-SA", "ara", "ARA", "ar" , "en-US" };
yield return new object[] { "en-US" , 0x0409, "en-US", "eng", "ENU", "en-US" , "en-US" };
yield return new object[] { "ar-SA" , 0x0401, "ar-SA", "ara", "ARA", "ar-SA" , "en-US" };
yield return new object[] { "ja-JP" , 0x0411, "ja-JP", "jpn", "JPN", "ja-JP" , "ja-JP" };
yield return new object[] { "zh-CN" , 0x0804, "zh-CN", "zho", "CHS", "zh-Hans-CN" , "zh-CN" };
yield return new object[] { "en-GB" , 0x0809, "en-GB", "eng", "ENG", "en-GB" , "en-GB" };
yield return new object[] { "tr-TR" , 0x041f, "tr-TR", "tur", "TRK", "tr-TR" , "tr-TR" };
}
[Theory]
[MemberData(nameof(CultureInfo_TestData))]
public void LcidTest(string cultureName, int lcid, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName)
{
_ = alternativeCultureName;
CultureInfo ci = new CultureInfo(lcid);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.True(ci.UseUserOverride, "UseUserOverride for lcid created culture expected to be true");
Assert.False(ci.IsReadOnly, "IsReadOnly for lcid created culture expected to be false");
Assert.Equal(threeLetterISOLanguageName, ci.ThreeLetterISOLanguageName);
Assert.Equal(threeLetterWindowsLanguageName, ci.ThreeLetterWindowsLanguageName);
ci = new CultureInfo(cultureName);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.True(ci.UseUserOverride, "UseUserOverride for named created culture expected to be true");
Assert.False(ci.IsReadOnly, "IsReadOnly for named created culture expected to be false");
ci = new CultureInfo(lcid, false);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with false user override culture expected to be false");
Assert.False(ci.IsReadOnly, "IsReadOnly with false user override culture expected to be false");
ci = CultureInfo.GetCultureInfo(lcid);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and lcid expected to be false");
Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and lcid expected to be true");
ci = CultureInfo.GetCultureInfo(cultureName);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and name expected to be false");
Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and name expected to be true");
ci = CultureInfo.GetCultureInfo(cultureName, "");
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and sort name expected to be false");
Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and sort name expected to be true");
Assert.Equal(CultureInfo.InvariantCulture.TextInfo, ci.TextInfo);
Assert.Equal(CultureInfo.InvariantCulture.CompareInfo, ci.CompareInfo);
ci = CultureInfo.CreateSpecificCulture(cultureName);
Assert.Equal(specificCultureName, ci.Name);
ci = CultureInfo.GetCultureInfoByIetfLanguageTag(cultureName);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(ci.Name, ci.IetfLanguageTag);
Assert.Equal(lcid, ci.KeyboardLayoutId);
Assert.Equal(consoleUICultureName, ci.GetConsoleFallbackUICulture().Name);
}
[Fact]
public void InstalledUICultureTest()
{
var c1 = CultureInfo.InstalledUICulture;
var c2 = CultureInfo.InstalledUICulture;
// we cannot expect the value we get for InstalledUICulture without reading the OS.
// instead we test ensuring the value doesn't change if we requested it multiple times.
Assert.Equal(c1.Name, c2.Name);
}
[Theory]
[MemberData(nameof(CultureInfo_TestData))]
public void GetCulturesTest(string cultureName, int lcid, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName)
{
_ = lcid;
_ = specificCultureName;
_ = threeLetterISOLanguageName;
_ = threeLetterWindowsLanguageName;
_ = consoleUICultureName;
bool found = false;
Assert.All(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
c => Assert.True( (c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.NeutralCultures) != 0)) || c.Equals(CultureInfo.InvariantCulture)));
found = CultureInfo.GetCultures(CultureTypes.NeutralCultures).Any(c => c.Name.Equals(cultureName, StringComparison.OrdinalIgnoreCase) ||
c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase));
Assert.All(CultureInfo.GetCultures(CultureTypes.SpecificCultures), c => Assert.True(!c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.SpecificCultures) != 0)));
if (!found)
{
found = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Any(c => c.Name.Equals(cultureName, StringComparison.OrdinalIgnoreCase) ||
c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase));
}
Assert.True(found, $"Expected to find the culture {cultureName} in the enumerated list");
}
[Fact]
public void ClearCachedDataTest()
{
CultureInfo ci = CultureInfo.GetCultureInfo("ja-JP");
Assert.True((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "Expected getting same object reference");
ci.ClearCachedData();
Assert.False((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "expected to get a new object reference");
}
[Fact]
public void CultureNotFoundExceptionTest()
{
AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("!@#$%^&*()"));
AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture"));
AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("longCulture" + new string('a', 100)));
AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000));
CultureNotFoundException e = AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture"));
Assert.Equal("This is invalid culture", e.InvalidCultureName);
e = AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000));
Assert.Equal(0x1000, e.InvalidCultureId);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class represents settings specified by de jure or
// de facto standards for a particular country/region. In
// contrast to CultureInfo, the RegionInfo does not represent
// preferences of the user and does not depend on the user's
// language or culture.
//
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class RegionInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
//
// Name of this region (ie: es-US): serialized, the field used for deserialization
//
internal String m_name;
//
// The CultureData instance that we are going to read data from.
//
internal CultureData m_cultureData;
//
// The RegionInfo for our current region
//
internal static volatile RegionInfo s_currentRegionInfo;
////////////////////////////////////////////////////////////////////////
//
// RegionInfo Constructors
//
// Note: We prefer that a region be created with a full culture name (ie: en-US)
// because otherwise the native strings won't be right.
//
// In Silverlight we enforce that RegionInfos must be created with a full culture name
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
public RegionInfo(String name)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0) //The InvariantCulture has no matching region
{
throw new ArgumentException(SR.Argument_NoRegionInvariantCulture);
}
Contract.EndContractBlock();
//
// For CoreCLR we only want the region names that are full culture names
//
this.m_cultureData = CultureData.GetCultureDataForRegion(name, true);
if (this.m_cultureData == null)
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.Argument_InvalidCultureName, name), "name");
// Not supposed to be neutral
if (this.m_cultureData.IsNeutralCulture)
throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), "name");
SetName(name);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal RegionInfo(CultureData cultureData)
{
this.m_cultureData = cultureData;
this.m_name = this.m_cultureData.SREGIONNAME;
}
[System.Security.SecurityCritical] // auto-generated
private void SetName(string name)
{
// when creating region by culture name, we keep the region name as the culture name so regions
// created by custom culture names can be differentiated from built in regions.
this.m_name = name.Equals(this.m_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ?
this.m_cultureData.SREGIONNAME :
this.m_cultureData.CultureName;
}
////////////////////////////////////////////////////////////////////////
//
// GetCurrentRegion
//
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
//
////////////////////////////////////////////////////////////////////////
public static RegionInfo CurrentRegion
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
RegionInfo temp = s_currentRegionInfo;
if (temp == null)
{
temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData);
// Need full name for custom cultures
temp.m_name = temp.m_cultureData.SREGIONNAME;
s_currentRegionInfo = temp;
}
return temp;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetName
//
// Returns the name of the region (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
return (m_name);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetEnglishName
//
// Returns the name of the region in English. (ie: United States)
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SENGCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetDisplayName
//
// Returns the display name (localized) of the region. (ie: United States
// if the current UI language is en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SLOCALIZEDCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetNativeName
//
// Returns the native name of the region. (ie: Deutschland)
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual String NativeName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SNATIVECOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// TwoLetterISORegionName
//
// Returns the two letter ISO region name (ie: US)
//
////////////////////////////////////////////////////////////////////////
public virtual String TwoLetterISORegionName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SISO3166CTRYNAME);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsMetric
//
// Returns true if this region uses the metric measurement system
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsMetric
{
get
{
int value = this.m_cultureData.IMEASURE;
return (value == 0);
}
}
////////////////////////////////////////////////////////////////////////
//
// CurrencySymbol
//
// Currency Symbol for this locale, ie: Fr. or $
//
////////////////////////////////////////////////////////////////////////
public virtual String CurrencySymbol
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SCURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
// ISOCurrencySymbol
//
// ISO Currency Symbol for this locale, ie: CHF
//
////////////////////////////////////////////////////////////////////////
public virtual String ISOCurrencySymbol
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SINTLSYMBOL);
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same RegionInfo as the current instance.
//
// RegionInfos are considered equal if and only if they have the same name
// (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
RegionInfo that = value as RegionInfo;
if (that != null)
{
return this.Name.Equals(that.Name);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for RegionInfo
// A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns the name of the Region, ie: es-US
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return (Name);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.HSSF.Model;
using System.Globalization;
/// <summary>
/// @author Glen Stampoultzis
/// </summary>
public class ColumnInfoRecordsAggregate : RecordAggregate
{
private class CIRComparator : IComparer
{
public static IComparer instance = new CIRComparator();
private CIRComparator()
{
// enforce singleton
}
public int Compare(Object a, Object b)
{
return CompareColInfos((ColumnInfoRecord)a, (ColumnInfoRecord)b);
}
public static int CompareColInfos(ColumnInfoRecord a, ColumnInfoRecord b)
{
return a.FirstColumn - b.FirstColumn;
}
}
// int size = 0;
ArrayList records = null;
/// <summary>
/// Initializes a new instance of the <see cref="ColumnInfoRecordsAggregate"/> class.
/// </summary>
public ColumnInfoRecordsAggregate()
{
records = new ArrayList();
}
/// <summary>
/// Initializes a new instance of the <see cref="ColumnInfoRecordsAggregate"/> class.
/// </summary>
/// <param name="rs">The rs.</param>
public ColumnInfoRecordsAggregate(RecordStream rs): this()
{
bool isInOrder = true;
ColumnInfoRecord cirPrev = null;
while (rs.PeekNextClass() == typeof(ColumnInfoRecord))
{
ColumnInfoRecord cir = (ColumnInfoRecord)rs.GetNext();
records.Add(cir);
if (cirPrev != null && CIRComparator.CompareColInfos(cirPrev, cir) > 0)
{
isInOrder = false;
}
cirPrev = cir;
}
if (records.Count < 1)
{
throw new InvalidOperationException("No column info records found");
}
if (!isInOrder)
{
records.Sort(CIRComparator.instance);
}
}
/** It's an aggregate... just made something up */
public override short Sid
{
get { return -1012; }
}
/// <summary>
/// Gets the num columns.
/// </summary>
/// <value>The num columns.</value>
public int NumColumns
{
get
{
return records.Count;
}
}
/// <summary>
/// Gets the size of the record.
/// </summary>
/// <value>The size of the record.</value>
public override int RecordSize
{
get
{
int size = 0;
for (IEnumerator iterator = records.GetEnumerator(); iterator.MoveNext(); )
size += ((ColumnInfoRecord)iterator.Current).RecordSize;
return size;
}
}
public IEnumerator GetEnumerator()
{
return records.GetEnumerator();
}
/**
* Performs a deep Clone of the record
*/
public Object Clone()
{
ColumnInfoRecordsAggregate rec = new ColumnInfoRecordsAggregate();
for (int k = 0; k < records.Count; k++)
{
ColumnInfoRecord ci = (ColumnInfoRecord)records[k];
ci = (ColumnInfoRecord)ci.Clone();
rec.records.Add(ci);
}
return rec;
}
/// <summary>
/// Inserts a column into the aggregate (at the end of the list).
/// </summary>
/// <param name="col">The column.</param>
public void InsertColumn(ColumnInfoRecord col)
{
records.Add(col);
records.Sort(CIRComparator.instance);
}
/// <summary>
/// Inserts a column into the aggregate (at the position specified
/// by index
/// </summary>
/// <param name="idx">The index.</param>
/// <param name="col">The columninfo.</param>
public void InsertColumn(int idx, ColumnInfoRecord col)
{
records.Insert(idx, col);
}
/// <summary>
/// called by the class that is responsible for writing this sucker.
/// Subclasses should implement this so that their data is passed back in a
/// byte array.
/// </summary>
/// <param name="offset">offset to begin writing at</param>
/// <param name="data">byte array containing instance data</param>
/// <returns>number of bytes written</returns>
public override int Serialize(int offset, byte[] data)
{
IEnumerator itr = records.GetEnumerator();
int pos = offset;
while (itr.MoveNext())
{
pos += ((Record)itr.Current).Serialize(pos, data);
}
return pos - offset;
}
/// <summary>
/// Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order
/// that they should be written to file. Implementors may or may not return the actual
/// Records being used to manage POI's internal implementation. Callers should not
/// assume either way, and therefore only attempt to modify those Records after cloning
/// </summary>
/// <param name="rv"></param>
public override void VisitContainedRecords(RecordVisitor rv)
{
int nItems = records.Count;
if (nItems < 1)
{
return;
}
ColumnInfoRecord cirPrev = null;
for (int i = 0; i < nItems; i++)
{
ColumnInfoRecord cir = (ColumnInfoRecord)records[i];
rv.VisitRecord(cir);
if (cirPrev != null && CIRComparator.CompareColInfos(cirPrev, cir) > 0)
{
// Excel probably wouldn't mind, but there is much logic in this class
// that assumes the column info records are kept in order
throw new InvalidOperationException("Column info records are out of order");
}
cirPrev = cir;
}
}
/// <summary>
/// Finds the start of column outline group.
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns></returns>
public int FindStartOfColumnOutlineGroup(int idx)
{
// Find the start of the Group.
ColumnInfoRecord columnInfo = (ColumnInfoRecord)records[idx];
int level = columnInfo.OutlineLevel;
while (idx != 0)
{
ColumnInfoRecord prevColumnInfo = (ColumnInfoRecord)records[idx - 1];
if (columnInfo.FirstColumn - 1 == prevColumnInfo.LastColumn)
{
if (prevColumnInfo.OutlineLevel < level)
{
break;
}
idx--;
columnInfo = prevColumnInfo;
}
else
{
break;
}
}
return idx;
}
/// <summary>
/// Finds the end of column outline group.
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns></returns>
public int FindEndOfColumnOutlineGroup(int idx)
{
// Find the end of the Group.
ColumnInfoRecord columnInfo = (ColumnInfoRecord)records[idx];
int level = columnInfo.OutlineLevel;
while (idx < records.Count - 1)
{
ColumnInfoRecord nextColumnInfo = (ColumnInfoRecord)records[idx + 1];
if (columnInfo.LastColumn + 1 == nextColumnInfo.FirstColumn)
{
if (nextColumnInfo.OutlineLevel < level)
{
break;
}
idx++;
columnInfo = nextColumnInfo;
}
else
{
break;
}
}
return idx;
}
/// <summary>
/// Gets the col info.
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns></returns>
public ColumnInfoRecord GetColInfo(int idx)
{
return (ColumnInfoRecord)records[idx];
}
/// <summary>
/// Determines whether [is column group collapsed] [the specified idx].
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns>
/// <c>true</c> if [is column group collapsed] [the specified idx]; otherwise, <c>false</c>.
/// </returns>
public bool IsColumnGroupCollapsed(int idx)
{
int endOfOutlineGroupIdx = FindEndOfColumnOutlineGroup(idx);
int nextColInfoIx = endOfOutlineGroupIdx + 1;
if (nextColInfoIx >= records.Count)
{
return false;
}
ColumnInfoRecord nextColInfo = GetColInfo(nextColInfoIx);
if (!GetColInfo(endOfOutlineGroupIdx).IsAdjacentBefore(nextColInfo))
{
return false;
}
return nextColInfo.IsCollapsed;
}
/// <summary>
/// Determines whether [is column group hidden by parent] [the specified idx].
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns>
/// <c>true</c> if [is column group hidden by parent] [the specified idx]; otherwise, <c>false</c>.
/// </returns>
public bool IsColumnGroupHiddenByParent(int idx)
{
// Look out outline details of end
int endLevel = 0;
bool endHidden = false;
int endOfOutlineGroupIdx = FindEndOfColumnOutlineGroup(idx);
if (endOfOutlineGroupIdx < records.Count)
{
ColumnInfoRecord nextInfo = GetColInfo(endOfOutlineGroupIdx + 1);
if (GetColInfo(endOfOutlineGroupIdx).IsAdjacentBefore(nextInfo))
{
endLevel = nextInfo.OutlineLevel;
endHidden = nextInfo.IsHidden;
}
}
// Look out outline details of start
int startLevel = 0;
bool startHidden = false;
int startOfOutlineGroupIdx = FindStartOfColumnOutlineGroup(idx);
if (startOfOutlineGroupIdx > 0)
{
ColumnInfoRecord prevInfo = GetColInfo(startOfOutlineGroupIdx - 1);
if (prevInfo.IsAdjacentBefore(GetColInfo(startOfOutlineGroupIdx)))
{
startLevel = prevInfo.OutlineLevel;
startHidden = prevInfo.IsHidden;
}
}
if (endLevel > startLevel)
{
return endHidden;
}
return startHidden;
}
/// <summary>
/// Collapses the column.
/// </summary>
/// <param name="columnNumber">The column number.</param>
public void CollapseColumn(int columnNumber)
{
int idx = FindColInfoIdx(columnNumber, 0);
if (idx == -1)
return;
// Find the start of the group.
int groupStartColInfoIx = FindStartOfColumnOutlineGroup(idx);
ColumnInfoRecord columnInfo = GetColInfo(groupStartColInfoIx);
// Hide all the columns until the end of the group
int lastColIx = SetGroupHidden(groupStartColInfoIx, columnInfo.OutlineLevel, true);
// Write collapse field
SetColumn(lastColIx + 1, null, null, null, null, true);
}
/// <summary>
/// Expands the column.
/// </summary>
/// <param name="columnNumber">The column number.</param>
public void ExpandColumn(int columnNumber)
{
int idx = FindColInfoIdx(columnNumber, 0);
if (idx == -1)
return;
// If it is already exapanded do nothing.
if (!IsColumnGroupCollapsed(idx))
return;
// Find the start of the Group.
int startIdx = FindStartOfColumnOutlineGroup(idx);
ColumnInfoRecord columnInfo = GetColInfo(startIdx);
// Find the end of the Group.
int endIdx = FindEndOfColumnOutlineGroup(idx);
ColumnInfoRecord endColumnInfo = GetColInfo(endIdx);
// expand:
// colapsed bit must be UnSet
// hidden bit Gets UnSet _if_ surrounding Groups are expanded you can determine
// this by looking at the hidden bit of the enclosing Group. You will have
// to look at the start and the end of the current Group to determine which
// is the enclosing Group
// hidden bit only is altered for this outline level. ie. don't Uncollapse contained Groups
if (!IsColumnGroupHiddenByParent(idx))
{
for (int i = startIdx; i <= endIdx; i++)
{
if (columnInfo.OutlineLevel == GetColInfo(i).OutlineLevel)
GetColInfo(i).IsHidden = false;
}
}
// Write collapse field
SetColumn(columnInfo.LastColumn + 1, null, null, null, null, false);
}
/**
* Sets all non null fields into the <c>ci</c> parameter.
*/
private static void SetColumnInfoFields(ColumnInfoRecord ci, short? xfStyle, int? width,
int? level, Boolean? hidden, Boolean? collapsed)
{
if (xfStyle != null)
{
ci.XFIndex = Convert.ToInt16(xfStyle, CultureInfo.InvariantCulture);
}
if (width != null)
{
ci.ColumnWidth = Convert.ToInt32(width, CultureInfo.InvariantCulture);
}
if (level != null)
{
ci.OutlineLevel = (short)level;
}
if (hidden != null)
{
ci.IsHidden = Convert.ToBoolean(hidden, CultureInfo.InvariantCulture);
}
if (collapsed != null)
{
ci.IsCollapsed = Convert.ToBoolean(collapsed, CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Attempts to merge the col info record at the specified index
/// with either or both of its neighbours
/// </summary>
/// <param name="colInfoIx">The col info ix.</param>
private void AttemptMergeColInfoRecords(int colInfoIx)
{
int nRecords = records.Count;
if (colInfoIx < 0 || colInfoIx >= nRecords)
{
throw new ArgumentException("colInfoIx " + colInfoIx
+ " is out of range (0.." + (nRecords - 1) + ")");
}
ColumnInfoRecord currentCol = GetColInfo(colInfoIx);
int nextIx = colInfoIx + 1;
if (nextIx < nRecords)
{
if (MergeColInfoRecords(currentCol, GetColInfo(nextIx)))
{
records.RemoveAt(nextIx);
}
}
if (colInfoIx > 0)
{
if (MergeColInfoRecords(GetColInfo(colInfoIx - 1), currentCol))
{
records.RemoveAt(colInfoIx);
}
}
}
/**
* merges two column info records (if they are adjacent and have the same formatting, etc)
* @return <c>false</c> if the two column records could not be merged
*/
private static bool MergeColInfoRecords(ColumnInfoRecord ciA, ColumnInfoRecord ciB)
{
if (ciA.IsAdjacentBefore(ciB) && ciA.FormatMatches(ciB))
{
ciA.LastColumn = ciB.LastColumn;
return true;
}
return false;
}
/// <summary>
/// Sets all adjacent columns of the same outline level to the specified hidden status.
/// </summary>
/// <param name="pIdx">the col info index of the start of the outline group.</param>
/// <param name="level">The level.</param>
/// <param name="hidden">The hidden.</param>
/// <returns>the column index of the last column in the outline group</returns>
private int SetGroupHidden(int pIdx, int level, bool hidden)
{
int idx = pIdx;
ColumnInfoRecord columnInfo = GetColInfo(idx);
while (idx < records.Count)
{
columnInfo.IsHidden = (hidden);
if (idx + 1 < records.Count)
{
ColumnInfoRecord nextColumnInfo = GetColInfo(idx + 1);
if (!columnInfo.IsAdjacentBefore(nextColumnInfo))
{
break;
}
if (nextColumnInfo.OutlineLevel < level)
{
break;
}
columnInfo = nextColumnInfo;
}
idx++;
}
return columnInfo.LastColumn;
}
/// <summary>
/// Sets the column.
/// </summary>
/// <param name="targetColumnIx">The target column ix.</param>
/// <param name="xfIndex">Index of the xf.</param>
/// <param name="width">The width.</param>
/// <param name="level">The level.</param>
/// <param name="hidden">The hidden.</param>
/// <param name="collapsed">The collapsed.</param>
public void SetColumn(int targetColumnIx, short? xfIndex, int? width, int? level, bool? hidden, bool? collapsed)
{
ColumnInfoRecord ci = null;
int k = 0;
for (k = 0; k < records.Count; k++)
{
ColumnInfoRecord tci = (ColumnInfoRecord)records[k];
if (tci.ContainsColumn(targetColumnIx))
{
ci = tci;
break;
}
if (tci.FirstColumn > targetColumnIx)
{
// call targetColumnIx infos after k are for later targetColumnIxs
break; // exit now so k will be the correct insert pos
}
}
if (ci == null)
{
// okay so there IsN'T a targetColumnIx info record that cover's this targetColumnIx so lets Create one!
ColumnInfoRecord nci = new ColumnInfoRecord();
nci.FirstColumn = targetColumnIx;
nci.LastColumn = targetColumnIx;
SetColumnInfoFields(nci, xfIndex, width, level, hidden, collapsed);
InsertColumn(k, nci);
AttemptMergeColInfoRecords(k);
return;
}
bool styleChanged = ci.XFIndex != xfIndex;
bool widthChanged = ci.ColumnWidth != width;
bool levelChanged = ci.OutlineLevel != level;
bool hiddenChanged = ci.IsHidden != hidden;
bool collapsedChanged = ci.IsCollapsed != collapsed;
bool targetColumnIxChanged = styleChanged || widthChanged || levelChanged || hiddenChanged || collapsedChanged;
if (!targetColumnIxChanged)
{
// do nothing...nothing Changed.
return;
}
if ((ci.FirstColumn == targetColumnIx)
&& (ci.LastColumn == targetColumnIx))
{ // if its only for this cell then
// ColumnInfo ci for a single column, the target column
SetColumnInfoFields(ci, xfIndex, width, level, hidden, collapsed);
AttemptMergeColInfoRecords(k);
return;
}
if ((ci.FirstColumn == targetColumnIx)
|| (ci.LastColumn == targetColumnIx))
{
// The target column is at either end of the multi-column ColumnInfo ci
// we'll just divide the info and create a new one
if (ci.FirstColumn == targetColumnIx)
{
ci.FirstColumn = targetColumnIx + 1;
}
else
{
ci.LastColumn = targetColumnIx - 1;
k++; // adjust insert pos to insert after
}
ColumnInfoRecord nci = CopyColInfo(ci);
nci.FirstColumn = targetColumnIx;
nci.LastColumn = targetColumnIx;
SetColumnInfoFields(nci, xfIndex, width, level, hidden, collapsed);
InsertColumn(k, nci);
AttemptMergeColInfoRecords(k);
}
else
{
//split to 3 records
ColumnInfoRecord ciStart = ci;
ColumnInfoRecord ciMid = CopyColInfo(ci);
ColumnInfoRecord ciEnd = CopyColInfo(ci);
int lastcolumn = ci.LastColumn;
ciStart.LastColumn = (targetColumnIx - 1);
ciMid.FirstColumn=(targetColumnIx);
ciMid.LastColumn=(targetColumnIx);
SetColumnInfoFields(ciMid, xfIndex, width, level, hidden, collapsed);
InsertColumn(++k, ciMid);
ciEnd.FirstColumn = (targetColumnIx + 1);
ciEnd.LastColumn = (lastcolumn);
InsertColumn(++k, ciEnd);
// no need to attemptMergeColInfoRecords because we
// know both on each side are different
}
}
private ColumnInfoRecord CopyColInfo(ColumnInfoRecord ci)
{
return (ColumnInfoRecord)ci.Clone();
}
/**
* Sets all non null fields into the <c>ci</c> parameter.
*/
private void SetColumnInfoFields(ColumnInfoRecord ci, short xfStyle, short width, int level, bool hidden, bool collapsed)
{
ci.XFIndex = (xfStyle);
ci.ColumnWidth = (width);
ci.OutlineLevel = (short)level;
ci.IsHidden = (hidden);
ci.IsCollapsed = (collapsed);
}
/// <summary>
/// Collapses the col info records.
/// </summary>
/// <param name="columnIdx">The column index.</param>
public void CollapseColInfoRecords(int columnIdx)
{
if (columnIdx == 0)
return;
ColumnInfoRecord previousCol = (ColumnInfoRecord)records[columnIdx - 1];
ColumnInfoRecord currentCol = (ColumnInfoRecord)records[columnIdx];
bool adjacentColumns = previousCol.LastColumn == currentCol.FirstColumn - 1;
if (!adjacentColumns)
return;
bool columnsMatch =
previousCol.XFIndex == currentCol.XFIndex &&
previousCol.Options == currentCol.Options &&
previousCol.ColumnWidth == currentCol.ColumnWidth;
if (columnsMatch)
{
previousCol.LastColumn = currentCol.LastColumn;
records.Remove(columnIdx);
}
}
/// <summary>
/// Creates an outline Group for the specified columns.
/// </summary>
/// <param name="fromColumnIx">Group from this column (inclusive)</param>
/// <param name="toColumnIx">Group to this column (inclusive)</param>
/// <param name="indent">if true the Group will be indented by one level;if false indenting will be Removed by one level.</param>
public void GroupColumnRange(int fromColumnIx, int toColumnIx, bool indent)
{
int colInfoSearchStartIdx = 0; // optimization to speed up the search for col infos
for (int i = fromColumnIx; i <= toColumnIx; i++)
{
int level = 1;
int colInfoIdx = FindColInfoIdx(i, colInfoSearchStartIdx);
if (colInfoIdx != -1)
{
level = GetColInfo(colInfoIdx).OutlineLevel;
if (indent)
{
level++;
}
else
{
level--;
}
level = Math.Max(0, level);
level = Math.Min(7, level);
colInfoSearchStartIdx = Math.Max(0, colInfoIdx - 1); // -1 just in case this column is collapsed later.
}
SetColumn(i, null, null, level, null, null);
}
}
/// <summary>
/// Finds the ColumnInfoRecord
/// which contains the specified columnIndex
/// </summary>
/// <param name="columnIndex">index of the column (not the index of the ColumnInfoRecord)</param>
/// <returns> /// <c>null</c>
/// if no column info found for the specified column
/// </returns>
public ColumnInfoRecord FindColumnInfo(int columnIndex)
{
int nInfos = records.Count;
for (int i = 0; i < nInfos; i++)
{
ColumnInfoRecord ci = GetColInfo(i);
if (ci.ContainsColumn(columnIndex))
{
return ci;
}
}
return null;
}
private int FindColInfoIdx(int columnIx, int fromColInfoIdx)
{
if (columnIx < 0)
{
throw new ArgumentException("column parameter out of range: " + columnIx);
}
if (fromColInfoIdx < 0)
{
throw new ArgumentException("fromIdx parameter out of range: " + fromColInfoIdx);
}
for (int k = fromColInfoIdx; k < records.Count; k++)
{
ColumnInfoRecord ci = GetColInfo(k);
if (ci.ContainsColumn(columnIx))
{
return k;
}
if (ci.FirstColumn > columnIx)
{
break;
}
}
return -1;
}
/// <summary>
/// Gets the max outline level.
/// </summary>
/// <value>The max outline level.</value>
public int MaxOutlineLevel
{
get
{
int result = 0;
int count = records.Count;
for (int i = 0; i < count; i++)
{
ColumnInfoRecord columnInfoRecord = GetColInfo(i);
result = Math.Max(columnInfoRecord.OutlineLevel, result);
}
return result;
}
}
public int GetOutlineLevel(int columnIndex)
{
ColumnInfoRecord ci = FindColumnInfo(columnIndex);
if (ci != null)
{
return ci.OutlineLevel;
}
else
{
return 0;
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.VFX;
using System.Linq;
using System.Reflection;
using Type = System.Type;
using Delegate = System.Delegate;
namespace UnityEditor.VFX.UI
{
public static class VFXGizmoUtility
{
static Dictionary<System.Type, GizmoContext> s_DrawFunctions;
internal class Property<T> : VFXGizmo.IProperty<T>
{
public Property(IPropertyRMProvider controller, bool editable)
{
m_Controller = controller;
m_Editable = editable;
}
IPropertyRMProvider m_Controller;
bool m_Editable;
public bool isEditable
{
get { return m_Editable; }
}
public void SetValue(T value)
{
if (m_Editable)
m_Controller.value = value;
}
}
internal class NullProperty<T> : VFXGizmo.IProperty<T>
{
public bool isEditable
{
get { return false; }
}
public void SetValue(T value)
{
}
public static NullProperty<T> defaultProperty = new NullProperty<T>();
}
public abstract class Context : VFXGizmo.IContext
{
public abstract Type portType
{
get;
}
bool m_Prepared;
public void Unprepare()
{
m_Prepared = false;
}
public bool Prepare()
{
if (m_Prepared)
return false;
m_Prepared = true;
m_Indeterminate = false;
m_PropertyCache.Clear();
InternalPrepare();
return true;
}
protected abstract void InternalPrepare();
public const string separator = ".";
public abstract object value
{
get;
}
public abstract VFXCoordinateSpace space
{
get;
}
public virtual bool spaceLocalByDefault
{
get { return false; }
}
protected Dictionary<string, object> m_PropertyCache = new Dictionary<string, object>();
public abstract VFXGizmo.IProperty<T> RegisterProperty<T>(string member);
protected bool m_Indeterminate;
public bool IsIndeterminate()
{
return m_Indeterminate;
}
}
static VFXGizmoUtility()
{
s_DrawFunctions = new Dictionary<System.Type, GizmoContext>();
foreach (Type type in typeof(VFXGizmoUtility).Assembly.GetTypes()) // TODO put all user assemblies instead
{
var attributes = type.GetCustomAttributes(false);
if (attributes != null)
{
var gizmoAttribute = attributes.OfType<VFXGizmoAttribute>().FirstOrDefault();
if (gizmoAttribute != null)
{
s_DrawFunctions[gizmoAttribute.type] = new GizmoContext() { gizmo = (VFXGizmo)System.Activator.CreateInstance(type) };
}
}
}
}
public static bool HasGizmo(Type type)
{
return s_DrawFunctions.ContainsKey(type);
}
static Type GetGizmoType(Type type)
{
if (type.IsAbstract)
return null;
Type baseType = type.BaseType;
while (baseType != null)
{
if (baseType.IsGenericType && !baseType.IsGenericTypeDefinition && baseType.GetGenericTypeDefinition() == typeof(VFXGizmo<>))
{
return baseType.GetGenericArguments()[0];
}
baseType = baseType.BaseType;
}
return null;
}
public static VFXGizmo CreateGizmoInstance(Context context)
{
GizmoContext gizmo;
if (s_DrawFunctions.TryGetValue(context.portType, out gizmo))
{
return (VFXGizmo)System.Activator.CreateInstance(gizmo.gizmo.GetType());
}
return null;
}
struct GizmoContext
{
public Context lastContext;
public VFXGizmo gizmo;
}
static internal void Draw(Context context, VisualEffect component)
{
GizmoContext gizmo;
if (s_DrawFunctions.TryGetValue(context.portType, out gizmo))
{
bool forceRegister = false;
if (gizmo.lastContext != context)
{
forceRegister = true;
s_DrawFunctions[context.portType] = new GizmoContext() { gizmo = gizmo.gizmo, lastContext = context };
}
Draw(context, component, gizmo.gizmo, forceRegister);
}
}
static internal bool NeedsComponent(Context context)
{
GizmoContext gizmo;
if (s_DrawFunctions.TryGetValue(context.portType, out gizmo))
{
gizmo.gizmo.currentSpace = context.space;
gizmo.gizmo.spaceLocalByDefault = context.spaceLocalByDefault;
return gizmo.gizmo.needsComponent;
}
return false;
}
static internal Bounds GetGizmoBounds(Context context, VisualEffect component)
{
GizmoContext gizmo;
if (s_DrawFunctions.TryGetValue(context.portType, out gizmo))
{
bool forceRegister = false;
if (gizmo.lastContext != context)
{
forceRegister = true;
s_DrawFunctions[context.portType] = new GizmoContext() { gizmo = gizmo.gizmo, lastContext = context };
}
return GetGizmoBounds(context, component, gizmo.gizmo, forceRegister);
}
return new Bounds();
}
static internal Bounds GetGizmoBounds(Context context, VisualEffect component, VFXGizmo gizmo, bool forceRegister = false)
{
if (context.Prepare() || forceRegister)
{
gizmo.RegisterEditableMembers(context);
}
if (!context.IsIndeterminate())
{
gizmo.component = component;
gizmo.currentSpace = context.space;
gizmo.spaceLocalByDefault = context.spaceLocalByDefault;
Bounds bounds = gizmo.CallGetGizmoBounds(context.value);
gizmo.component = null;
return bounds;
}
return new Bounds();
}
static internal void Draw(Context context, VisualEffect component, VFXGizmo gizmo, bool forceRegister = false)
{
if (context.Prepare() || forceRegister)
{
gizmo.RegisterEditableMembers(context);
}
if (!context.IsIndeterminate())
{
gizmo.component = component;
gizmo.currentSpace = context.space;
gizmo.spaceLocalByDefault = context.spaceLocalByDefault;
gizmo.CallDrawGizmo(context.value);
gizmo.component = null;
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace System.Diagnostics
{
using System;
using System.Runtime.InteropServices;
[Serializable, AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute() { }
}
[Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepperBoundaryAttribute : Attribute
{
public DebuggerStepperBoundaryAttribute() { }
}
[Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute() { }
}
[Serializable, AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
public DebuggerNonUserCodeAttribute() { }
}
// Attribute class used by the compiler to mark modules.
// If present, then debugging information for everything in the
// assembly was generated by the compiler, and will be preserved
// by the Runtime so that the debugger can provide full functionality
// in the case of JIT attach. If not present, then the compiler may
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module, AllowMultiple = false)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
public enum DebuggingModes
{
None = 0x0,
Default = 0x1,
DisableOptimizations = 0x100,
IgnoreSymbolStoreSequencePoints = 0x2,
EnableEditAndContinue = 0x4
}
private DebuggingModes m_debuggingModes;
public DebuggableAttribute(bool isJITTrackingEnabled,
bool isJITOptimizerDisabled)
{
m_debuggingModes = 0;
if (isJITTrackingEnabled)
{
m_debuggingModes |= DebuggingModes.Default;
}
if (isJITOptimizerDisabled)
{
m_debuggingModes |= DebuggingModes.DisableOptimizations;
}
}
public DebuggableAttribute(DebuggingModes modes)
{
m_debuggingModes = modes;
}
public bool IsJITTrackingEnabled
{
get { return ((m_debuggingModes & DebuggingModes.Default) != 0); }
}
public bool IsJITOptimizerDisabled
{
get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); }
}
public DebuggingModes DebuggingFlags
{
get { return m_debuggingModes; }
}
}
// DebuggerBrowsableState states are defined as follows:
// Never never show this element
// Expanded expansion of the class is done, so that all visible internal members are shown
// Collapsed expansion of the class is not performed. Internal visible members are hidden
// RootHidden The target element itself should not be shown, but should instead be
// automatically expanded to have its members displayed.
// Default value is collapsed
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
public enum DebuggerBrowsableState
{
Never = 0,
Collapsed = 2,
RootHidden = 3
}
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class DebuggerBrowsableAttribute : Attribute
{
private DebuggerBrowsableState state;
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException("state");
this.state = state;
}
public DebuggerBrowsableState State
{
get { return state; }
}
}
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DebuggerTypeProxyAttribute : Attribute
{
private string typeName;
private string targetName;
private Type target;
public DebuggerTypeProxyAttribute(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
this.typeName = type.FullName + "," + type.Assembly.FullName;
}
public DebuggerTypeProxyAttribute(string typeName)
{
this.typeName = typeName;
}
public string ProxyTypeName
{
get { return typeName; }
}
public Type Target
{
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
targetName = value.FullName + "," + value.Assembly.FullName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
// This attribute is used to control what is displayed for the given class or field
// in the data windows in the debugger. The single argument to this attribute is
// the string that will be displayed in the value column for instances of the type.
// This string can include text between { and } which can be either a field,
// property or method (as will be documented in mscorlib). In the C# case,
// a general expression will be allowed which only has implicit access to the this pointer
// for the current instance of the target type. The expression will be limited,
// however: there is no access to aliases, locals, or pointers.
// In addition, attributes on properties referenced in the expression are not processed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DebuggerDisplayAttribute : Attribute
{
private string name;
private string value;
private string type;
private string targetName;
private Type target;
public DebuggerDisplayAttribute(string value)
{
if (value == null)
{
this.value = "";
}
else
{
this.value = value;
}
name = "";
type = "";
}
public string Value
{
get { return this.value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public Type Target
{
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
targetName = value.FullName + "," + value.Assembly.FullName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.Platforms.Features.WamBroker;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using Windows.Security.Authentication.Web.Core;
using Windows.Security.Credentials;
namespace Microsoft.Identity.Test.Unit.BrokerTests
{
[TestClass]
public class WamMsaPassthroughTests : TestBase
{
private MsaPassthroughHandler _msaPassthroughHandler;
private ICoreLogger _logger;
private IWamPlugin _msaPlugin;
private IWamProxy _wamProxy;
[TestInitialize]
public void Init()
{
_logger = Substitute.For<ICoreLogger>();
_msaPlugin = Substitute.For<IWamPlugin>();
_wamProxy = Substitute.For<IWamProxy>();
_msaPassthroughHandler = new MsaPassthroughHandler(
_logger,
_msaPlugin,
_wamProxy,
IntPtr.Zero);
}
[TestMethod]
public void AddTransferTokenToRequest()
{
// Arrange
const string TransferToken = "transfer_token";
var provider = new WebAccountProvider("id", "user@contoso.com", null);
WebTokenRequest request = new WebTokenRequest(provider, "scope", "client_id");
// Act
_msaPassthroughHandler.AddTransferTokenToRequest(request, TransferToken);
// Assert
Assert.AreEqual(TransferToken, request.Properties["SamlAssertion"]);
Assert.AreEqual("SAMLV1", request.Properties["SamlAssertionType"]);
}
[TestMethod]
public async Task FetchTransferToken_Silent_Async()
{
// Arrange
using (MockHttpAndServiceBundle harness = CreateTestHarness())
{
var msaProvider = new WebAccountProvider("id", "user@contoso.com", null);
Client.Internal.Requests.AuthenticationRequestParameters requestParams =
harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityHomeTenant,
validateAuthority: true);
requestParams.AppConfig.WindowsBrokerOptions = new WindowsBrokerOptions() { MsaPassthrough = true };
var msaRequest = new WebTokenRequest(msaProvider);
_msaPlugin.CreateWebTokenRequestAsync(msaProvider, requestParams, false, false, true, MsaPassthroughHandler.TransferTokenScopes)
.Returns(Task.FromResult(msaRequest));
var webTokenResponseWrapper = Substitute.For<IWebTokenRequestResultWrapper>();
webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "user@outlook.com", WebAccountState.Connected);
var webTokenResponse = new WebTokenResponse("transfer_token", accountFromMsaProvider);
webTokenResponseWrapper.ResponseData.Returns(new List<WebTokenResponse>() { webTokenResponse });
_wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, msaRequest, accountFromMsaProvider).Returns(webTokenResponseWrapper);
_msaPlugin.ParseSuccessfullWamResponse(Arg.Any<WebTokenResponse>(), out Arg.Any<Dictionary<string, string>>())
.Returns(x =>
{
x[1] = new Dictionary<string, string>();
(x[1] as Dictionary<string, string>).Add("code", "actual_transfer_token");
return new MsalTokenResponse();
});
// Act
var transferToken = await _msaPassthroughHandler.TryFetchTransferTokenSilentAsync(
requestParams,
accountFromMsaProvider)
.ConfigureAwait(false);
// Assert
Assert.AreEqual("actual_transfer_token", transferToken);
}
}
[TestMethod]
public async Task FetchTransferToken_DefaultAccount_Silent_Async()
{
// Arrange
using (MockHttpAndServiceBundle harness = CreateTestHarness())
{
var msaProvider = new WebAccountProvider("id", "user@contoso.com", null);
Client.Internal.Requests.AuthenticationRequestParameters requestParams =
harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityHomeTenant,
validateAuthority: true);
requestParams.AppConfig.WindowsBrokerOptions = new WindowsBrokerOptions() { MsaPassthrough = true };
var msaRequest = new WebTokenRequest(msaProvider);
_msaPlugin.CreateWebTokenRequestAsync(msaProvider, requestParams, false, false, true, MsaPassthroughHandler.TransferTokenScopes)
.Returns(Task.FromResult(msaRequest));
var webTokenResponseWrapper = Substitute.For<IWebTokenRequestResultWrapper>();
webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "user@outlook.com", WebAccountState.Connected);
var webTokenResponse = new WebTokenResponse("transfer_token", accountFromMsaProvider);
webTokenResponseWrapper.ResponseData.Returns(new List<WebTokenResponse>() { webTokenResponse });
_wamProxy.GetTokenSilentlyForDefaultAccountAsync(msaRequest).Returns(webTokenResponseWrapper);
_msaPlugin.ParseSuccessfullWamResponse(Arg.Any<WebTokenResponse>(), out Arg.Any<Dictionary<string, string>>())
.Returns(x =>
{
x[1] = new Dictionary<string, string>();
(x[1] as Dictionary<string, string>).Add("code", "actual_transfer_token");
return new MsalTokenResponse();
});
// Act
var transferToken = await _msaPassthroughHandler.TryFetchTransferTokenSilentDefaultAccountAsync(
requestParams,
msaProvider)
.ConfigureAwait(false);
// Assert
Assert.AreEqual("actual_transfer_token", transferToken);
}
}
[TestMethod]
public async Task FetchTransferToken_Interactive_Async()
{
// Arrange
using (MockHttpAndServiceBundle harness = CreateTestHarness())
{
var msaProvider = new WebAccountProvider("id", "user@contoso.com", null);
Client.Internal.Requests.AuthenticationRequestParameters requestParams =
harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityHomeTenant,
validateAuthority: true);
requestParams.AppConfig.WindowsBrokerOptions = new WindowsBrokerOptions() { MsaPassthrough = true };
var msaRequest = new WebTokenRequest(msaProvider);
_msaPlugin.CreateWebTokenRequestAsync(msaProvider, requestParams, false, true, false, MsaPassthroughHandler.TransferTokenScopes)
.Returns(Task.FromResult(msaRequest));
var webTokenResponseWrapper = Substitute.For<IWebTokenRequestResultWrapper>();
webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "user@outlook.com", WebAccountState.Connected);
var webTokenResponse = new WebTokenResponse("transfer_token", accountFromMsaProvider);
webTokenResponseWrapper.ResponseData.Returns(new List<WebTokenResponse>() { webTokenResponse });
_wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, msaRequest).Returns(webTokenResponseWrapper);
_msaPlugin.ParseSuccessfullWamResponse(Arg.Any<WebTokenResponse>(), out Arg.Any<Dictionary<string, string>>())
.Returns(x =>
{
x[1] = new Dictionary<string, string>();
(x[1] as Dictionary<string, string>).Add("code", "actual_transfer_token");
return new MsalTokenResponse();
});
// Act
var transferToken = await _msaPassthroughHandler.TryFetchTransferTokenInteractiveAsync(requestParams, msaProvider)
.ConfigureAwait(false);
// Assert
Assert.AreEqual("actual_transfer_token", transferToken);
}
}
[TestMethod]
public async Task FetchTransferToken_FailSilently_Async()
{
// Arrange
using (MockHttpAndServiceBundle harness = CreateTestHarness())
{
var msaProvider = new WebAccountProvider("id", "user@contoso.com", null);
Client.Internal.Requests.AuthenticationRequestParameters requestParams =
harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityHomeTenant,
validateAuthority: true);
requestParams.AppConfig.WindowsBrokerOptions = new WindowsBrokerOptions() { MsaPassthrough = true };
var msaRequest = new WebTokenRequest(msaProvider);
_msaPlugin.CreateWebTokenRequestAsync(msaProvider, requestParams, false, true, false, MsaPassthroughHandler.TransferTokenScopes)
.Returns(Task.FromResult(msaRequest));
_msaPlugin.MapTokenRequestError(WebTokenRequestStatus.ProviderError, 0, true)
.Returns(Tuple.Create("some_provider_error", "", false));
var webTokenResponseWrapper = Substitute.For<IWebTokenRequestResultWrapper>();
webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.ProviderError);
_wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, msaRequest).Returns(webTokenResponseWrapper);
// Act
var transferToken = await _msaPassthroughHandler.TryFetchTransferTokenInteractiveAsync(requestParams, msaProvider)
.ConfigureAwait(false);
// Assert
Assert.IsNull(transferToken);
}
}
}
}
| |
// 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 OrInt64()
{
var test = new SimpleBinaryOpTest__OrInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// 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();
// 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 SimpleBinaryOpTest__OrInt64
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data1 = new Int64[ElementCount];
private static Int64[] _data2 = new Int64[ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector128<Int64> _fld1;
private Vector128<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64> _dataTable;
static SimpleBinaryOpTest__OrInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__OrInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Or(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Or(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrInt64();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
if ((long)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((long)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<Int64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace OrthogonalComponentHsm
{
/// <summary>
/// AlarmClock example main form. Please overlook the poor GUI used for this example.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBoxAlarm;
private System.Windows.Forms.GroupBox groupBoxTime;
private System.Windows.Forms.TextBox textBoxTime;
private System.Windows.Forms.Label labelTime;
private System.Windows.Forms.TextBox textBoxAlarm;
private System.Windows.Forms.Label labelAlarm;
private System.Windows.Forms.RadioButton radioButtonAlarmOn;
private System.Windows.Forms.RadioButton radioButtonAlarmOff;
private System.Windows.Forms.RadioButton radioButton12HourTime;
private System.Windows.Forms.RadioButton radioButton24HourTime;
private System.Windows.Forms.Button buttonStop;//exit button
private System.Windows.Forms.PictureBox pictureBoxAlarm;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Label label1;//only used for timing how long picture is shown
private System.ComponentModel.IContainer components = null;
//in this example, nothing works until after the start button is clicked once
private void buttonStart_Click(object sender, System.EventArgs e)
{
this.buttonStart.Visible = false; //start button is used only once in place of the init signal
this.textBoxAlarm.Enabled = true;
this.radioButtonAlarmOn.Enabled = true;
this.radioButtonAlarmOff.Enabled = true;
this.radioButton12HourTime.Enabled = true;
this.radioButton24HourTime.Enabled = true;
//now listen to events from Alarm Clock
AlarmClock.Instance.DisplayAlarmTime += new AlarmClock.AlarmDisplayHandler(UpdateAlarmTime);
AlarmClock.Instance.DisplayTimeOfDay += new AlarmClock.AlarmDisplayHandler(UpdateTimeOfDay);
AlarmClock.Instance.DisplayAlarmAlert += new AlarmClock.AlarmDisplayHandler(ShowAlarmPicture);
DispatchMessage(AlarmClockSignals.Start);
this.radioButtonAlarmOn.Checked = true;//an optional convenience
}
/// <summary>
/// Exits Application
/// </summary>
private void buttonStop_Click(object sender, System.EventArgs e)
{
DispatchMessage(AlarmClockSignals.Terminate);
}
private void DispatchMessage(AlarmClockSignals signal)
{
AlarmInitEvent e = new AlarmInitEvent(signal);
AlarmClock.Instance.DispatchQ(e);
}
private void radioButtonAlarm_CheckedChanged(object sender, System.EventArgs e)
{
this.HideAlarmPicture();
//The ideal alarm time text input validator would be another
//state machine. However, that would complicate this example.
//Therefore, we take a shortcut and don't fully validate input.
if (this.radioButtonAlarmOn.Checked == true)
{
try
{
AlarmClock.Instance.AlarmTime = DateTime.Parse(this.textBoxAlarm.Text);
DispatchMessage(AlarmClockSignals.AlarmOn);
}
catch (System.FormatException exception)
{
radioButtonAlarmOn.Checked = false;
MessageBox.Show(exception.Message, "Invalid Alarm Time");
}
}
else
{
DispatchMessage(AlarmClockSignals.AlarmOff);
}
}
private void radioButton12or24HourTime_CheckedChanged(object sender, System.EventArgs e)
{
if (this.radioButton12HourTime.Checked == true)
{
DispatchMessage(AlarmClockSignals.Mode12Hour);
}
else
{
DispatchMessage(AlarmClockSignals.Mode24Hour);
}
}
private void UpdateTimeOfDay(object sender, AlarmClockEventArgs e)
{
// Is this method on the UI thread? If not then we need to marshal it to the UI thread.
if (this.InvokeRequired)
{
AlarmClock.AlarmDisplayHandler alarmDisplayHandler = new AlarmClock.AlarmDisplayHandler(UpdateTimeOfDay);
Invoke(alarmDisplayHandler, new object[] {sender, e});
}
else
{
this.textBoxTime.Text = e.Message;
}
}
private void UpdateAlarmTime(object sender, AlarmClockEventArgs e)
{
// Is this method on the UI thread? If not then we need to marshal it to the UI thread.
if (this.InvokeRequired)
{
AlarmClock.AlarmDisplayHandler alarmDisplayHandler = new AlarmClock.AlarmDisplayHandler(UpdateAlarmTime);
Invoke(alarmDisplayHandler, new object[] {sender, e});
}
else
{
this.textBoxAlarm.Text = e.Message;
}
}
private void ShowAlarmPicture(object sender, AlarmClockEventArgs e)
{
// Is this method on the UI thread? If not then we need to marshal it to the UI thread.
if (this.InvokeRequired)
{
AlarmClock.AlarmDisplayHandler alarmDisplayHandler = new AlarmClock.AlarmDisplayHandler(ShowAlarmPicture);
Invoke(alarmDisplayHandler, new object[] {sender, e});
}
else
{
this.pictureBoxAlarm.Show();
//this.Refresh();
}
}
private void HideAlarmPicture()
{
this.pictureBoxAlarm.Hide();
//this.Refresh();
}
private void MainForm_Load(object sender, System.EventArgs e)
{
//show this only after the alarm activates
this.pictureBoxAlarm.Hide();
//disable these until after Start is clicked
this.textBoxAlarm.Enabled = false;
this.radioButtonAlarmOn.Enabled = false;
this.radioButtonAlarmOff.Enabled = false;
this.radioButton12HourTime.Enabled = false;
this.radioButton24HourTime.Enabled = false;
}
private MainForm()
{
InitializeComponent();
}//ctor
//
//Thread-safe implementation of singleton -- not strictly necessary for this
//example project
//
private static volatile MainForm singleton = null;
private static object sync = new object();//for static lock
public static MainForm Instance
{
[System.Diagnostics.DebuggerStepThrough()]
get
{
if (singleton == null)
{
lock (sync)
{
if (singleton == null)
{
singleton = new MainForm();
}
}
}
return singleton;
}
}//Instance
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
this.pictureBoxAlarm.Dispose();
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.groupBoxAlarm = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.radioButtonAlarmOff = new System.Windows.Forms.RadioButton();
this.radioButtonAlarmOn = new System.Windows.Forms.RadioButton();
this.textBoxAlarm = new System.Windows.Forms.TextBox();
this.labelAlarm = new System.Windows.Forms.Label();
this.groupBoxTime = new System.Windows.Forms.GroupBox();
this.radioButton24HourTime = new System.Windows.Forms.RadioButton();
this.radioButton12HourTime = new System.Windows.Forms.RadioButton();
this.textBoxTime = new System.Windows.Forms.TextBox();
this.labelTime = new System.Windows.Forms.Label();
this.pictureBoxAlarm = new System.Windows.Forms.PictureBox();
this.buttonStop = new System.Windows.Forms.Button();
this.buttonStart = new System.Windows.Forms.Button();
this.groupBoxAlarm.SuspendLayout();
this.groupBoxTime.SuspendLayout();
this.SuspendLayout();
//
// groupBoxAlarm
//
this.groupBoxAlarm.Controls.Add(this.label1);
this.groupBoxAlarm.Controls.Add(this.radioButtonAlarmOff);
this.groupBoxAlarm.Controls.Add(this.radioButtonAlarmOn);
this.groupBoxAlarm.Controls.Add(this.textBoxAlarm);
this.groupBoxAlarm.Controls.Add(this.labelAlarm);
this.groupBoxAlarm.Location = new System.Drawing.Point(10, 18);
this.groupBoxAlarm.Name = "groupBoxAlarm";
this.groupBoxAlarm.Size = new System.Drawing.Size(240, 130);
this.groupBoxAlarm.TabIndex = 0;
this.groupBoxAlarm.TabStop = false;
this.groupBoxAlarm.Text = "Alarm";
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(106, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(110, 19);
this.label1.TabIndex = 4;
this.label1.Text = "(input not validated)";
this.label1.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
//
// radioButtonAlarmOff
//
this.radioButtonAlarmOff.Checked = true;
this.radioButtonAlarmOff.Location = new System.Drawing.Point(134, 83);
this.radioButtonAlarmOff.Name = "radioButtonAlarmOff";
this.radioButtonAlarmOff.Size = new System.Drawing.Size(58, 28);
this.radioButtonAlarmOff.TabIndex = 3;
this.radioButtonAlarmOff.TabStop = true;
this.radioButtonAlarmOff.Text = "Off";
this.radioButtonAlarmOff.CheckedChanged += new System.EventHandler(this.radioButtonAlarm_CheckedChanged);
//
// radioButtonAlarmOn
//
this.radioButtonAlarmOn.Location = new System.Drawing.Point(29, 83);
this.radioButtonAlarmOn.Name = "radioButtonAlarmOn";
this.radioButtonAlarmOn.Size = new System.Drawing.Size(57, 28);
this.radioButtonAlarmOn.TabIndex = 2;
this.radioButtonAlarmOn.Text = "On";
this.radioButtonAlarmOn.CheckedChanged += new System.EventHandler(this.radioButtonAlarm_CheckedChanged);
//
// textBoxAlarm
//
this.textBoxAlarm.Location = new System.Drawing.Point(96, 46);
this.textBoxAlarm.Name = "textBoxAlarm";
this.textBoxAlarm.Size = new System.Drawing.Size(125, 22);
this.textBoxAlarm.TabIndex = 1;
this.textBoxAlarm.TabStop = false;
this.textBoxAlarm.Text = "12:01:01";
this.textBoxAlarm.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// labelAlarm
//
this.labelAlarm.Location = new System.Drawing.Point(14, 46);
this.labelAlarm.Name = "labelAlarm";
this.labelAlarm.Size = new System.Drawing.Size(82, 19);
this.labelAlarm.TabIndex = 0;
this.labelAlarm.Text = "Alarm Time:";
this.labelAlarm.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// groupBoxTime
//
this.groupBoxTime.Controls.Add(this.radioButton24HourTime);
this.groupBoxTime.Controls.Add(this.radioButton12HourTime);
this.groupBoxTime.Controls.Add(this.textBoxTime);
this.groupBoxTime.Controls.Add(this.labelTime);
this.groupBoxTime.Location = new System.Drawing.Point(10, 175);
this.groupBoxTime.Name = "groupBoxTime";
this.groupBoxTime.Size = new System.Drawing.Size(336, 116);
this.groupBoxTime.TabIndex = 1;
this.groupBoxTime.TabStop = false;
this.groupBoxTime.Text = "TimeKeeping";
//
// radioButton24HourTime
//
this.radioButton24HourTime.Checked = true;
this.radioButton24HourTime.Location = new System.Drawing.Point(202, 74);
this.radioButton24HourTime.Name = "radioButton24HourTime";
this.radioButton24HourTime.Size = new System.Drawing.Size(124, 28);
this.radioButton24HourTime.TabIndex = 3;
this.radioButton24HourTime.TabStop = true;
this.radioButton24HourTime.Text = "24 Hour Mode";
this.radioButton24HourTime.CheckedChanged += new System.EventHandler(this.radioButton12or24HourTime_CheckedChanged);
//
// radioButton12HourTime
//
this.radioButton12HourTime.Location = new System.Drawing.Point(29, 74);
this.radioButton12HourTime.Name = "radioButton12HourTime";
this.radioButton12HourTime.Size = new System.Drawing.Size(125, 28);
this.radioButton12HourTime.TabIndex = 2;
this.radioButton12HourTime.Text = "12 Hour Mode";
this.radioButton12HourTime.CheckedChanged += new System.EventHandler(this.radioButton12or24HourTime_CheckedChanged);
//
// textBoxTime
//
this.textBoxTime.Location = new System.Drawing.Point(130, 28);
this.textBoxTime.Name = "textBoxTime";
this.textBoxTime.ReadOnly = true;
this.textBoxTime.Size = new System.Drawing.Size(192, 22);
this.textBoxTime.TabIndex = 1;
this.textBoxTime.TabStop = false;
this.textBoxTime.Text = "12:00:00";
this.textBoxTime.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// labelTime
//
this.labelTime.Location = new System.Drawing.Point(14, 28);
this.labelTime.Name = "labelTime";
this.labelTime.Size = new System.Drawing.Size(106, 18);
this.labelTime.TabIndex = 0;
this.labelTime.Text = "Time Of Day:";
this.labelTime.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// pictureBoxAlarm
//
this.pictureBoxAlarm.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxAlarm.Image")));
this.pictureBoxAlarm.Location = new System.Drawing.Point(269, 18);
this.pictureBoxAlarm.Name = "pictureBoxAlarm";
this.pictureBoxAlarm.Size = new System.Drawing.Size(100, 115);
this.pictureBoxAlarm.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxAlarm.TabIndex = 25;
this.pictureBoxAlarm.TabStop = false;
//
// buttonStop
//
this.buttonStop.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.buttonStop.Location = new System.Drawing.Point(365, 185);
this.buttonStop.Name = "buttonStop";
this.buttonStop.Size = new System.Drawing.Size(29, 101);
this.buttonStop.TabIndex = 2;
this.buttonStop.Text = "E X I T";
this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
//
// buttonStart
//
this.buttonStart.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.buttonStart.Location = new System.Drawing.Point(269, 18);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(120, 133);
this.buttonStart.TabIndex = 26;
this.buttonStart.Text = "Start";
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(400, 310);
this.Controls.Add(this.buttonStart);
this.Controls.Add(this.buttonStop);
this.Controls.Add(this.groupBoxAlarm);
this.Controls.Add(this.groupBoxTime);
this.Controls.Add(this.pictureBoxAlarm);
this.MaximizeBox = false;
this.Name = "MainForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Orthogonal Component Pattern";
this.Load += new System.EventHandler(this.MainForm_Load);
this.groupBoxAlarm.ResumeLayout(false);
this.groupBoxTime.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
}//class MainForm
}//namespace OrthogonalComponentHsm
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.CookiePolicy.Test
{
public class CookiePolicyTests
{
private readonly RequestDelegate SecureCookieAppends = context =>
{
context.Response.Cookies.Append("A", "A");
context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false });
context.Response.Cookies.Append("C", "C", new CookieOptions());
context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true });
return Task.FromResult(0);
};
private readonly RequestDelegate HttpCookieAppends = context =>
{
context.Response.Cookies.Append("A", "A");
context.Response.Cookies.Append("B", "B", new CookieOptions { HttpOnly = false });
context.Response.Cookies.Append("C", "C", new CookieOptions());
context.Response.Cookies.Append("D", "D", new CookieOptions { HttpOnly = true });
return Task.FromResult(0);
};
private readonly RequestDelegate SameSiteCookieAppends = context =>
{
context.Response.Cookies.Append("A", "A");
context.Response.Cookies.Append("B", "B", new CookieOptions());
context.Response.Cookies.Append("C", "C", new CookieOptions { SameSite = Http.SameSiteMode.None });
context.Response.Cookies.Append("D", "D", new CookieOptions { SameSite = Http.SameSiteMode.Lax });
context.Response.Cookies.Append("E", "E", new CookieOptions { SameSite = Http.SameSiteMode.Strict });
context.Response.Cookies.Append("F", "F", new CookieOptions { SameSite = (Http.SameSiteMode)(-1) });
return Task.FromResult(0);
};
[Fact]
public async Task SecureAlwaysSetsSecure()
{
await RunTest("/secureAlways",
new CookiePolicyOptions
{
Secure = CookieSecurePolicy.Always
},
SecureCookieAppends,
new RequestTest("http://example.com/secureAlways",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/; secure", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/; secure", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; secure", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; secure", transaction.SetCookie[3]);
}));
}
[Fact]
public async Task SecureNoneLeavesSecureUnchanged()
{
await RunTest("/secureNone",
new CookiePolicyOptions
{
Secure = CookieSecurePolicy.None
},
SecureCookieAppends,
new RequestTest("http://example.com/secureNone",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; secure", transaction.SetCookie[3]);
}));
}
[Fact]
public async Task SecureSameUsesRequest()
{
await RunTest("/secureSame",
new CookiePolicyOptions
{
Secure = CookieSecurePolicy.SameAsRequest
},
SecureCookieAppends,
new RequestTest("http://example.com/secureSame",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; secure", transaction.SetCookie[3]);
}),
new RequestTest("https://example.com/secureSame",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/; secure", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/; secure", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; secure", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; secure", transaction.SetCookie[3]);
}));
}
[Fact]
public async Task HttpOnlyAlwaysSetsItAlways()
{
await RunTest("/httpOnlyAlways",
new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always
},
HttpCookieAppends,
new RequestTest("http://example.com/httpOnlyAlways",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/; httponly", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/; httponly", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; httponly", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; httponly", transaction.SetCookie[3]);
}));
}
[Fact]
public async Task HttpOnlyNoneLeavesItAlone()
{
await RunTest("/httpOnlyNone",
new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.None
},
HttpCookieAppends,
new RequestTest("http://example.com/httpOnlyNone",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; httponly", transaction.SetCookie[3]);
}));
}
[Fact]
public async Task SameSiteStrictSetsItAlways()
{
await RunTest("/sameSiteStrict",
new CookiePolicyOptions
{
MinimumSameSitePolicy = Http.SameSiteMode.Strict
},
SameSiteCookieAppends,
new RequestTest("http://example.com/sameSiteStrict",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/; samesite=strict", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/; samesite=strict", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; samesite=strict", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; samesite=strict", transaction.SetCookie[3]);
Assert.Equal("E=E; path=/; samesite=strict", transaction.SetCookie[4]);
}));
}
[Fact]
public async Task SameSiteLaxSetsItAlways()
{
await RunTest("/sameSiteLax",
new CookiePolicyOptions
{
MinimumSameSitePolicy = Http.SameSiteMode.Lax
},
SameSiteCookieAppends,
new RequestTest("http://example.com/sameSiteLax",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/; samesite=lax", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/; samesite=lax", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; samesite=lax", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; samesite=lax", transaction.SetCookie[3]);
Assert.Equal("E=E; path=/; samesite=strict", transaction.SetCookie[4]);
}));
}
[Fact]
public async Task SameSiteNoneSetsItAlways()
{
await RunTest("/sameSiteNone",
new CookiePolicyOptions
{
MinimumSameSitePolicy = Http.SameSiteMode.None
},
SameSiteCookieAppends,
new RequestTest("http://example.com/sameSiteNone",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/; samesite=none", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/; samesite=none", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; samesite=none", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; samesite=lax", transaction.SetCookie[3]);
Assert.Equal("E=E; path=/; samesite=strict", transaction.SetCookie[4]);
}));
}
[Fact]
public async Task SameSiteUnspecifiedLeavesItAlone()
{
await RunTest("/sameSiteNone",
new CookiePolicyOptions
{
MinimumSameSitePolicy = Http.SameSiteMode.Unspecified
},
SameSiteCookieAppends,
new RequestTest("http://example.com/sameSiteNone",
transaction =>
{
Assert.NotNull(transaction.SetCookie);
Assert.Equal("A=A; path=/", transaction.SetCookie[0]);
Assert.Equal("B=B; path=/", transaction.SetCookie[1]);
Assert.Equal("C=C; path=/; samesite=none", transaction.SetCookie[2]);
Assert.Equal("D=D; path=/; samesite=lax", transaction.SetCookie[3]);
Assert.Equal("E=E; path=/; samesite=strict", transaction.SetCookie[4]);
Assert.Equal("F=F; path=/", transaction.SetCookie[5]);
}));
}
[Fact]
public async Task CookiePolicyCanHijackAppend()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao"
});
app.Run(context =>
{
context.Response.Cookies.Append("A", "A");
context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false });
context.Response.Cookies.Append("C", "C", new CookieOptions() { SameSite = Http.SameSiteMode.Strict });
context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
Assert.NotNull(transaction.SetCookie);
Assert.Equal("Hao=Hao; path=/", transaction.SetCookie[0]);
Assert.Equal("Hao=Hao; path=/", transaction.SetCookie[1]);
Assert.Equal("Hao=Hao; path=/; samesite=strict", transaction.SetCookie[2]);
Assert.Equal("Hao=Hao; path=/; secure", transaction.SetCookie[3]);
}
[Fact]
public async Task CookiePolicyCanHijackDelete()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context =>
{
context.Response.Cookies.Delete("A");
context.Response.Cookies.Delete("B", new CookieOptions { Secure = false });
context.Response.Cookies.Delete("C", new CookieOptions());
context.Response.Cookies.Delete("D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
Assert.NotNull(transaction.SetCookie);
Assert.Equal(1, transaction.SetCookie.Count);
Assert.Equal("A=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure", transaction.SetCookie[0]);
}
[Fact]
public async Task CookiePolicyCallsCookieFeature()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.Use(next => context =>
{
context.Features.Set<IResponseCookiesFeature>(new TestCookieFeature());
return next(context);
});
app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context =>
{
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A"));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A", new CookieOptions()));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Append("A", "A"));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Append("A", "A", new CookieOptions()));
return context.Response.WriteAsync("Done");
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
Assert.Equal("Done", transaction.ResponseText);
}
[Fact]
public async Task CookiePolicyAppliesToCookieAuth()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
});
app.UseAuthentication();
app.Run(context =>
{
return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("TestUser", "Cookies"))));
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.AddAuthentication().AddCookie(o =>
{
o.Cookie.Name = "TestCookie";
o.Cookie.HttpOnly = false;
o.Cookie.SecurePolicy = CookieSecurePolicy.None;
});
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
Assert.NotNull(transaction.SetCookie);
Assert.Equal(1, transaction.SetCookie.Count);
var cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[0]);
Assert.Equal("TestCookie", cookie.Name);
Assert.True(cookie.HttpOnly);
Assert.True(cookie.Secure);
Assert.Equal("/", cookie.Path);
}
[Fact]
public async Task CookiePolicyAppliesToCookieAuthChunks()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
});
app.UseAuthentication();
app.Run(context =>
{
return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(new string('c', 1024 * 5), "Cookies"))));
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.AddAuthentication().AddCookie(o =>
{
o.Cookie.Name = "TestCookie";
o.Cookie.HttpOnly = false;
o.Cookie.SecurePolicy = CookieSecurePolicy.None;
});
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
Assert.NotNull(transaction.SetCookie);
Assert.Equal(3, transaction.SetCookie.Count);
var cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[0]);
Assert.Equal("TestCookie", cookie.Name);
Assert.Equal("chunks-2", cookie.Value);
Assert.True(cookie.HttpOnly);
Assert.True(cookie.Secure);
Assert.Equal("/", cookie.Path);
cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[1]);
Assert.Equal("TestCookieC1", cookie.Name);
Assert.True(cookie.HttpOnly);
Assert.True(cookie.Secure);
Assert.Equal("/", cookie.Path);
cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[2]);
Assert.Equal("TestCookieC2", cookie.Name);
Assert.True(cookie.HttpOnly);
Assert.True(cookie.Secure);
Assert.Equal("/", cookie.Path);
}
private class TestCookieFeature : IResponseCookiesFeature
{
public IResponseCookies Cookies { get; } = new BadCookies();
private class BadCookies : IResponseCookies
{
public void Append(string key, string value)
{
throw new NotImplementedException();
}
public void Append(string key, string value, CookieOptions options)
{
throw new NotImplementedException();
}
public void Delete(string key)
{
throw new NotImplementedException();
}
public void Delete(string key, CookieOptions options)
{
throw new NotImplementedException();
}
}
}
private class RequestTest
{
public RequestTest(string testUri, Action<Transaction> verify)
{
TestUri = testUri;
Verification = verify;
}
public async Task Execute(TestServer server)
{
var transaction = await server.SendAsync(TestUri);
Verification(transaction);
}
public string TestUri { get; set; }
public Action<Transaction> Verification { get; set; }
}
private async Task RunTest(
string path,
CookiePolicyOptions cookiePolicy,
RequestDelegate configureSetup,
params RequestTest[] tests)
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.Map(path, map =>
{
map.UseCookiePolicy(cookiePolicy);
map.Run(configureSetup);
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
foreach (var test in tests)
{
await test.Execute(server);
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.Generic;
namespace Anima2D
{
[InitializeOnLoad]
public class EditorEventHandler
{
static List<SpriteMeshInstance> s_SpriteMeshInstances = new List<SpriteMeshInstance>();
static EditorEventHandler()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemCallback;
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
}
static SpriteMesh spriteMesh = null;
static SpriteMeshInstance instance = null;
static SpriteMeshInstance currentDestination = null;
static List<Bone2D> s_InstanceBones = new List<Bone2D>();
static bool init = false;
static Vector3 instancePosition = Vector3.zero;
static Transform parentTransform = null;
static SpriteMesh GetSpriteMesh()
{
SpriteMesh l_spriteMesh = null;
if(DragAndDrop.objectReferences.Length > 0)
{
Object obj = DragAndDrop.objectReferences[0];
l_spriteMesh = obj as SpriteMesh;
}
return l_spriteMesh;
}
static void Cleanup()
{
init = false;
spriteMesh = null;
instance = null;
currentDestination = null;
parentTransform = null;
s_InstanceBones.Clear();
}
static Vector3 GetMouseWorldPosition()
{
Ray mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
Plane rootPlane = new Plane(Vector3.forward,Vector3.zero);
float distance = 0f;
Vector3 mouseWorldPos = Vector3.zero;
if(rootPlane.Raycast(mouseRay, out distance))
{
mouseWorldPos = mouseRay.GetPoint(distance);
}
return mouseWorldPos;
}
static void CreateInstance()
{
instance = SpriteMeshUtils.CreateSpriteMeshInstance(spriteMesh,false);
if(instance)
{
s_InstanceBones = instance.bones;
instance.transform.parent = parentTransform;
if(parentTransform)
{
instance.transform.localPosition = Vector3.zero;
}
}
}
[UnityEditor.Callbacks.DidReloadScripts]
static void HierarchyWindowChanged()
{
s_SpriteMeshInstances = GameObject.FindObjectsOfType<SpriteMeshInstance>().ToList();
}
private static void HierarchyWindowItemCallback(int pID, Rect pRect)
{
instancePosition = Vector3.zero;
GameObject parent = null;
if(pRect.Contains(Event.current.mousePosition))
{
parent = EditorUtility.InstanceIDToObject(pID) as GameObject;
if(parent)
{
parentTransform = parent.transform;
}
}
HandleDragAndDrop(false,parentTransform);
}
static void OnSceneGUI(SceneView sceneview)
{
instancePosition = GetMouseWorldPosition();
HandleDragAndDrop(true,null);
}
static SpriteMeshInstance GetClosestBindeableIntersectingSpriteMeshInstance()
{
float minDistance = float.MaxValue;
SpriteMeshInstance closestSpriteMeshInstance = null;
foreach(SpriteMeshInstance spriteMeshInstance in s_SpriteMeshInstances)
{
if(spriteMeshInstance && spriteMeshInstance != instance && spriteMeshInstance.spriteMesh && spriteMeshInstance.cachedRenderer)
{
Ray guiRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
if(spriteMeshInstance.cachedRenderer.bounds.IntersectRay(guiRay))
{
if(Bindeable(instance,spriteMeshInstance))
{
Vector2 guiCenter = HandleUtility.WorldToGUIPoint(spriteMeshInstance.cachedRenderer.bounds.center);
float distance = (Event.current.mousePosition - guiCenter).sqrMagnitude;
if(distance < minDistance)
{
closestSpriteMeshInstance = spriteMeshInstance;
}
}
}
}
}
return closestSpriteMeshInstance;
}
static int FindBindInfo(BindInfo bindInfo, SpriteMeshInstance spriteMeshInstance)
{
if(spriteMeshInstance)
{
return FindBindInfo(bindInfo, SpriteMeshUtils.LoadSpriteMeshData(spriteMeshInstance.spriteMesh));
}
return -1;
}
static int FindBindInfo(BindInfo bindInfo, SpriteMeshData spriteMeshData)
{
if(bindInfo && spriteMeshData)
{
for(int i = 0; i < spriteMeshData.bindPoses.Length; ++i)
{
BindInfo l_bindInfo = spriteMeshData.bindPoses[i];
if(bindInfo.name == l_bindInfo.name /*&& Mathf.Approximately(bindInfo.boneLength,l_bindInfo.boneLength)*/)
{
return i;
}
}
}
return -1;
}
static bool Bindeable(SpriteMeshInstance targetSpriteMeshInstance, SpriteMeshInstance destinationSpriteMeshInstance)
{
bool bindeable = false;
if(targetSpriteMeshInstance &&
destinationSpriteMeshInstance &&
targetSpriteMeshInstance.spriteMesh &&
destinationSpriteMeshInstance.spriteMesh &&
targetSpriteMeshInstance.spriteMesh != destinationSpriteMeshInstance.spriteMesh &&
destinationSpriteMeshInstance.cachedSkinnedRenderer)
{
SpriteMeshData targetData = SpriteMeshUtils.LoadSpriteMeshData(targetSpriteMeshInstance.spriteMesh);
SpriteMeshData destinationData = SpriteMeshUtils.LoadSpriteMeshData(destinationSpriteMeshInstance.spriteMesh);
bindeable = true;
if(destinationData.bindPoses.Length >= targetData.bindPoses.Length)
{
for(int i = 0; i < targetData.bindPoses.Length; ++i)
{
if(bindeable)
{
BindInfo bindInfo = targetData.bindPoses[i];
if(FindBindInfo(bindInfo,destinationData) < 0)
{
bindeable = false;
}
}
}
}else{
bindeable = false;
}
}
return bindeable;
}
static void HandleDragAndDrop(bool createOnEnter, Transform parent)
{
switch(Event.current.type)
{
case EventType.DragUpdated:
if(!init)
{
spriteMesh = GetSpriteMesh();
if(createOnEnter)
{
parentTransform = null;
CreateInstance();
}
Event.current.Use();
init = true;
}
if(instance)
{
instance.transform.position = instancePosition;
SpriteMeshInstance l_currentDestination = GetClosestBindeableIntersectingSpriteMeshInstance();
if(currentDestination != l_currentDestination)
{
currentDestination = l_currentDestination;
if(currentDestination)
{
List<Bone2D> destinationBones = currentDestination.bones;
List<Bone2D> newBones = new List<Bone2D>();
SpriteMeshData data = SpriteMeshUtils.LoadSpriteMeshData(instance.spriteMesh);
for(int i = 0; i < data.bindPoses.Length; ++i)
{
BindInfo bindInfo = data.bindPoses[i];
int index = FindBindInfo(bindInfo,currentDestination);
if(index >= 0 && index < destinationBones.Count)
{
newBones.Add(destinationBones[index]);
}
}
instance.transform.parent = currentDestination.transform.parent;
instance.bones = newBones;
SpriteMeshUtils.UpdateRenderer(instance,false);
foreach(Bone2D bone in s_InstanceBones)
{
bone.hideFlags = HideFlags.HideAndDontSave;
bone.gameObject.SetActive(false);
}
}else{
foreach(Bone2D bone in s_InstanceBones)
{
bone.hideFlags = HideFlags.None;
bone.gameObject.SetActive(true);
}
instance.transform.parent = null;
instance.bones = s_InstanceBones;
SpriteMeshUtils.UpdateRenderer(instance,false);
}
SceneView.RepaintAll();
}
}
break;
case EventType.DragExited:
if(instance)
{
GameObject.DestroyImmediate(instance.gameObject);
Event.current.Use();
}
Cleanup();
break;
case EventType.DragPerform:
if(!createOnEnter)
{
CreateInstance();
}
if(instance)
{
if(currentDestination)
{
foreach(Bone2D bone in s_InstanceBones)
{
if(bone)
{
GameObject.DestroyImmediate(bone.gameObject);
}
}
}
Undo.RegisterCreatedObjectUndo(instance.gameObject,"create SpriteMeshInstance");
}
Cleanup();
break;
}
if(instance)
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update;
namespace Microsoft.Azure.Management.Network.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent.VirtualNetworkGatewayConnection.Definition;
using Microsoft.Azure.Management.Network.Fluent.VirtualNetworkGatewayConnection.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System.Collections.Generic;
internal partial class VirtualNetworkGatewayConnectionImpl
{
/// <summary>
/// Specify shared key.
/// </summary>
/// <param name="sharedKey">Shared key.</param>
/// <return>The next stage of the definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithCreate VirtualNetworkGatewayConnection.Definition.IWithSharedKey.WithSharedKey(string sharedKey)
{
return this.WithSharedKey(sharedKey);
}
/// <summary>
/// Specify shared key.
/// </summary>
/// <param name="sharedKey">Shared key.</param>
/// <return>The next stage of the update.</return>
VirtualNetworkGatewayConnection.Update.IUpdate VirtualNetworkGatewayConnection.Update.IWithSharedKey.WithSharedKey(string sharedKey)
{
return this.WithSharedKey(sharedKey);
}
/// <summary>
/// Gets the reference to virtual network gateway resource.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.VirtualNetworkGateway1Id
{
get
{
return this.VirtualNetworkGateway1Id();
}
}
/// <summary>
/// Gets the authorizationKey value.
/// </summary>
/// <summary>
/// Gets the authorizationKey value.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.AuthorizationKey
{
get
{
return this.AuthorizationKey();
}
}
/// <summary>
/// Gets the egress bytes transferred in this connection.
/// </summary>
long Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.IngressBytesTransferred
{
get
{
return this.IngressBytesTransferred();
}
}
/// <summary>
/// Gets the tunnelConnectionStatus value.
/// </summary>
/// <summary>
/// Gets collection of all tunnels' connection health status.
/// </summary>
System.Collections.Generic.IReadOnlyCollection<Models.TunnelConnectionHealth> Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.TunnelConnectionStatus
{
get
{
return this.TunnelConnectionStatus();
}
}
/// <summary>
/// Gets the Virtual Network Gateway connection status.
/// </summary>
/// <summary>
/// Gets the connectionStatus value.
/// </summary>
Models.VirtualNetworkGatewayConnectionStatus Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.ConnectionStatus
{
get
{
return this.ConnectionStatus();
}
}
/// <summary>
/// Gets the reference to local network gateway resource.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.LocalNetworkGateway2Id
{
get
{
return this.LocalNetworkGateway2Id();
}
}
/// <summary>
/// Gets the provisioning state of the VirtualNetworkGatewayConnection resource.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.ProvisioningState
{
get
{
return this.ProvisioningState();
}
}
/// <summary>
/// Gets the reference to virtual network gateway resource.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.VirtualNetworkGateway2Id
{
get
{
return this.VirtualNetworkGateway2Id();
}
}
/// <summary>
/// Gets if policy-based traffic selectors enabled.
/// </summary>
bool Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.UsePolicyBasedTrafficSelectors
{
get
{
return this.UsePolicyBasedTrafficSelectors();
}
}
/// <summary>
/// Gets the routing weight.
/// </summary>
int Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.RoutingWeight
{
get
{
return this.RoutingWeight();
}
}
/// <summary>
/// Gets the gateway connection type.
/// </summary>
/// <summary>
/// Gets the connectionType value.
/// </summary>
Models.VirtualNetworkGatewayConnectionType Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.ConnectionType
{
get
{
return this.ConnectionType();
}
}
/// <summary>
/// Gets the reference to peerings resource.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.PeerId
{
get
{
return this.PeerId();
}
}
/// <summary>
/// Gets the IPSec Policies to be considered by this connection.
/// </summary>
System.Collections.Generic.IReadOnlyCollection<Models.IpsecPolicy> Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.IpsecPolicies
{
get
{
return this.IpsecPolicies();
}
}
/// <summary>
/// Gets the egress bytes transferred in this connection.
/// </summary>
long Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.EgressBytesTransferred
{
get
{
return this.EgressBytesTransferred();
}
}
/// <summary>
/// Gets the IPSec shared key.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.SharedKey
{
get
{
return this.SharedKey();
}
}
/// <summary>
/// Gets the enableBgp flag.
/// </summary>
bool Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection.IsBgpEnabled
{
get
{
return this.IsBgpEnabled();
}
}
/// <summary>
/// Gets the parent of this child object.
/// </summary>
Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGateway Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasParent<Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGateway>.Parent
{
get
{
return this.Parent();
}
}
/// <param name="localNetworkGateway">Local network gateway to connect to.</param>
/// <return>The next stage of the definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithSharedKey VirtualNetworkGatewayConnection.Definition.IWithLocalNetworkGateway.WithLocalNetworkGateway(ILocalNetworkGateway localNetworkGateway)
{
return this.WithLocalNetworkGateway(localNetworkGateway);
}
/// <summary>
/// Specify authorization key.
/// This is required in case of Express Route connection if Express Route circuit and virtual network gateway reside in different subscriptions.
/// </summary>
/// <param name="authorizationKey">Authorization key to use.</param>
/// <return>The next stage of the definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithCreate VirtualNetworkGatewayConnection.Definition.IWithAuthorization.WithAuthorization(string authorizationKey)
{
return this.WithAuthorization(authorizationKey);
}
/// <summary>
/// Specify authorization key.
/// This is required in case of Express Route connection if Express Route circuit and virtual network gateway reside in different subscriptions.
/// </summary>
/// <param name="authorizationKey">Authorization key to use.</param>
/// <return>The next stage of the update.</return>
VirtualNetworkGatewayConnection.Update.IUpdate VirtualNetworkGatewayConnection.Update.IWithAuthorization.WithAuthorization(string authorizationKey)
{
return this.WithAuthorization(authorizationKey);
}
/// <summary>
/// Enable BGP for the connection.
/// </summary>
/// <return>The next stage of the definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithCreate VirtualNetworkGatewayConnection.Definition.IWithBgp.WithBgp()
{
return this.WithBgp();
}
/// <summary>
/// Disable BGP for the connection.
/// </summary>
/// <return>The next stage of the update.</return>
VirtualNetworkGatewayConnection.Update.IUpdate VirtualNetworkGatewayConnection.Update.IWithBgp.WithoutBgp()
{
return this.WithoutBgp();
}
/// <summary>
/// Enable BGP for the connection.
/// </summary>
/// <return>The next stage of the update.</return>
VirtualNetworkGatewayConnection.Update.IUpdate VirtualNetworkGatewayConnection.Update.IWithBgp.WithBgp()
{
return this.WithBgp();
}
/// <summary>
/// Create Site-to-Site connection.
/// </summary>
/// <return>Next stage of definition, allowing to specify local network gateway.</return>
VirtualNetworkGatewayConnection.Definition.IWithLocalNetworkGateway VirtualNetworkGatewayConnection.Definition.IWithConnectionType.WithSiteToSite()
{
return this.WithSiteToSite();
}
/// <summary>
/// Create VNet-to-VNet connection.
/// </summary>
/// <return>The next stage of the definition, allowing to specify virtual network gateway to connect to.</return>
VirtualNetworkGatewayConnection.Definition.IWithSecondVirtualNetworkGateway VirtualNetworkGatewayConnection.Definition.IWithConnectionType.WithVNetToVNet()
{
return this.WithVNetToVNet();
}
/// <summary>
/// Create Express Route connection.
/// </summary>
/// <param name="circuitId">Id of Express Route circuit used for connection.</param>
/// <return>Next stage of definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithCreate VirtualNetworkGatewayConnection.Definition.IWithConnectionType.WithExpressRoute(string circuitId)
{
return this.WithExpressRoute(circuitId);
}
/// <summary>
/// Create Express Route connection.
/// </summary>
/// <param name="circuit">Express Route circuit used for connection.</param>
/// <return>The next stage of the definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithCreate VirtualNetworkGatewayConnection.Definition.IWithConnectionType.WithExpressRoute(IExpressRouteCircuit circuit)
{
return this.WithExpressRoute(circuit);
}
/// <param name="virtualNetworkGateway2">Virtual network gateway to connect to.</param>
/// <return>The next stage of the definition.</return>
VirtualNetworkGatewayConnection.Definition.IWithSharedKey VirtualNetworkGatewayConnection.Definition.IWithSecondVirtualNetworkGateway.WithSecondVirtualNetworkGateway(IVirtualNetworkGateway virtualNetworkGateway2)
{
return this.WithSecondVirtualNetworkGateway(virtualNetworkGateway2);
}
public IAppliableWithTags<IVirtualNetworkGatewayConnection> WithoutTag(string key)
{
return base.WithoutTag(key);
}
public IAppliableWithTags<IVirtualNetworkGatewayConnection> WithTag(string key, string value)
{
return base.WithTag(key, value);
}
public IAppliableWithTags<IVirtualNetworkGatewayConnection> WithTags(IDictionary<string, string> tags)
{
return base.WithTags(tags);
}
IWithCreate IDefinitionWithTags<IWithCreate>.WithTags(IDictionary<string, string> tags)
{
return base.WithTags(tags);
}
IUpdate IUpdateWithTags<IUpdate>.WithTag(string key, string value)
{
return base.WithTag(key, value);
}
IUpdate IUpdateWithTags<IUpdate>.WithoutTag(string key)
{
return base.WithoutTag(key);
}
IUpdate IUpdateWithTags<IUpdate>.WithTags(IDictionary<string, string> tags)
{
return base.WithTags(tags);
}
IWithCreate IDefinitionWithTags<IWithCreate>.WithTag(string key, string value)
{
return base.WithTag(key, value);
}
}
}
| |
#if !ISOLATION_IN_MSCORLIB
#define FEATURE_COMINTEROP
#endif
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
using System.Globalization;
using System.Threading;
using System.Security;
using System.Deployment.Internal.Isolation;
namespace System.Deployment.Internal.Isolation.Manifest
{
#if FEATURE_COMINTEROP
internal enum CMSSECTIONID
{
CMSSECTIONID_FILE_SECTION = 1,
CMSSECTIONID_CATEGORY_INSTANCE_SECTION = 2,
CMSSECTIONID_COM_REDIRECTION_SECTION = 3,
CMSSECTIONID_PROGID_REDIRECTION_SECTION = 4,
CMSSECTIONID_CLR_SURROGATE_SECTION = 5,
CMSSECTIONID_ASSEMBLY_REFERENCE_SECTION = 6,
CMSSECTIONID_WINDOW_CLASS_SECTION = 8,
CMSSECTIONID_STRING_SECTION = 9,
CMSSECTIONID_ENTRYPOINT_SECTION = 10,
CMSSECTIONID_PERMISSION_SET_SECTION = 11,
CMSSECTIONENTRYID_METADATA = 12,
CMSSECTIONID_ASSEMBLY_REQUEST_SECTION = 13,
CMSSECTIONID_REGISTRY_KEY_SECTION = 16,
CMSSECTIONID_DIRECTORY_SECTION = 17,
CMSSECTIONID_FILE_ASSOCIATION_SECTION = 18,
CMSSECTIONID_COMPATIBLE_FRAMEWORKS_SECTION = 19,
CMSSECTIONID_EVENT_SECTION = 101,
CMSSECTIONID_EVENT_MAP_SECTION = 102,
CMSSECTIONID_EVENT_TAG_SECTION = 103,
CMSSECTIONID_COUNTERSET_SECTION = 110,
CMSSECTIONID_COUNTER_SECTION = 111,
}
internal enum CMS_ASSEMBLY_DEPLOYMENT_FLAG
{
CMS_ASSEMBLY_DEPLOYMENT_FLAG_BEFORE_APPLICATION_STARTUP = 4,
CMS_ASSEMBLY_DEPLOYMENT_FLAG_RUN_AFTER_INSTALL = 16,
CMS_ASSEMBLY_DEPLOYMENT_FLAG_INSTALL = 32,
CMS_ASSEMBLY_DEPLOYMENT_FLAG_TRUST_URL_PARAMETERS = 64,
CMS_ASSEMBLY_DEPLOYMENT_FLAG_DISALLOW_URL_ACTIVATION = 128,
CMS_ASSEMBLY_DEPLOYMENT_FLAG_MAP_FILE_EXTENSIONS = 256,
CMS_ASSEMBLY_DEPLOYMENT_FLAG_CREATE_DESKTOP_SHORTCUT = 512,
}
internal enum CMS_ASSEMBLY_REFERENCE_FLAG
{
CMS_ASSEMBLY_REFERENCE_FLAG_OPTIONAL = 1,
CMS_ASSEMBLY_REFERENCE_FLAG_VISIBLE = 2,
CMS_ASSEMBLY_REFERENCE_FLAG_FOLLOW = 4,
CMS_ASSEMBLY_REFERENCE_FLAG_IS_PLATFORM = 8,
CMS_ASSEMBLY_REFERENCE_FLAG_CULTURE_WILDCARDED = 16,
CMS_ASSEMBLY_REFERENCE_FLAG_PROCESSOR_ARCHITECTURE_WILDCARDED = 32,
CMS_ASSEMBLY_REFERENCE_FLAG_PREREQUISITE = 128,
}
internal enum CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG
{
CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG_OPTIONAL = 1,
CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG_VISIBLE = 2,
CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG_PREREQUISITE = 4,
CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG_RESOURCE_FALLBACK_CULTURE_INTERNAL = 8,
CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG_INSTALL = 16,
CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG_ALLOW_DELAYED_BINDING = 32,
}
internal enum CMS_FILE_FLAG
{
CMS_FILE_FLAG_OPTIONAL = 1,
}
internal enum CMS_ENTRY_POINT_FLAG
{
CMS_ENTRY_POINT_FLAG_HOST_IN_BROWSER = 1,
CMS_ENTRY_POINT_FLAG_CUSTOMHOSTSPECIFIED = 2,
CMS_ENTRY_POINT_FLAG_CUSTOMUX = 4,
}
internal enum CMS_COM_SERVER_FLAG
{
CMS_COM_SERVER_FLAG_IS_CLR_CLASS = 1,
}
#if !ISOLATION_IN_MSCORLIB
internal enum CMS_REGISTRY_KEY_FLAG
{
CMS_REGISTRY_KEY_FLAG_OWNER = 1,
CMS_REGISTRY_KEY_FLAG_LEAF_IN_MANIFEST = 2,
}
internal enum CMS_REGISTRY_VALUE_FLAG
{
CMS_REGISTRY_VALUE_FLAG_OWNER = 1,
}
internal enum CMS_DIRECTORY_FLAG
{
CMS_DIRECTORY_FLAG_OWNER = 1,
}
internal enum CMS_MANIFEST_FLAG
{
CMS_MANIFEST_FLAG_ASSEMBLY = 1,
CMS_MANIFEST_FLAG_CATEGORY = 2,
CMS_MANIFEST_FLAG_FEATURE = 3,
CMS_MANIFEST_FLAG_APPLICATION = 4,
CMS_MANIFEST_FLAG_USEMANIFESTFORTRUST = 8,
}
#endif
internal enum CMS_USAGE_PATTERN
{
CMS_USAGE_PATTERN_SCOPE_APPLICATION = 1,
CMS_USAGE_PATTERN_SCOPE_PROCESS = 2,
CMS_USAGE_PATTERN_SCOPE_MACHINE = 3,
CMS_USAGE_PATTERN_SCOPE_MASK = 7,
}
internal enum CMS_SCHEMA_VERSION
{
CMS_SCHEMA_VERSION_V1 = 1,
}
internal enum CMS_FILE_HASH_ALGORITHM
{
CMS_FILE_HASH_ALGORITHM_SHA1 = 1,
CMS_FILE_HASH_ALGORITHM_SHA256 = 2,
CMS_FILE_HASH_ALGORITHM_SHA384 = 3,
CMS_FILE_HASH_ALGORITHM_SHA512 = 4,
CMS_FILE_HASH_ALGORITHM_MD5 = 5,
CMS_FILE_HASH_ALGORITHM_MD4 = 6,
CMS_FILE_HASH_ALGORITHM_MD2 = 7,
}
internal enum CMS_TIME_UNIT_TYPE
{
CMS_TIME_UNIT_TYPE_HOURS = 1,
CMS_TIME_UNIT_TYPE_DAYS = 2,
CMS_TIME_UNIT_TYPE_WEEKS = 3,
CMS_TIME_UNIT_TYPE_MONTHS = 4,
}
#if !ISOLATION_IN_MSCORLIB
internal enum CMS_REGISTRY_VALUE_TYPE
{
CMS_REGISTRY_VALUE_TYPE_NONE = 0,
CMS_REGISTRY_VALUE_TYPE_SZ = 1,
CMS_REGISTRY_VALUE_TYPE_EXPAND_SZ = 2,
CMS_REGISTRY_VALUE_TYPE_MULTI_SZ = 3,
CMS_REGISTRY_VALUE_TYPE_BINARY = 4,
CMS_REGISTRY_VALUE_TYPE_DWORD = 5,
CMS_REGISTRY_VALUE_TYPE_DWORD_LITTLE_ENDIAN = 6,
CMS_REGISTRY_VALUE_TYPE_DWORD_BIG_ENDIAN = 7,
CMS_REGISTRY_VALUE_TYPE_LINK = 8,
CMS_REGISTRY_VALUE_TYPE_RESOURCE_LIST = 9,
CMS_REGISTRY_VALUE_TYPE_FULL_RESOURCE_DESCRIPTOR = 10,
CMS_REGISTRY_VALUE_TYPE_RESOURCE_REQUIREMENTS_LIST = 11,
CMS_REGISTRY_VALUE_TYPE_QWORD = 12,
CMS_REGISTRY_VALUE_TYPE_QWORD_LITTLE_ENDIAN = 13,
}
internal enum CMS_REGISTRY_VALUE_HINT
{
CMS_REGISTRY_VALUE_HINT_REPLACE = 1,
CMS_REGISTRY_VALUE_HINT_APPEND = 2,
CMS_REGISTRY_VALUE_HINT_PREPEND = 3,
}
internal enum CMS_SYSTEM_PROTECTION
{
CMS_SYSTEM_PROTECTION_READ_ONLY_IGNORE_WRITES = 1,
CMS_SYSTEM_PROTECTION_READ_ONLY_FAIL_WRITES = 2,
CMS_SYSTEM_PROTECTION_OS_ONLY_IGNORE_WRITES = 3,
CMS_SYSTEM_PROTECTION_OS_ONLY_FAIL_WRITES = 4,
CMS_SYSTEM_PROTECTION_TRANSACTED = 5,
CMS_SYSTEM_PROTECTION_APPLICATION_VIRTUALIZED = 6,
CMS_SYSTEM_PROTECTION_USER_VIRTUALIZED = 7,
CMS_SYSTEM_PROTECTION_APPLICATION_AND_USER_VIRTUALIZED = 8,
CMS_SYSTEM_PROTECTION_INHERIT = 9,
CMS_SYSTEM_PROTECTION_NOT_PROTECTED = 10,
}
#endif
internal enum CMS_FILE_WRITABLE_TYPE
{
CMS_FILE_WRITABLE_TYPE_NOT_WRITABLE = 1,
CMS_FILE_WRITABLE_TYPE_APPLICATION_DATA = 2,
}
internal enum CMS_HASH_TRANSFORM
{
CMS_HASH_TRANSFORM_IDENTITY = 1,
CMS_HASH_TRANSFORM_MANIFESTINVARIANT = 2,
}
internal enum CMS_HASH_DIGESTMETHOD
{
CMS_HASH_DIGESTMETHOD_SHA1 = 1,
CMS_HASH_DIGESTMETHOD_SHA256 = 2,
CMS_HASH_DIGESTMETHOD_SHA384 = 3,
CMS_HASH_DIGESTMETHOD_SHA512 = 4,
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown),Guid("a504e5b0-8ccf-4cb4-9902-c9d1b9abd033")]
internal interface ICMS
{
IDefinitionIdentity Identity { [SecurityCritical]get; }
ISection FileSection { [SecurityCritical]get; }
ISection CategoryMembershipSection { [SecurityCritical]get; }
ISection COMRedirectionSection { [SecurityCritical]get; }
ISection ProgIdRedirectionSection { [SecurityCritical]get; }
ISection CLRSurrogateSection { [SecurityCritical]get; }
ISection AssemblyReferenceSection { [SecurityCritical]get; }
ISection WindowClassSection { [SecurityCritical]get; }
ISection StringSection { [SecurityCritical]get; }
ISection EntryPointSection { [SecurityCritical]get; }
ISection PermissionSetSection { [SecurityCritical]get; }
ISectionEntry MetadataSectionEntry { [SecurityCritical]get; }
ISection AssemblyRequestSection { [SecurityCritical]get; }
ISection RegistryKeySection { [SecurityCritical]get; }
ISection DirectorySection { [SecurityCritical]get; }
ISection FileAssociationSection { [SecurityCritical]get; }
ISection CompatibleFrameworksSection { [SecurityCritical]get; }
ISection EventSection { [SecurityCritical]get; }
ISection EventMapSection { [SecurityCritical]get; }
ISection EventTagSection { [SecurityCritical]get; }
ISection CounterSetSection { [SecurityCritical]get; }
ISection CounterSection { [SecurityCritical]get; }
}
//++! start object [MuiResourceIdLookupMap]
[StructLayout(LayoutKind.Sequential)]
internal class MuiResourceIdLookupMapEntry
{
public uint Count;
};
internal enum MuiResourceIdLookupMapEntryFieldId
{
MuiResourceIdLookupMap_Count,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("24abe1f7-a396-4a03-9adf-1d5b86a5569f")]
internal interface IMuiResourceIdLookupMapEntry
{
MuiResourceIdLookupMapEntry AllData { [SecurityCritical]get; }
uint Count { [SecurityCritical]get; }
};
//++! end object [MuiResourceIdLookupMap]
//++! start object [MuiResourceTypeIdString]
[StructLayout(LayoutKind.Sequential)]
internal class MuiResourceTypeIdStringEntry : IDisposable
{
[MarshalAs(UnmanagedType.SysInt)] public IntPtr StringIds;
public uint StringIdsSize;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr IntegerIds;
public uint IntegerIdsSize;
~MuiResourceTypeIdStringEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (StringIds != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(StringIds);
StringIds = IntPtr.Zero;
}
if (IntegerIds != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(IntegerIds);
IntegerIds = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum MuiResourceTypeIdStringEntryFieldId
{
MuiResourceTypeIdString_StringIds,
MuiResourceTypeIdString_StringIdsSize,
MuiResourceTypeIdString_IntegerIds,
MuiResourceTypeIdString_IntegerIdsSize,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("11df5cad-c183-479b-9a44-3842b71639ce")]
internal interface IMuiResourceTypeIdStringEntry
{
MuiResourceTypeIdStringEntry AllData { [SecurityCritical]get; }
object StringIds { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
object IntegerIds { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
};
//++! end object [MuiResourceTypeIdString]
//++! start object [MuiResourceTypeIdInt]
[StructLayout(LayoutKind.Sequential)]
internal class MuiResourceTypeIdIntEntry : IDisposable
{
[MarshalAs(UnmanagedType.SysInt)] public IntPtr StringIds;
public uint StringIdsSize;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr IntegerIds;
public uint IntegerIdsSize;
~MuiResourceTypeIdIntEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (StringIds != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(StringIds);
StringIds = IntPtr.Zero;
}
if (IntegerIds != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(IntegerIds);
IntegerIds = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum MuiResourceTypeIdIntEntryFieldId
{
MuiResourceTypeIdInt_StringIds,
MuiResourceTypeIdInt_StringIdsSize,
MuiResourceTypeIdInt_IntegerIds,
MuiResourceTypeIdInt_IntegerIdsSize,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("55b2dec1-d0f6-4bf4-91b1-30f73ad8e4df")]
internal interface IMuiResourceTypeIdIntEntry
{
MuiResourceTypeIdIntEntry AllData { [SecurityCritical]get; }
object StringIds { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
object IntegerIds { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
};
//++! end object [MuiResourceTypeIdInt]
//++! start object [MuiResourceMap]
[StructLayout(LayoutKind.Sequential)]
internal class MuiResourceMapEntry : IDisposable
{
[MarshalAs(UnmanagedType.SysInt)] public IntPtr ResourceTypeIdInt;
public uint ResourceTypeIdIntSize;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr ResourceTypeIdString;
public uint ResourceTypeIdStringSize;
~MuiResourceMapEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (ResourceTypeIdInt != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(ResourceTypeIdInt);
ResourceTypeIdInt = IntPtr.Zero;
}
if (ResourceTypeIdString != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(ResourceTypeIdString);
ResourceTypeIdString = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum MuiResourceMapEntryFieldId
{
MuiResourceMap_ResourceTypeIdInt,
MuiResourceMap_ResourceTypeIdIntSize,
MuiResourceMap_ResourceTypeIdString,
MuiResourceMap_ResourceTypeIdStringSize,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("397927f5-10f2-4ecb-bfe1-3c264212a193")]
internal interface IMuiResourceMapEntry
{
MuiResourceMapEntry AllData { [SecurityCritical]get; }
object ResourceTypeIdInt { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
object ResourceTypeIdString { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
};
//++! end object [MuiResourceMap]
//++! start object [HashElement]
[StructLayout(LayoutKind.Sequential)]
internal class HashElementEntry : IDisposable
{
public uint index;
public byte Transform;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr TransformMetadata;
public uint TransformMetadataSize;
public byte DigestMethod;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr DigestValue;
public uint DigestValueSize;
[MarshalAs(UnmanagedType.LPWStr)] public string Xml;
~HashElementEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (TransformMetadata != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(TransformMetadata);
TransformMetadata = IntPtr.Zero;
}
if (DigestValue != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(DigestValue);
DigestValue = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum HashElementEntryFieldId
{
HashElement_Transform,
HashElement_TransformMetadata,
HashElement_TransformMetadataSize,
HashElement_DigestMethod,
HashElement_DigestValue,
HashElement_DigestValueSize,
HashElement_Xml,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("9D46FB70-7B54-4f4f-9331-BA9E87833FF5")]
internal interface IHashElementEntry
{
HashElementEntry AllData { [SecurityCritical]get; }
uint index { [SecurityCritical]get; }
byte Transform { [SecurityCritical]get; }
object TransformMetadata { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
byte DigestMethod { [SecurityCritical]get; }
object DigestValue { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
string Xml { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [HashElement]
//++! start object [File]
[StructLayout(LayoutKind.Sequential)]
internal class FileEntry : IDisposable
{
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
public uint HashAlgorithm;
[MarshalAs(UnmanagedType.LPWStr)] public string LoadFrom;
[MarshalAs(UnmanagedType.LPWStr)] public string SourcePath;
[MarshalAs(UnmanagedType.LPWStr)] public string ImportPath;
[MarshalAs(UnmanagedType.LPWStr)] public string SourceName;
[MarshalAs(UnmanagedType.LPWStr)] public string Location;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr HashValue;
public uint HashValueSize;
public ulong Size;
[MarshalAs(UnmanagedType.LPWStr)] public string Group;
public uint Flags;
public MuiResourceMapEntry MuiMapping;
public uint WritableType;
public ISection HashElements;
~FileEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (HashValue != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(HashValue);
HashValue = IntPtr.Zero;
}
if (fDisposing) {
if( MuiMapping != null) {
MuiMapping.Dispose(true);
MuiMapping = null;
}
System.GC.SuppressFinalize(this);
}
}
};
internal enum FileEntryFieldId
{
File_HashAlgorithm,
File_LoadFrom,
File_SourcePath,
File_ImportPath,
File_SourceName,
File_Location,
File_HashValue,
File_HashValueSize,
File_Size,
File_Group,
File_Flags,
File_MuiMapping,
File_WritableType,
File_HashElements,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("A2A55FAD-349B-469b-BF12-ADC33D14A937")]
internal interface IFileEntry
{
FileEntry AllData { [SecurityCritical]get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint HashAlgorithm { [SecurityCritical]get; }
string LoadFrom { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string SourcePath { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string ImportPath { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string SourceName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Location { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
object HashValue { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
ulong Size { [SecurityCritical]get; }
string Group { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint Flags { [SecurityCritical]get; }
IMuiResourceMapEntry MuiMapping { [SecurityCritical]get; }
uint WritableType { [SecurityCritical]get; }
ISection HashElements { [SecurityCritical]get; }
};
//++! end object [File]
//++! start object [FileAssociation]
[StructLayout(LayoutKind.Sequential)]
internal class FileAssociationEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Extension;
[MarshalAs(UnmanagedType.LPWStr)] public string Description;
[MarshalAs(UnmanagedType.LPWStr)] public string ProgID;
[MarshalAs(UnmanagedType.LPWStr)] public string DefaultIcon;
[MarshalAs(UnmanagedType.LPWStr)] public string Parameter;
};
internal enum FileAssociationEntryFieldId
{
FileAssociation_Description,
FileAssociation_ProgID,
FileAssociation_DefaultIcon,
FileAssociation_Parameter,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("0C66F299-E08E-48c5-9264-7CCBEB4D5CBB")]
internal interface IFileAssociationEntry
{
FileAssociationEntry AllData { [SecurityCritical]get; }
string Extension { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Description { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string ProgID { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string DefaultIcon { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Parameter { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [FileAssociation]
//++! start object [CategoryMembershipData]
[StructLayout(LayoutKind.Sequential)]
internal class CategoryMembershipDataEntry
{
public uint index;
[MarshalAs(UnmanagedType.LPWStr)] public string Xml;
[MarshalAs(UnmanagedType.LPWStr)] public string Description;
};
internal enum CategoryMembershipDataEntryFieldId
{
CategoryMembershipData_Xml,
CategoryMembershipData_Description,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DA0C3B27-6B6B-4b80-A8F8-6CE14F4BC0A4")]
internal interface ICategoryMembershipDataEntry
{
CategoryMembershipDataEntry AllData { [SecurityCritical]get; }
uint index { [SecurityCritical]get; }
string Xml { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Description { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [CategoryMembershipData]
//++! start object [SubcategoryMembership]
[StructLayout(LayoutKind.Sequential)]
internal class SubcategoryMembershipEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Subcategory;
public ISection CategoryMembershipData;
};
internal enum SubcategoryMembershipEntryFieldId
{
SubcategoryMembership_CategoryMembershipData,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5A7A54D7-5AD5-418e-AB7A-CF823A8D48D0")]
internal interface ISubcategoryMembershipEntry
{
SubcategoryMembershipEntry AllData { [SecurityCritical]get; }
string Subcategory { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
ISection CategoryMembershipData { [SecurityCritical]get; }
};
//++! end object [SubcategoryMembership]
//++! start object [CategoryMembership]
[StructLayout(LayoutKind.Sequential)]
internal class CategoryMembershipEntry
{
public IDefinitionIdentity Identity;
public ISection SubcategoryMembership;
};
internal enum CategoryMembershipEntryFieldId
{
CategoryMembership_SubcategoryMembership,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("97FDCA77-B6F2-4718-A1EB-29D0AECE9C03")]
internal interface ICategoryMembershipEntry
{
CategoryMembershipEntry AllData { [SecurityCritical]get; }
IDefinitionIdentity Identity { [SecurityCritical]get; }
ISection SubcategoryMembership { [SecurityCritical]get; }
};
//++! end object [CategoryMembership]
//++! start object [COMServer]
[StructLayout(LayoutKind.Sequential)]
internal class COMServerEntry
{
public Guid Clsid;
public uint Flags;
public Guid ConfiguredGuid;
public Guid ImplementedClsid;
public Guid TypeLibrary;
public uint ThreadingModel;
[MarshalAs(UnmanagedType.LPWStr)] public string RuntimeVersion;
[MarshalAs(UnmanagedType.LPWStr)] public string HostFile;
};
internal enum COMServerEntryFieldId
{
COMServer_Flags,
COMServer_ConfiguredGuid,
COMServer_ImplementedClsid,
COMServer_TypeLibrary,
COMServer_ThreadingModel,
COMServer_RuntimeVersion,
COMServer_HostFile,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("3903B11B-FBE8-477c-825F-DB828B5FD174")]
internal interface ICOMServerEntry
{
COMServerEntry AllData { [SecurityCritical]get; }
Guid Clsid { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
Guid ConfiguredGuid { [SecurityCritical]get; }
Guid ImplementedClsid { [SecurityCritical]get; }
Guid TypeLibrary { [SecurityCritical]get; }
uint ThreadingModel { [SecurityCritical]get; }
string RuntimeVersion { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string HostFile { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [COMServer]
//++! start object [ProgIdRedirection]
[StructLayout(LayoutKind.Sequential)]
internal class ProgIdRedirectionEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string ProgId;
public Guid RedirectedGuid;
};
internal enum ProgIdRedirectionEntryFieldId
{
ProgIdRedirection_RedirectedGuid,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("54F198EC-A63A-45ea-A984-452F68D9B35B")]
internal interface IProgIdRedirectionEntry
{
ProgIdRedirectionEntry AllData { [SecurityCritical]get; }
string ProgId { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
Guid RedirectedGuid { [SecurityCritical]get; }
};
//++! end object [ProgIdRedirection]
//++! start object [CLRSurrogate]
[StructLayout(LayoutKind.Sequential)]
internal class CLRSurrogateEntry
{
public Guid Clsid;
[MarshalAs(UnmanagedType.LPWStr)] public string RuntimeVersion;
[MarshalAs(UnmanagedType.LPWStr)] public string ClassName;
};
internal enum CLRSurrogateEntryFieldId
{
CLRSurrogate_RuntimeVersion,
CLRSurrogate_ClassName,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("1E0422A1-F0D2-44ae-914B-8A2DECCFD22B")]
internal interface ICLRSurrogateEntry
{
CLRSurrogateEntry AllData { [SecurityCritical]get; }
Guid Clsid { [SecurityCritical]get; }
string RuntimeVersion { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string ClassName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [CLRSurrogate]
//++! start object [AssemblyReferenceDependentAssembly]
[StructLayout(LayoutKind.Sequential)]
internal class AssemblyReferenceDependentAssemblyEntry : IDisposable
{
[MarshalAs(UnmanagedType.LPWStr)] public string Group;
[MarshalAs(UnmanagedType.LPWStr)] public string Codebase;
public ulong Size;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr HashValue;
public uint HashValueSize;
public uint HashAlgorithm;
public uint Flags;
[MarshalAs(UnmanagedType.LPWStr)] public string ResourceFallbackCulture;
[MarshalAs(UnmanagedType.LPWStr)] public string Description;
[MarshalAs(UnmanagedType.LPWStr)] public string SupportUrl;
public ISection HashElements;
~AssemblyReferenceDependentAssemblyEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (HashValue != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(HashValue);
HashValue = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum AssemblyReferenceDependentAssemblyEntryFieldId
{
AssemblyReferenceDependentAssembly_Group,
AssemblyReferenceDependentAssembly_Codebase,
AssemblyReferenceDependentAssembly_Size,
AssemblyReferenceDependentAssembly_HashValue,
AssemblyReferenceDependentAssembly_HashValueSize,
AssemblyReferenceDependentAssembly_HashAlgorithm,
AssemblyReferenceDependentAssembly_Flags,
AssemblyReferenceDependentAssembly_ResourceFallbackCulture,
AssemblyReferenceDependentAssembly_Description,
AssemblyReferenceDependentAssembly_SupportUrl,
AssemblyReferenceDependentAssembly_HashElements,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("C31FF59E-CD25-47b8-9EF3-CF4433EB97CC")]
internal interface IAssemblyReferenceDependentAssemblyEntry
{
AssemblyReferenceDependentAssemblyEntry AllData { [SecurityCritical]get; }
string Group { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Codebase { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
ulong Size { [SecurityCritical]get; }
object HashValue { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
uint HashAlgorithm { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
string ResourceFallbackCulture { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Description { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string SupportUrl { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
ISection HashElements { [SecurityCritical]get; }
};
//++! end object [AssemblyReferenceDependentAssembly]
//++! start object [AssemblyReference]
[StructLayout(LayoutKind.Sequential)]
internal class AssemblyReferenceEntry
{
public IReferenceIdentity ReferenceIdentity;
public uint Flags;
public AssemblyReferenceDependentAssemblyEntry DependentAssembly;
};
internal enum AssemblyReferenceEntryFieldId
{
AssemblyReference_Flags,
AssemblyReference_DependentAssembly,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("FD47B733-AFBC-45e4-B7C2-BBEB1D9F766C")]
internal interface IAssemblyReferenceEntry
{
AssemblyReferenceEntry AllData { [SecurityCritical]get; }
IReferenceIdentity ReferenceIdentity { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
IAssemblyReferenceDependentAssemblyEntry DependentAssembly { [SecurityCritical]get; }
};
//++! end object [AssemblyReference]
//++! start object [WindowClass]
[StructLayout(LayoutKind.Sequential)]
internal class WindowClassEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string ClassName;
[MarshalAs(UnmanagedType.LPWStr)] public string HostDll;
public bool fVersioned;
};
internal enum WindowClassEntryFieldId
{
WindowClass_HostDll,
WindowClass_fVersioned,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("8AD3FC86-AFD3-477a-8FD5-146C291195BA")]
internal interface IWindowClassEntry
{
WindowClassEntry AllData { [SecurityCritical]get; }
string ClassName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string HostDll { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
bool fVersioned { [SecurityCritical]get; }
};
//++! end object [WindowClass]
//++! start object [ResourceTableMapping]
[StructLayout(LayoutKind.Sequential)]
internal class ResourceTableMappingEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string id;
[MarshalAs(UnmanagedType.LPWStr)] public string FinalStringMapped;
};
internal enum ResourceTableMappingEntryFieldId
{
ResourceTableMapping_FinalStringMapped,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("70A4ECEE-B195-4c59-85BF-44B6ACA83F07")]
internal interface IResourceTableMappingEntry
{
ResourceTableMappingEntry AllData { [SecurityCritical]get; }
string id { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string FinalStringMapped { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [ResourceTableMapping]
//++! start object [EntryPoint]
[StructLayout(LayoutKind.Sequential)]
internal class EntryPointEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
[MarshalAs(UnmanagedType.LPWStr)] public string CommandLine_File;
[MarshalAs(UnmanagedType.LPWStr)] public string CommandLine_Parameters;
public IReferenceIdentity Identity;
public uint Flags;
};
internal enum EntryPointEntryFieldId
{
EntryPoint_CommandLine_File,
EntryPoint_CommandLine_Parameters,
EntryPoint_Identity,
EntryPoint_Flags,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("1583EFE9-832F-4d08-B041-CAC5ACEDB948")]
internal interface IEntryPointEntry
{
EntryPointEntry AllData { [SecurityCritical]get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string CommandLine_File { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string CommandLine_Parameters { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
IReferenceIdentity Identity { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
};
//++! end object [EntryPoint]
//++! start object [PermissionSet]
[StructLayout(LayoutKind.Sequential)]
internal class PermissionSetEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Id;
[MarshalAs(UnmanagedType.LPWStr)] public string XmlSegment;
};
internal enum PermissionSetEntryFieldId
{
PermissionSet_XmlSegment,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("EBE5A1ED-FEBC-42c4-A9E1-E087C6E36635")]
internal interface IPermissionSetEntry
{
PermissionSetEntry AllData { [SecurityCritical]get; }
string Id { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string XmlSegment { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [PermissionSet]
//++! start object [AssemblyRequest]
[StructLayout(LayoutKind.Sequential)]
internal class AssemblyRequestEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
[MarshalAs(UnmanagedType.LPWStr)] public string permissionSetID;
};
internal enum AssemblyRequestEntryFieldId
{
AssemblyRequest_permissionSetID,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("2474ECB4-8EFD-4410-9F31-B3E7C4A07731")]
internal interface IAssemblyRequestEntry
{
AssemblyRequestEntry AllData { [SecurityCritical]get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string permissionSetID { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [AssemblyRequest]
//++! start object [DescriptionMetadata]
[StructLayout(LayoutKind.Sequential)]
internal class DescriptionMetadataEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Publisher;
[MarshalAs(UnmanagedType.LPWStr)] public string Product;
[MarshalAs(UnmanagedType.LPWStr)] public string SupportUrl;
[MarshalAs(UnmanagedType.LPWStr)] public string IconFile;
[MarshalAs(UnmanagedType.LPWStr)] public string ErrorReportUrl;
[MarshalAs(UnmanagedType.LPWStr)] public string SuiteName;
};
internal enum DescriptionMetadataEntryFieldId
{
DescriptionMetadata_Publisher,
DescriptionMetadata_Product,
DescriptionMetadata_SupportUrl,
DescriptionMetadata_IconFile,
DescriptionMetadata_ErrorReportUrl,
DescriptionMetadata_SuiteName,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CB73147E-5FC2-4c31-B4E6-58D13DBE1A08")]
internal interface IDescriptionMetadataEntry
{
DescriptionMetadataEntry AllData { [SecurityCritical]get; }
string Publisher { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Product { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string SupportUrl { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string IconFile { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string ErrorReportUrl { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string SuiteName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [DescriptionMetadata]
//++! start object [DeploymentMetadata]
[StructLayout(LayoutKind.Sequential)]
internal class DeploymentMetadataEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string DeploymentProviderCodebase;
[MarshalAs(UnmanagedType.LPWStr)] public string MinimumRequiredVersion;
public ushort MaximumAge;
public byte MaximumAge_Unit;
public uint DeploymentFlags;
};
internal enum DeploymentMetadataEntryFieldId
{
DeploymentMetadata_DeploymentProviderCodebase,
DeploymentMetadata_MinimumRequiredVersion,
DeploymentMetadata_MaximumAge,
DeploymentMetadata_MaximumAge_Unit,
DeploymentMetadata_DeploymentFlags,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CFA3F59F-334D-46bf-A5A5-5D11BB2D7EBC")]
internal interface IDeploymentMetadataEntry
{
DeploymentMetadataEntry AllData { [SecurityCritical]get; }
string DeploymentProviderCodebase { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string MinimumRequiredVersion { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
ushort MaximumAge { [SecurityCritical]get; }
byte MaximumAge_Unit { [SecurityCritical]get; }
uint DeploymentFlags { [SecurityCritical]get; }
};
//++! end object [DeploymentMetadata]
//++! start object [DependentOSMetadata]
[StructLayout(LayoutKind.Sequential)]
internal class DependentOSMetadataEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string SupportUrl;
[MarshalAs(UnmanagedType.LPWStr)] public string Description;
public ushort MajorVersion;
public ushort MinorVersion;
public ushort BuildNumber;
public byte ServicePackMajor;
public byte ServicePackMinor;
};
internal enum DependentOSMetadataEntryFieldId
{
DependentOSMetadata_SupportUrl,
DependentOSMetadata_Description,
DependentOSMetadata_MajorVersion,
DependentOSMetadata_MinorVersion,
DependentOSMetadata_BuildNumber,
DependentOSMetadata_ServicePackMajor,
DependentOSMetadata_ServicePackMinor,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CF168CF4-4E8F-4d92-9D2A-60E5CA21CF85")]
internal interface IDependentOSMetadataEntry
{
DependentOSMetadataEntry AllData { [SecurityCritical]get; }
string SupportUrl { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Description { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
ushort MajorVersion { [SecurityCritical]get; }
ushort MinorVersion { [SecurityCritical]get; }
ushort BuildNumber { [SecurityCritical]get; }
byte ServicePackMajor { [SecurityCritical]get; }
byte ServicePackMinor { [SecurityCritical]get; }
};
//++! end object [DependentOSMetadata]
//++! start object [CompatibleFrameworksMetadata]
[StructLayout(LayoutKind.Sequential)]
internal class CompatibleFrameworksMetadataEntry
{
[MarshalAs(UnmanagedType.LPWStr)]
public string SupportUrl;
};
internal enum CompatibleFrameworksMetadataEntryFieldId
{
CompatibleFrameworksMetadata_SupportUrl,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("4A33D662-2210-463A-BE9F-FBDF1AA554E3")]
internal interface ICompatibleFrameworksMetadataEntry
{
CompatibleFrameworksMetadataEntry AllData { [SecurityCritical]get; }
string SupportUrl { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [CompatibleFrameworksMetadata]
//++! start object [MetadataSection]
[StructLayout(LayoutKind.Sequential)]
internal class MetadataSectionEntry : IDisposable
{
public uint SchemaVersion;
public uint ManifestFlags;
public uint UsagePatterns;
public IDefinitionIdentity CdfIdentity;
[MarshalAs(UnmanagedType.LPWStr)] public string LocalPath;
public uint HashAlgorithm;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr ManifestHash;
public uint ManifestHashSize;
[MarshalAs(UnmanagedType.LPWStr)] public string ContentType;
[MarshalAs(UnmanagedType.LPWStr)] public string RuntimeImageVersion;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr MvidValue;
public uint MvidValueSize;
public DescriptionMetadataEntry DescriptionData;
public DeploymentMetadataEntry DeploymentData;
public DependentOSMetadataEntry DependentOSData;
[MarshalAs(UnmanagedType.LPWStr)] public string defaultPermissionSetID;
[MarshalAs(UnmanagedType.LPWStr)] public string RequestedExecutionLevel;
public bool RequestedExecutionLevelUIAccess;
public IReferenceIdentity ResourceTypeResourcesDependency;
public IReferenceIdentity ResourceTypeManifestResourcesDependency;
[MarshalAs(UnmanagedType.LPWStr)] public string KeyInfoElement;
public CompatibleFrameworksMetadataEntry CompatibleFrameworksData;
~MetadataSectionEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose(bool fDisposing)
{
if (ManifestHash != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(ManifestHash);
ManifestHash = IntPtr.Zero;
}
if (MvidValue != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(MvidValue);
MvidValue = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum MetadataSectionEntryFieldId
{
MetadataSection_SchemaVersion,
MetadataSection_ManifestFlags,
MetadataSection_UsagePatterns,
MetadataSection_CdfIdentity,
MetadataSection_LocalPath,
MetadataSection_HashAlgorithm,
MetadataSection_ManifestHash,
MetadataSection_ManifestHashSize,
MetadataSection_ContentType,
MetadataSection_RuntimeImageVersion,
MetadataSection_MvidValue,
MetadataSection_MvidValueSize,
MetadataSection_DescriptionData,
MetadataSection_DeploymentData,
MetadataSection_DependentOSData,
MetadataSection_defaultPermissionSetID,
MetadataSection_RequestedExecutionLevel,
MetadataSection_RequestedExecutionLevelUIAccess,
MetadataSection_ResourceTypeResourcesDependency,
MetadataSection_ResourceTypeManifestResourcesDependency,
MetadataSection_KeyInfoElement,
MetadataSection_CompatibleFrameworksData,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("AB1ED79F-943E-407d-A80B-0744E3A95B28")]
internal interface IMetadataSectionEntry
{
MetadataSectionEntry AllData { [SecurityCritical]get; }
uint SchemaVersion { [SecurityCritical]get; }
uint ManifestFlags { [SecurityCritical]get; }
uint UsagePatterns { [SecurityCritical]get; }
IDefinitionIdentity CdfIdentity { [SecurityCritical]get; }
string LocalPath { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint HashAlgorithm { [SecurityCritical]get; }
object ManifestHash { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
string ContentType { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string RuntimeImageVersion { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
object MvidValue { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
IDescriptionMetadataEntry DescriptionData { [SecurityCritical]get; }
IDeploymentMetadataEntry DeploymentData { [SecurityCritical]get; }
IDependentOSMetadataEntry DependentOSData { [SecurityCritical]get; }
string defaultPermissionSetID { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string RequestedExecutionLevel { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
bool RequestedExecutionLevelUIAccess { [SecurityCritical]get; }
IReferenceIdentity ResourceTypeResourcesDependency { [SecurityCritical]get; }
IReferenceIdentity ResourceTypeManifestResourcesDependency { [SecurityCritical]get; }
string KeyInfoElement { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
ICompatibleFrameworksMetadataEntry CompatibleFrameworksData { [SecurityCritical]get; }
};
//++! end object [MetadataSection]
//++! start object [Event]
#if !ISOLATION_IN_MSCORLIB
[StructLayout(LayoutKind.Sequential)]
internal class EventEntry
{
public uint EventID;
public uint Level;
public uint Version;
public Guid Guid;
[MarshalAs(UnmanagedType.LPWStr)] public string SubTypeName;
public uint SubTypeValue;
[MarshalAs(UnmanagedType.LPWStr)] public string DisplayName;
public uint EventNameMicrodomIndex;
};
internal enum EventEntryFieldId
{
Event_Level,
Event_Version,
Event_Guid,
Event_SubTypeName,
Event_SubTypeValue,
Event_DisplayName,
Event_EventNameMicrodomIndex,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("8AD3FC86-AFD3-477a-8FD5-146C291195BB")]
internal interface IEventEntry
{
EventEntry AllData { [SecurityCritical]get; }
uint EventID { [SecurityCritical]get; }
uint Level { [SecurityCritical]get; }
uint Version { [SecurityCritical]get; }
Guid Guid { [SecurityCritical]get; }
string SubTypeName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint SubTypeValue { [SecurityCritical]get; }
string DisplayName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint EventNameMicrodomIndex { [SecurityCritical]get; }
};
//++! end object [Event]
//++! start object [EventMap]
[StructLayout(LayoutKind.Sequential)]
internal class EventMapEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string MapName;
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
public uint Value;
public bool IsValueMap;
};
internal enum EventMapEntryFieldId
{
EventMap_Name,
EventMap_Value,
EventMap_IsValueMap,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("8AD3FC86-AFD3-477a-8FD5-146C291195BC")]
internal interface IEventMapEntry
{
EventMapEntry AllData { [SecurityCritical]get; }
string MapName { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint Value { [SecurityCritical]get; }
bool IsValueMap { [SecurityCritical]get; }
};
//++! end object [EventMap]
//++! start object [EventTag]
[StructLayout(LayoutKind.Sequential)]
internal class EventTagEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string TagData;
public uint EventID;
};
internal enum EventTagEntryFieldId
{
EventTag_EventID,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("8AD3FC86-AFD3-477a-8FD5-146C291195BD")]
internal interface IEventTagEntry
{
EventTagEntry AllData { [SecurityCritical]get; }
string TagData { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint EventID { [SecurityCritical]get; }
};
//++! end object [EventTag]
//++! start object [RegistryValue]
[StructLayout(LayoutKind.Sequential)]
internal class RegistryValueEntry
{
public uint Flags;
public uint OperationHint;
public uint Type;
[MarshalAs(UnmanagedType.LPWStr)] public string Value;
[MarshalAs(UnmanagedType.LPWStr)] public string BuildFilter;
};
internal enum RegistryValueEntryFieldId
{
RegistryValue_Flags,
RegistryValue_OperationHint,
RegistryValue_Type,
RegistryValue_Value,
RegistryValue_BuildFilter,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("49e1fe8d-ebb8-4593-8c4e-3e14c845b142")]
internal interface IRegistryValueEntry
{
RegistryValueEntry AllData { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
uint OperationHint { [SecurityCritical]get; }
uint Type { [SecurityCritical]get; }
string Value { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string BuildFilter { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [RegistryValue]
//++! start object [RegistryKey]
[StructLayout(LayoutKind.Sequential)]
internal class RegistryKeyEntry : IDisposable
{
public uint Flags;
public uint Protection;
[MarshalAs(UnmanagedType.LPWStr)] public string BuildFilter;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr SecurityDescriptor;
public uint SecurityDescriptorSize;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr Values;
public uint ValuesSize;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr Keys;
public uint KeysSize;
~RegistryKeyEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[SecuritySafeCritical]
public void Dispose(bool fDisposing)
{
if (SecurityDescriptor != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(SecurityDescriptor);
SecurityDescriptor = IntPtr.Zero;
}
if (Values != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(Values);
Values = IntPtr.Zero;
}
if (Keys != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(Keys);
Keys = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum RegistryKeyEntryFieldId
{
RegistryKey_Flags,
RegistryKey_Protection,
RegistryKey_BuildFilter,
RegistryKey_SecurityDescriptor,
RegistryKey_SecurityDescriptorSize,
RegistryKey_Values,
RegistryKey_ValuesSize,
RegistryKey_Keys,
RegistryKey_KeysSize,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("186685d1-6673-48c3-bc83-95859bb591df")]
internal interface IRegistryKeyEntry
{
RegistryKeyEntry AllData { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
uint Protection { [SecurityCritical]get; }
string BuildFilter { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
object SecurityDescriptor { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
object Values { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
object Keys { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
};
//++! end object [RegistryKey]
//++! start object [Directory]
[StructLayout(LayoutKind.Sequential)]
internal class DirectoryEntry : IDisposable
{
public uint Flags;
public uint Protection;
[MarshalAs(UnmanagedType.LPWStr)] public string BuildFilter;
[MarshalAs(UnmanagedType.SysInt)] public IntPtr SecurityDescriptor;
public uint SecurityDescriptorSize;
~DirectoryEntry()
{
Dispose(false);
}
void IDisposable.Dispose() { this.Dispose(true); }
[SecuritySafeCritical]
public void Dispose(bool fDisposing)
{
if (SecurityDescriptor != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(SecurityDescriptor);
SecurityDescriptor = IntPtr.Zero;
}
if (fDisposing)
System.GC.SuppressFinalize(this);
}
};
internal enum DirectoryEntryFieldId
{
Directory_Flags,
Directory_Protection,
Directory_BuildFilter,
Directory_SecurityDescriptor,
Directory_SecurityDescriptorSize,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("9f27c750-7dfb-46a1-a673-52e53e2337a9")]
internal interface IDirectoryEntry
{
DirectoryEntry AllData { [SecurityCritical]get; }
uint Flags { [SecurityCritical]get; }
uint Protection { [SecurityCritical]get; }
string BuildFilter { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
object SecurityDescriptor { [SecurityCritical][return: MarshalAs(UnmanagedType.Interface)] get; }
};
//++! end object [Directory]
//++! start object [SecurityDescriptorReference]
[StructLayout(LayoutKind.Sequential)]
internal class SecurityDescriptorReferenceEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
[MarshalAs(UnmanagedType.LPWStr)] public string BuildFilter;
};
internal enum SecurityDescriptorReferenceEntryFieldId
{
SecurityDescriptorReference_Name,
SecurityDescriptorReference_BuildFilter,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("a75b74e9-2c00-4ebb-b3f9-62a670aaa07e")]
internal interface ISecurityDescriptorReferenceEntry
{
SecurityDescriptorReferenceEntry AllData { [SecurityCritical]get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string BuildFilter { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [SecurityDescriptorReference]
//++! start object [CounterSet]
[StructLayout(LayoutKind.Sequential)]
internal class CounterSetEntry
{
public Guid CounterSetGuid;
public Guid ProviderGuid;
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
[MarshalAs(UnmanagedType.LPWStr)] public string Description;
public bool InstanceType;
};
internal enum CounterSetEntryFieldId
{
CounterSet_ProviderGuid,
CounterSet_Name,
CounterSet_Description,
CounterSet_InstanceType,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("8CD3FC85-AFD3-477a-8FD5-146C291195BB")]
internal interface ICounterSetEntry
{
CounterSetEntry AllData { [SecurityCritical]get; }
Guid CounterSetGuid { [SecurityCritical]get; }
Guid ProviderGuid { [SecurityCritical]get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Description { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
bool InstanceType { [SecurityCritical]get; }
};
//++! end object [CounterSet]
//++! start object [Counter]
[StructLayout(LayoutKind.Sequential)]
internal class CounterEntry
{
public Guid CounterSetGuid;
public uint CounterId;
[MarshalAs(UnmanagedType.LPWStr)] public string Name;
[MarshalAs(UnmanagedType.LPWStr)] public string Description;
public uint CounterType;
public ulong Attributes;
public uint BaseId;
public uint DefaultScale;
};
internal enum CounterEntryFieldId
{
Counter_CounterId,
Counter_Name,
Counter_Description,
Counter_CounterType,
Counter_Attributes,
Counter_BaseId,
Counter_DefaultScale,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("8CD3FC86-AFD3-477a-8FD5-146C291195BB")]
internal interface ICounterEntry
{
CounterEntry AllData { [SecurityCritical]get; }
Guid CounterSetGuid { [SecurityCritical]get; }
uint CounterId { [SecurityCritical]get; }
string Name { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Description { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
uint CounterType { [SecurityCritical]get; }
ulong Attributes { [SecurityCritical]get; }
uint BaseId { [SecurityCritical]get; }
uint DefaultScale { [SecurityCritical] get; }
};
//++! end object [Counter]
//++! start object [CompatibleFramework]
[StructLayout(LayoutKind.Sequential)]
internal class CompatibleFrameworkEntry
{
public uint index;
[MarshalAs(UnmanagedType.LPWStr)] public string TargetVersion;
[MarshalAs(UnmanagedType.LPWStr)] public string Profile;
[MarshalAs(UnmanagedType.LPWStr)] public string SupportedRuntime;
};
internal enum CompatibleFrameworkEntryFieldId
{
CompatibleFramework_TargetVersion,
CompatibleFramework_Profile,
CompatibleFramework_SupportedRuntime,
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("C98BFE2A-62C9-40AD-ADCE-A9037BE2BE6C")]
internal interface ICompatibleFrameworkEntry
{
CompatibleFrameworkEntry AllData { [SecurityCritical]get; }
uint index{ [SecurityCritical]get; }
string TargetVersion { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
string Profile { [SecurityCritical][return:MarshalAs(UnmanagedType.LPWStr)] get; }
string SupportedRuntime { [SecurityCritical][return: MarshalAs(UnmanagedType.LPWStr)] get; }
};
//++! end object [CompatibleFramework]
#endif
#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.
using Microsoft.Win32.SafeHandles;
using System;
using System.Configuration.Assemblies;
using System.Diagnostics.Eventing;
using System.Diagnostics.Eventing.Reader;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading;
namespace Microsoft.Win32
{
internal static partial class UnsafeNativeMethods
{
internal const String WEVTAPI = "wevtapi.dll";
// WinError.h codes:
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
// Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_LOCK_VIOLATION = 0x21; // 33
internal const int ERROR_HANDLE_EOF = 0x26; // 38
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57; // 87
internal const int ERROR_BROKEN_PIPE = 0x6D; // 109
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long
internal const int ERROR_PIPE_BUSY = 0xE7; // 231
internal const int ERROR_NO_DATA = 0xE8; // 232
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259
internal const int ERROR_PIPE_CONNECTED = 0x217; // 535
internal const int ERROR_PIPE_LISTENING = 0x218; // 536
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_IO_PENDING = 0x3E5; // 997
internal const int ERROR_NOT_FOUND = 0x490; // 1168
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534
internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815
// Event log specific codes:
internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;
internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029;
internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030;
internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031;
internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033;
internal const int ERROR_MUI_FILE_NOT_FOUND = 15100;
internal enum EvtQueryFlags
{
EvtQueryChannelPath = 0x1,
EvtQueryFilePath = 0x2,
EvtQueryForwardDirection = 0x100,
EvtQueryReverseDirection = 0x200,
EvtQueryTolerateQueryErrors = 0x1000
}
[Flags]
internal enum EvtSubscribeFlags
{
EvtSubscribeToFutureEvents = 1,
EvtSubscribeStartAtOldestRecord = 2,
EvtSubscribeStartAfterBookmark = 3,
EvtSubscribeTolerateQueryErrors = 0x1000,
EvtSubscribeStrict = 0x10000
}
/// <summary>
/// Evt Variant types
/// </summary>
internal enum EvtVariantType
{
EvtVarTypeNull = 0,
EvtVarTypeString = 1,
EvtVarTypeAnsiString = 2,
EvtVarTypeSByte = 3,
EvtVarTypeByte = 4,
EvtVarTypeInt16 = 5,
EvtVarTypeUInt16 = 6,
EvtVarTypeInt32 = 7,
EvtVarTypeUInt32 = 8,
EvtVarTypeInt64 = 9,
EvtVarTypeUInt64 = 10,
EvtVarTypeSingle = 11,
EvtVarTypeDouble = 12,
EvtVarTypeBoolean = 13,
EvtVarTypeBinary = 14,
EvtVarTypeGuid = 15,
EvtVarTypeSizeT = 16,
EvtVarTypeFileTime = 17,
EvtVarTypeSysTime = 18,
EvtVarTypeSid = 19,
EvtVarTypeHexInt32 = 20,
EvtVarTypeHexInt64 = 21,
// these types used internally
EvtVarTypeEvtHandle = 32,
EvtVarTypeEvtXml = 35,
// Array = 128
EvtVarTypeStringArray = 129,
EvtVarTypeUInt32Array = 136
}
internal enum EvtMasks
{
EVT_VARIANT_TYPE_MASK = 0x7f,
EVT_VARIANT_TYPE_ARRAY = 128
}
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
public short Month;
[MarshalAs(UnmanagedType.U2)]
public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short Day;
[MarshalAs(UnmanagedType.U2)]
public short Hour;
[MarshalAs(UnmanagedType.U2)]
public short Minute;
[MarshalAs(UnmanagedType.U2)]
public short Second;
[MarshalAs(UnmanagedType.U2)]
public short Milliseconds;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
#pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal struct EvtVariant
{
[FieldOffset(0)]
public UInt32 UInteger;
[FieldOffset(0)]
public Int32 Integer;
[FieldOffset(0)]
public byte UInt8;
[FieldOffset(0)]
public short Short;
[FieldOffset(0)]
public ushort UShort;
[FieldOffset(0)]
public UInt32 Bool;
[FieldOffset(0)]
public Byte ByteVal;
[FieldOffset(0)]
public byte SByte;
[FieldOffset(0)]
public UInt64 ULong;
[FieldOffset(0)]
public Int64 Long;
[FieldOffset(0)]
public Single Single;
[FieldOffset(0)]
public Double Double;
[FieldOffset(0)]
public IntPtr StringVal;
[FieldOffset(0)]
public IntPtr AnsiString;
[FieldOffset(0)]
public IntPtr SidVal;
[FieldOffset(0)]
public IntPtr Binary;
[FieldOffset(0)]
public IntPtr Reference;
[FieldOffset(0)]
public IntPtr Handle;
[FieldOffset(0)]
public IntPtr GuidReference;
[FieldOffset(0)]
public UInt64 FileTime;
[FieldOffset(0)]
public IntPtr SystemTime;
[FieldOffset(0)]
public IntPtr SizeT;
[FieldOffset(8)]
public UInt32 Count; // number of elements (not length) in bytes.
[FieldOffset(12)]
public UInt32 Type;
}
internal enum EvtEventPropertyId
{
EvtEventQueryIDs = 0,
EvtEventPath = 1
}
/// <summary>
/// The query flags to get information about query
/// </summary>
internal enum EvtQueryPropertyId
{
EvtQueryNames = 0, //String; //Variant will be array of EvtVarTypeString
EvtQueryStatuses = 1 //UInt32; //Variant will be Array of EvtVarTypeUInt32
}
/// <summary>
/// Publisher Metadata properties
/// </summary>
internal enum EvtPublisherMetadataPropertyId
{
EvtPublisherMetadataPublisherGuid = 0, // EvtVarTypeGuid
EvtPublisherMetadataResourceFilePath = 1, // EvtVarTypeString
EvtPublisherMetadataParameterFilePath = 2, // EvtVarTypeString
EvtPublisherMetadataMessageFilePath = 3, // EvtVarTypeString
EvtPublisherMetadataHelpLink = 4, // EvtVarTypeString
EvtPublisherMetadataPublisherMessageID = 5, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferences = 6, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataChannelReferencePath = 7, // EvtVarTypeString
EvtPublisherMetadataChannelReferenceIndex = 8, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceID = 9, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceFlags = 10, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceMessageID = 11, // EvtVarTypeUInt32
EvtPublisherMetadataLevels = 12, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataLevelName = 13, // EvtVarTypeString
EvtPublisherMetadataLevelValue = 14, // EvtVarTypeUInt32
EvtPublisherMetadataLevelMessageID = 15, // EvtVarTypeUInt32
EvtPublisherMetadataTasks = 16, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataTaskName = 17, // EvtVarTypeString
EvtPublisherMetadataTaskEventGuid = 18, // EvtVarTypeGuid
EvtPublisherMetadataTaskValue = 19, // EvtVarTypeUInt32
EvtPublisherMetadataTaskMessageID = 20, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodes = 21, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataOpcodeName = 22, // EvtVarTypeString
EvtPublisherMetadataOpcodeValue = 23, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodeMessageID = 24, // EvtVarTypeUInt32
EvtPublisherMetadataKeywords = 25, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataKeywordName = 26, // EvtVarTypeString
EvtPublisherMetadataKeywordValue = 27, // EvtVarTypeUInt64
EvtPublisherMetadataKeywordMessageID = 28//, // EvtVarTypeUInt32
// EvtPublisherMetadataPropertyIdEND
}
internal enum EvtChannelReferenceFlags
{
EvtChannelReferenceImported = 1
}
internal enum EvtEventMetadataPropertyId
{
EventMetadataEventID, // EvtVarTypeUInt32
EventMetadataEventVersion, // EvtVarTypeUInt32
EventMetadataEventChannel, // EvtVarTypeUInt32
EventMetadataEventLevel, // EvtVarTypeUInt32
EventMetadataEventOpcode, // EvtVarTypeUInt32
EventMetadataEventTask, // EvtVarTypeUInt32
EventMetadataEventKeyword, // EvtVarTypeUInt64
EventMetadataEventMessageID,// EvtVarTypeUInt32
EventMetadataEventTemplate // EvtVarTypeString
// EvtEventMetadataPropertyIdEND
}
// CHANNEL CONFIGURATION
internal enum EvtChannelConfigPropertyId
{
EvtChannelConfigEnabled = 0, // EvtVarTypeBoolean
EvtChannelConfigIsolation, // EvtVarTypeUInt32, EVT_CHANNEL_ISOLATION_TYPE
EvtChannelConfigType, // EvtVarTypeUInt32, EVT_CHANNEL_TYPE
EvtChannelConfigOwningPublisher, // EvtVarTypeString
EvtChannelConfigClassicEventlog, // EvtVarTypeBoolean
EvtChannelConfigAccess, // EvtVarTypeString
EvtChannelLoggingConfigRetention, // EvtVarTypeBoolean
EvtChannelLoggingConfigAutoBackup, // EvtVarTypeBoolean
EvtChannelLoggingConfigMaxSize, // EvtVarTypeUInt64
EvtChannelLoggingConfigLogFilePath, // EvtVarTypeString
EvtChannelPublishingConfigLevel, // EvtVarTypeUInt32
EvtChannelPublishingConfigKeywords, // EvtVarTypeUInt64
EvtChannelPublishingConfigControlGuid, // EvtVarTypeGuid
EvtChannelPublishingConfigBufferSize, // EvtVarTypeUInt32
EvtChannelPublishingConfigMinBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigMaxBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigLatency, // EvtVarTypeUInt32
EvtChannelPublishingConfigClockType, // EvtVarTypeUInt32, EVT_CHANNEL_CLOCK_TYPE
EvtChannelPublishingConfigSidType, // EvtVarTypeUInt32, EVT_CHANNEL_SID_TYPE
EvtChannelPublisherList, // EvtVarTypeString | EVT_VARIANT_TYPE_ARRAY
EvtChannelConfigPropertyIdEND
}
// LOG INFORMATION
internal enum EvtLogPropertyId
{
EvtLogCreationTime = 0, // EvtVarTypeFileTime
EvtLogLastAccessTime, // EvtVarTypeFileTime
EvtLogLastWriteTime, // EvtVarTypeFileTime
EvtLogFileSize, // EvtVarTypeUInt64
EvtLogAttributes, // EvtVarTypeUInt32
EvtLogNumberOfLogRecords, // EvtVarTypeUInt64
EvtLogOldestRecordNumber, // EvtVarTypeUInt64
EvtLogFull, // EvtVarTypeBoolean
}
internal enum EvtExportLogFlags
{
EvtExportLogChannelPath = 1,
EvtExportLogFilePath = 2,
EvtExportLogTolerateQueryErrors = 0x1000
}
// RENDERING
internal enum EvtRenderContextFlags
{
EvtRenderContextValues = 0, // Render specific properties
EvtRenderContextSystem = 1, // Render all system properties (System)
EvtRenderContextUser = 2 // Render all user properties (User/EventData)
}
internal enum EvtRenderFlags
{
EvtRenderEventValues = 0, // Variants
EvtRenderEventXml = 1, // XML
EvtRenderBookmark = 2 // Bookmark
}
internal enum EvtFormatMessageFlags
{
EvtFormatMessageEvent = 1,
EvtFormatMessageLevel = 2,
EvtFormatMessageTask = 3,
EvtFormatMessageOpcode = 4,
EvtFormatMessageKeyword = 5,
EvtFormatMessageChannel = 6,
EvtFormatMessageProvider = 7,
EvtFormatMessageId = 8,
EvtFormatMessageXml = 9
}
internal enum EvtSystemPropertyId
{
EvtSystemProviderName = 0, // EvtVarTypeString
EvtSystemProviderGuid, // EvtVarTypeGuid
EvtSystemEventID, // EvtVarTypeUInt16
EvtSystemQualifiers, // EvtVarTypeUInt16
EvtSystemLevel, // EvtVarTypeUInt8
EvtSystemTask, // EvtVarTypeUInt16
EvtSystemOpcode, // EvtVarTypeUInt8
EvtSystemKeywords, // EvtVarTypeHexInt64
EvtSystemTimeCreated, // EvtVarTypeFileTime
EvtSystemEventRecordId, // EvtVarTypeUInt64
EvtSystemActivityID, // EvtVarTypeGuid
EvtSystemRelatedActivityID, // EvtVarTypeGuid
EvtSystemProcessID, // EvtVarTypeUInt32
EvtSystemThreadID, // EvtVarTypeUInt32
EvtSystemChannel, // EvtVarTypeString
EvtSystemComputer, // EvtVarTypeString
EvtSystemUserID, // EvtVarTypeSid
EvtSystemVersion, // EvtVarTypeUInt8
EvtSystemPropertyIdEND
}
// SESSION
internal enum EvtLoginClass
{
EvtRpcLogin = 1
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct EvtRpcLogin
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Server;
[MarshalAs(UnmanagedType.LPWStr)]
public string User;
[MarshalAs(UnmanagedType.LPWStr)]
public string Domain;
public CoTaskMemUnicodeSafeHandle Password;
public int Flags;
}
// SEEK
[Flags]
internal enum EvtSeekFlags
{
EvtSeekRelativeToFirst = 1,
EvtSeekRelativeToLast = 2,
EvtSeekRelativeToCurrent = 3,
EvtSeekRelativeToBookmark = 4,
EvtSeekOriginMask = 7,
EvtSeekStrict = 0x10000
}
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern EventLogHandle EvtQuery(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string path,
[MarshalAs(UnmanagedType.LPWStr)]string query,
int flags);
// SEEK
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtSeek(
EventLogHandle resultSet,
long position,
EventLogHandle bookmark,
int timeout,
[MarshalAs(UnmanagedType.I4)]EvtSeekFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern EventLogHandle EvtSubscribe(
EventLogHandle session,
SafeWaitHandle signalEvent,
[MarshalAs(UnmanagedType.LPWStr)]string path,
[MarshalAs(UnmanagedType.LPWStr)]string query,
EventLogHandle bookmark,
IntPtr context,
IntPtr callback,
int flags);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern bool EvtNext(
EventLogHandle queryHandle,
int eventSize,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] events,
int timeout,
int flags,
ref int returned);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern bool EvtCancel(EventLogHandle handle);
[DllImport(WEVTAPI)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool EvtClose(IntPtr handle);
/*
[DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)]
public static extern bool EvtClose(
IntPtr eventHandle
);
*/
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetEventInfo(
EventLogHandle eventHandle,
// int propertyId
[MarshalAs(UnmanagedType.I4)]EvtEventPropertyId propertyId,
int bufferSize,
IntPtr bufferPtr,
out int bufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetQueryInfo(
EventLogHandle queryHandle,
[MarshalAs(UnmanagedType.I4)]EvtQueryPropertyId propertyId,
int bufferSize,
IntPtr buffer,
ref int bufferRequired
);
// PUBLISHER METADATA
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenPublisherMetadata(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string publisherId,
[MarshalAs(UnmanagedType.LPWStr)] string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetPublisherMetadataProperty(
EventLogHandle publisherMetadataHandle,
[MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId,
int flags,
int publisherMetadataPropertyBufferSize,
IntPtr publisherMetadataPropertyBuffer,
out int publisherMetadataPropertyBufferUsed
);
// NEW
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetObjectArraySize(
EventLogHandle objectArray,
out int objectArraySize
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetObjectArrayProperty(
EventLogHandle objectArray,
int propertyId,
int arrayIndex,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
// NEW 2
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenEventMetadataEnum(
EventLogHandle publisherMetadata,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
// public static extern IntPtr EvtNextEventMetadata(
internal static extern EventLogHandle EvtNextEventMetadata(
EventLogHandle eventMetadataEnum,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetEventMetadataProperty(
EventLogHandle eventMetadata,
[MarshalAs(UnmanagedType.I4)] EvtEventMetadataPropertyId propertyId,
int flags,
int eventMetadataPropertyBufferSize,
IntPtr eventMetadataPropertyBuffer,
out int eventMetadataPropertyBufferUsed
);
// Channel Configuration Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenChannelEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtNextChannelPath(
EventLogHandle channelEnum,
int channelPathBufferSize,
// StringBuilder channelPathBuffer,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder channelPathBuffer,
out int channelPathBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenPublisherEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtNextPublisherId(
EventLogHandle publisherEnum,
int publisherIdBufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder publisherIdBuffer,
out int publisherIdBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenChannelConfig(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]String channelPath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtSaveChannelConfig(
EventLogHandle channelConfig,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtSetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
int flags,
ref EvtVariant propertyValue
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
// Log Information Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string path,
[MarshalAs(UnmanagedType.I4)]PathType flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtGetLogInfo(
EventLogHandle log,
[MarshalAs(UnmanagedType.I4)]EvtLogPropertyId propertyId,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
// LOG MANIPULATION
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtExportLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string channelPath,
[MarshalAs(UnmanagedType.LPWStr)]string query,
[MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtArchiveExportedLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtClearLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string channelPath,
[MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
int flags
);
// RENDERING
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtCreateRenderContext(
Int32 valuePathsCount,
[MarshalAs(UnmanagedType.LPArray,ArraySubType = UnmanagedType.LPWStr)]
String[] valuePaths,
[MarshalAs(UnmanagedType.I4)]EvtRenderContextFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
out int buffUsed,
out int propCount
);
[DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
IntPtr buffer,
out int buffUsed,
out int propCount
);
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
internal struct EvtStringVariant
{
[MarshalAs(UnmanagedType.LPWStr), FieldOffset(0)]
public string StringVal;
[FieldOffset(8)]
public UInt32 Count;
[FieldOffset(12)]
public UInt32 Type;
};
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtFormatMessage(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
EvtStringVariant[] values,
[MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
int bufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
out int bufferUsed
);
[DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtFormatMessageBuffer(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
IntPtr values,
[MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
int bufferSize,
IntPtr buffer,
out int bufferUsed
);
// SESSION
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtOpenSession(
[MarshalAs(UnmanagedType.I4)]EvtLoginClass loginClass,
ref EvtRpcLogin login,
int timeout,
int flags
);
// BOOKMARK
[DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern EventLogHandle EvtCreateBookmark(
[MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EvtUpdateBookmark(
EventLogHandle bookmark,
EventLogHandle eventHandle
);
//
// EventLog
//
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F11_City_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="F11_City_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="F10_City"/> collection.
/// </remarks>
[Serializable]
public partial class F11_City_ReChild : BusinessBase<F11_City_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int city_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F11_City_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F11_City_ReChild"/> object.</returns>
internal static F11_City_ReChild NewF11_City_ReChild()
{
return DataPortal.CreateChild<F11_City_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="F11_City_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F11_City_ReChild"/> object.</returns>
internal static F11_City_ReChild GetF11_City_ReChild(SafeDataReader dr)
{
F11_City_ReChild obj = new F11_City_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F11_City_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F11_City_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F11_City_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F11_City_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name"));
// parent properties
city_ID2 = dr.GetInt32("City_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="F11_City_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F10_City parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IF11_City_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.City_ID,
City_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F11_City_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(F10_City parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IF11_City_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.City_ID,
City_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="F11_City_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(F10_City parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IF11_City_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.City_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <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
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateImageCreateOrUpdateDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pImageName = new RuntimeDefinedParameter();
pImageName.Name = "ImageName";
pImageName.ParameterType = typeof(string);
pImageName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pImageName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ImageName", pImageName);
var pParameters = new RuntimeDefinedParameter();
pParameters.Name = "Image";
pParameters.ParameterType = typeof(Image);
pParameters.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true
});
pParameters.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Image", pParameters);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 4,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteImageCreateOrUpdateMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string imageName = (string)ParseParameter(invokeMethodInputParameters[1]);
Image parameters = (Image)ParseParameter(invokeMethodInputParameters[2]);
var result = ImagesClient.CreateOrUpdate(resourceGroupName, imageName, parameters);
WriteObject(result);
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateImageCreateOrUpdateParameters()
{
string resourceGroupName = string.Empty;
string imageName = string.Empty;
Image parameters = new Image();
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "ImageName", "Parameters" },
new object[] { resourceGroupName, imageName, parameters });
}
}
[Cmdlet(VerbsCommon.New, "AzureRmImage", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSImage))]
public partial class NewAzureRmImage : ComputeAutomationBaseCmdlet
{
protected override void ProcessRecord()
{
AutoMapper.Mapper.AddProfile<ComputeAutomationAutoMapperProfile>();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.ResourceGroupName, VerbsCommon.New))
{
string resourceGroupName = this.ResourceGroupName;
string imageName = this.ImageName;
Image parameters = new Image();
Mapper.Map<PSImage, Image>(this.Image, parameters);
var result = ImagesClient.CreateOrUpdate(resourceGroupName, imageName, parameters);
var psObject = new PSImage();
Mapper.Map<Image, PSImage>(result, psObject);
WriteObject(psObject);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Alias("Name")]
[AllowNull]
public string ImageName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 3,
Mandatory = true,
ValueFromPipelineByPropertyName = false,
ValueFromPipeline = true)]
[AllowNull]
public PSImage Image { get; set; }
}
[Cmdlet(VerbsData.Update, "AzureRmImage", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSImage))]
public partial class UpdateAzureRmImage : ComputeAutomationBaseCmdlet
{
protected override void ProcessRecord()
{
AutoMapper.Mapper.AddProfile<ComputeAutomationAutoMapperProfile>();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.ResourceGroupName, VerbsData.Update))
{
string resourceGroupName = this.ResourceGroupName;
string imageName = this.ImageName;
Image parameters = new Image();
Mapper.Map<PSImage, Image>(this.Image, parameters);
var result = ImagesClient.CreateOrUpdate(resourceGroupName, imageName, parameters);
var psObject = new PSImage();
Mapper.Map<Image, PSImage>(result, psObject);
WriteObject(psObject);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Alias("Name")]
[AllowNull]
public string ImageName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 3,
Mandatory = true,
ValueFromPipelineByPropertyName = false,
ValueFromPipeline = true)]
[AllowNull]
public PSImage Image { get; set; }
}
}
| |
/*
* Copyright (c) 2012 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* 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.Collections.Generic;
using System.IO;
using System.Text;
namespace CarrotInc.MiniJSON {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web.Caching;
using fyiReporting.RDL;
namespace fyiReporting.RdlAsp
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class RdlReport : Control
{
/// <summary>
/// RdlReport generates an HTML report from a RDL file.
/// </summary>
///
private const string STATISTICS="statistics";
private string _ReportFile=null;
private ArrayList _Errors=null;
private int _MaxSeverity=0;
private string _CSS=null;
private string _JavaScript=null;
private string _Html=null;
private string _Xml=null;
private string _Csv = null;
private byte[] _Object = null;
private string _ParameterHtml=null;
private OutputPresentationType _RenderType=OutputPresentationType.ASPHTML;
private string _PassPhrase = null;
private bool _NoShow;
protected override void Render(HtmlTextWriter tw)
{
if (_ReportFile == null)
{
this.AddError(8, "ReportFile not specified.");
return;
}
else if (_ReportFile == STATISTICS)
{
DoStatistics(tw);
return;
}
else if (_Html != null)
tw.Write(_Html);
else if (_Object != null)
{
// TODO - shouldn't use control to write out object???
throw new Exception("_Object needed in render");
}
else // we never generated anything!
{
if (_Errors != null)
{
tw.RenderBeginTag(HtmlTextWriterTag.Table);
tw.RenderBeginTag(HtmlTextWriterTag.Tr);
tw.RenderBeginTag(HtmlTextWriterTag.Td);
tw.Write("Errors");
tw.RenderEndTag();
tw.RenderEndTag();
foreach(string e in _Errors)
{
tw.RenderBeginTag(HtmlTextWriterTag.Tr);
tw.RenderBeginTag(HtmlTextWriterTag.Td);
tw.Write(e);
tw.RenderEndTag();
tw.RenderEndTag();
}
tw.RenderEndTag();
}
}
return;
}
/// <summary>
/// When true report won't be shown but parameters (if any) will be
/// </summary>
public bool NoShow
{
get { return _NoShow; }
set { _NoShow = value; }
}
public string RenderType
{
get
{
switch (_RenderType)
{
case OutputPresentationType.ASPHTML:
case OutputPresentationType.HTML:
return "html";
case OutputPresentationType.PDF:
return "pdf";
case OutputPresentationType.XML:
return "xml";
case OutputPresentationType.CSV:
return "csv";
case OutputPresentationType.Excel:
return "xlsx";
case OutputPresentationType.RTF:
return "rtf";
default:
return "html";
}
}
set
{
_RenderType = this.GetRenderType(value);
}
}
public string ReportFile
{
get {return _ReportFile;}
set
{
_ReportFile = value;
// Clear out old report information (if any)
this._Errors = null;
this._MaxSeverity = 0;
_CSS=null;
_JavaScript=null;
_Html=null;
_ParameterHtml=null;
if (_ReportFile == STATISTICS)
{
StringWriter sw=null;
HtmlTextWriter htw=null;
try
{
sw = new StringWriter();
htw = new HtmlTextWriter(sw);
DoStatistics(htw);
htw.Flush();
_Html = sw.ToString();
}
finally
{
if (htw != null)
{
htw.Close();
htw.Dispose();
}
if (sw != null)
{
sw.Close();
sw.Dispose();
}
}
return;
}
// Build the new report
string pfile = this.MapPathSecure(_ReportFile);
DoRender(pfile);
}
}
public string PassPhrase
{
set { _PassPhrase = value; }
}
private string GetPassword()
{
return _PassPhrase;
}
public string Html
{
get {return _Html;}
}
public string Xml
{
get {return _Xml;}
}
public string CSV
{
get { return _Csv; }
}
public byte[] Object
{
get {return _Object;}
}
public ArrayList Errors
{
get {return _Errors;}
}
public int MaxErrorSeverity
{
get {return _MaxSeverity;}
}
public string CSS
{
get {return _CSS;}
}
public string JavaScript
{
get {return _JavaScript;}
}
public string ParameterHtml
{
get
{
return _ParameterHtml;
}
}
// Render the report files with the requested types
private void DoRender(string file)
{
string source;
Report report=null;
NameValueCollection nvc;
nvc = this.Context.Request.QueryString; // parameters
ListDictionary ld = new ListDictionary();
try
{
for (int i=0; i < nvc.Count; i++)
{
ld.Add(nvc.GetKey(i), nvc[i]);
}
// if (!_NoShow) { report = GetCachedReport(file); }
report = ReportHelper.GetCachedReport(file, this.Context.Cache, this.Context.Application);
if (report == null) // couldn't obtain report definition from cache
{
// Obtain the source
source = ReportHelper.GetSource(file);
if (source == null)
return; // GetSource reported the error
// Compile the report
report = this.GetReport(source, file);
if (report == null)
return;
ReportHelper.SaveCachedReport(report, file, this.Context.Cache);
}
// Set the user context information: ID, language
ReportHelper.SetUserContext(report, this.Context, new RDL.NeedPassword(GetPassword));
// Obtain the data if report is being generated
if (!_NoShow)
{
report.RunGetData(ld);
Generate(report);
}
}
catch (Exception exe)
{
AddError(8, "Error: {0}", exe.Message);
}
if (_ParameterHtml == null)
_ParameterHtml = ReportHelper.GetParameterHtml(report, ld, this.Context, _ReportFile, _NoShow); // build the parameter html
}
private void AddError(int severity, string err, params object[] args)
{
if (_MaxSeverity < severity)
_MaxSeverity = severity;
string error = string.Format(err, args);
if (_Errors == null)
_Errors = new ArrayList();
_Errors.Add(error);
}
private void AddError(int severity, IList errors)
{
if (_MaxSeverity < severity)
_MaxSeverity = severity;
if (_Errors == null)
{ // if we don't have any we can just start with this list
_Errors = new ArrayList(errors);
return;
}
// Need to copy all items in the errors array
foreach(string err in errors)
_Errors.Add(err);
return;
}
private void DoStatistics(HtmlTextWriter tw)
{
RdlSession rs = Context.Application[RdlSession.SessionStat] as RdlSession;
ReportHelper s = ReportHelper.Get(this.Context.Application);
Cache c = this.Context.Cache;
int sessions=0;
if (rs != null)
sessions = rs.Count;
tw.Write("<p>{0} sessions", sessions);
tw.Write("<p>{0} items are in the cache", c.Count);
tw.Write("<p>{0} cache hits", s.CacheHits);
tw.Write("<p>{0} cache misses", s.CacheMisses);
foreach(DictionaryEntry de in c)
{
if (de.Value is ReportDefn)
tw.Write("<p>file=" + de.Key.ToString());
else
tw.Write("<p>key=" + de.Key.ToString());
}
}
private void Generate(Report report)
{
MemoryStreamGen sg=null;
try
{
sg = new MemoryStreamGen("ShowFile.aspx?type=", null, this.RenderType);
report.RunRender(sg, _RenderType, this.UniqueID);
_CSS = "";
_JavaScript = "";
switch (_RenderType)
{
case OutputPresentationType.ASPHTML:
case OutputPresentationType.HTML:
_CSS = report.CSS;//.Replace("position: relative;", "position: absolute;");
_JavaScript = report.JavaScript;
_Html = sg.GetText();
break;
case OutputPresentationType.XML:
_Xml = sg.GetText();
break;
case OutputPresentationType.CSV:
_Csv = sg.GetText();
break;
case OutputPresentationType.PDF:
{
MemoryStream ms = sg.MemoryList[0] as MemoryStream;
_Object = ms.ToArray();
break;
}
}
// Now save off the other streams in the session context for later use
IList strms = sg.MemoryList;
IList names = sg.MemoryNames;
for (int i=1; i < sg.MemoryList.Count; i++) // we skip the first one
{
string n = names[i] as string;
MemoryStream ms = strms[i] as MemoryStream;
Context.Session[n] = ms.ToArray();
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (sg != null)
{
sg.CloseMainStream();
}
}
if (report.ErrorMaxSeverity > 0)
{
AddError(report.ErrorMaxSeverity, report.ErrorItems);
report.ErrorReset();
}
return;
}
private OutputPresentationType GetRenderType(string type)
{
switch (type.ToLower())
{
case "htm":
case "html":
return OutputPresentationType.ASPHTML;
case "pdf":
return OutputPresentationType.PDF;
case "xml":
return OutputPresentationType.XML;
case "csv":
return OutputPresentationType.CSV;
case "xlsx":
return OutputPresentationType.Excel;
case "rtf":
return OutputPresentationType.RTF;
default:
return OutputPresentationType.ASPHTML;
}
}
private Report GetReport(string prog, string file)
{
// Now parse the file
RDLParser rdlp;
Report r;
try
{
// Make sure RdlEngine is configed before we ever parse a program
// The config file must exist in the Bin directory.
string searchDir = this.MapPathSecure(this.ReportFile.StartsWith("~") ? "~/Bin" : "/Bin") + Path.DirectorySeparatorChar;
RdlEngineConfig.RdlEngineConfigInit(searchDir);
rdlp = new RDLParser(prog);
string folder = Path.GetDirectoryName(file);
if (folder == "")
folder = Environment.CurrentDirectory;
rdlp.Folder = folder;
rdlp.DataSourceReferencePassword = new NeedPassword(this.GetPassword);
r = rdlp.Parse();
if (r.ErrorMaxSeverity > 0)
{
AddError(r.ErrorMaxSeverity, r.ErrorItems);
if (r.ErrorMaxSeverity >= 8)
r = null;
r.ErrorReset();
}
// If we've loaded the report; we should tell it where it got loaded from
if (r != null)
{
r.Folder = folder;
r.Name = Path.GetFileNameWithoutExtension(file);
r.GetDataSourceReferencePassword = new RDL.NeedPassword(GetPassword);
}
}
catch(Exception e)
{
r = null;
AddError(8, "Exception parsing report {0}. {1}", file, e.Message);
}
return r;
}
}
internal class ReportHelper
{
static internal bool DoCaching = true;
internal int CacheHits;
internal int CacheMisses;
private ReportHelper()
{
CacheHits = 0;
CacheMisses = 0;
}
static internal ReportHelper Get(HttpApplicationState app)
{
ReportHelper s = app["fyistats"] as ReportHelper;
if (s == null)
{
s = new ReportHelper();
app["fyistats"] = s;
}
return s;
}
static internal void IncrHits(HttpApplicationState app)
{
ReportHelper s = Get(app);
lock (s)
{
s.CacheHits++;
}
}
static internal void IncrMisses(HttpApplicationState app)
{
ReportHelper s = Get(app);
lock (s)
{
s.CacheMisses++;
}
}
static internal Report GetCachedReport(string file, Cache c, HttpApplicationState app)
{
if (!ReportHelper.DoCaching) // caching is disabled
{
ReportHelper.IncrMisses(app);
return null;
}
// Cache c = this.Context.Cache;
ReportDefn rd = c[file] as ReportDefn;
if (rd == null)
{
ReportHelper.IncrMisses(app);
return null;
}
ReportHelper.IncrHits(app);
Report r = new Report(rd);
return r;
}
static internal void SaveCachedReport(Report r, string file, Cache c)
{
if (!ReportHelper.DoCaching) // caching is disabled
return;
c.Insert(file, r.ReportDefinition, new CacheDependency(file));
return;
}
static internal ListDictionary GetParameters(string parms)
{
ListDictionary ld = new ListDictionary();
if (parms == null)
return ld; // dictionary will be empty in this case
// parms are separated by &
char[] breakChars = new char[] { '&' };
string[] ps = parms.Split(breakChars);
foreach (string p in ps)
{
int iEq = p.IndexOf("=");
if (iEq > 0)
{
string name = p.Substring(0, iEq);
string val = p.Substring(iEq + 1);
ld.Add(name, val);
}
}
return ld;
}
static internal string GetSource(string file)
{
StreamReader fs = null;
string prog = null;
try
{
fs = new StreamReader(file);
prog = fs.ReadToEnd();
}
finally
{
if (fs != null)
fs.Close();
}
return prog;
}
static internal void SetUserContext(Report r, HttpContext context, NeedPassword np)
{
r.GetDataSourceReferencePassword = np;
if (context == null) // may not always have a context
return;
HttpRequest req = context.Request;
if (req != null && req.UserLanguages!= null && req.UserLanguages.Length > 0)
{
string l = req.UserLanguages[0];
r.ClientLanguage = l;
}
if (context.User != null && context.User.Identity != null)
{
System.Security.Principal.IIdentity id = context.User.Identity;
if (id.IsAuthenticated)
{
r.UserID = id.Name;
}
}
return;
}
/// <summary>
/// Returns the HTML needed to represent the parameters of a report.
/// </summary>
static internal string GetParameterHtml(Report rpt, IDictionary pd, HttpContext context, string reportFile, bool bShow)
{
if (rpt == null)
return "";
StringBuilder pHtml = new StringBuilder();
pHtml.AppendFormat("<form target=\"_self\" method=get action=\"{0}\">", context.Request.Url);
// hidden field
pHtml.AppendFormat("<input type=hidden name=\"rs:url\" value=\"{0}\" />",
reportFile);
pHtml.AppendFormat("<table width=\"100%\">");
int row = 0;
foreach (UserReportParameter rp in rpt.UserReportParameters)
{
if (rp.Prompt == null) // skip parameters that don't have a prompt
continue;
pHtml.Append("<tr>"); // Create a row for each parameter
// Create the label
pHtml.Append("<td>"); // Label definition
pHtml.Append(rp.Prompt);
pHtml.Append("</td><td>"); // end of label; start of control
// Create the control
string defaultValue;
if (rp.DefaultValue != null)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rp.DefaultValue.Length; i++)
{
if (i > 0)
sb.Append(", ");
sb.Append(rp.DefaultValue[i].ToString());
}
defaultValue = sb.ToString();
}
else
defaultValue = "";
if (rp.DisplayValues == null)
{
string pv = (string)pd[rp.Name];
switch (rp.dt)
{
case TypeCode.Int32:
case TypeCode.Int16:
case TypeCode.Int64:
pHtml.AppendFormat("<input type=text name=\"{0}\" value=\"{1}\" tabindex=\"{2}\" size=32 onKeyPress=\"javascript:return limitinput(event, '0123456789', true);\"/></td>",
rp.Name, // name
pv == null ? defaultValue : pv, // provide actual value if passed as parm otherwise default
row + 1); //use the row to set the tab order
break;
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.Single:
pHtml.AppendFormat("<input type=text name=\"{0}\" value=\"{1}\" tabindex=\"{2}\" size=32 onKeyPress=\"javascript:return limitinput(event, '0123456789.', true);\"/></td>",
rp.Name, // name
pv == null ? defaultValue : pv, // provide actual value if passed as parm otherwise default
row + 1); //use the row to set the tab order
break;
default:
pHtml.AppendFormat("<input type=text name=\"{0}\" value=\"{1}\" tabindex=\"{2}\" size=32/></td>",
rp.Name, // name
pv == null ? defaultValue : pv, // provide actual value if passed as parm otherwise default
row + 1); //use the row to set the tab order
break;
}
/* pHtml.AppendFormat("<input type=text name=\"{0}\" value=\"{1}\" tabindex=\"{2}\" size=32/></td>",
rp.Name, // name
pv == null? defaultValue: pv, // provide actual value if passed as parm otherwise default
row + 1); //use the row to set the tab order*/
if (rp.dt == TypeCode.DateTime)
{
//pHtml.AppendFormat("<td><input id=\"{0}\" type=\"button\" value=\"Date\" />", rp.Name + "Dtbtn /><td>");
pHtml.AppendFormat("<td><A id=\"lnk" + rp.Name + "\" href=\"javascript:NewCal('{0}','ddmmmyyyy',true,24)\" runat=\"server\"><IMG height=\"16\" alt=\"Pick a date\" src=\"SmallCalendar.gif\" width=\"16\" border=\"0\"/></td>", rp.Name);
}
}
else
{
pHtml.AppendFormat("<select name=\"{0}\" tabindex=\"{1}\"size=1>", rp.Name, row + 1);
string pv = (string)pd[rp.Name];
if (pv == null)
pv = defaultValue;
string selected;
for (int i = 0; i < rp.DisplayValues.Length; i++)
{
if (pv.CompareTo(rp.DataValues[i].ToString()) == 0)
selected = " selected";
else
selected = "";
if (rp.DataValues[i] is String &&
rp.DisplayValues[i].CompareTo(rp.DataValues[i]) == 0) // When display and data values are same don't put out a value tag
pHtml.AppendFormat("<option{1}>{0}</option>", XmlUtil.XmlAnsi(rp.DisplayValues[i]), selected);
else
pHtml.AppendFormat("<option value=\"{0}\"{2}>{1}</option>", XmlUtil.XmlAnsi(rp.DataValues[i].ToString()), XmlUtil.XmlAnsi(rp.DisplayValues[i]), selected);
}
pHtml.Append("</select></td>");
}
if (row == 0)
{ // On the first row add a column that will be the submit button
pHtml.AppendFormat("<td rowspan=2><table><tr><td align=right><input type=\"submit\" value=\"Run Report\" style=\"font-family:Ariel; color: black; font-size=10pt; background: gainsboro;\" tabindex=\"{0}\"/></td></tr>", rpt.UserReportParameters.Count + 1);
if (!bShow) { ReportHelper.AppendExports(pHtml, context, reportFile); } else { pHtml.AppendFormat("<tr><td align=right></td><td align=right> </td></tr></table></td>"); }
}
pHtml.Append("</tr>"); // End of row for each parameter
row++;
}
if (row == 0)
{
pHtml.AppendFormat("<tr><td><table><tr><td align=right><input type=\"submit\" value=\"Run Report\" style=\"font-family:Ariel; color: white; font-size=10pt; background: lightblue;\" tabindex=\"{0}\"/></td></tr>", rpt.UserReportParameters.Count + 1);
if (!bShow) { ReportHelper.AppendExports(pHtml, context, reportFile); } else { pHtml.AppendFormat("<tr><td align=right></td><td align=right> </td></tr></table></td>"); }
}
pHtml.Append("</table></form>"); // End of table, form, html
return pHtml.ToString();
}
static private void AppendExports(StringBuilder pHtml, HttpContext context, string reportFile)
{
StringBuilder args = new StringBuilder();
NameValueCollection nvc;
nvc = context.Request.QueryString; // parameters
for (int i = 0; i < nvc.Count; i++)
{
string key = nvc.GetKey(i);
if (!key.StartsWith("rs:"))
args.AppendFormat("&{0}={1}",
System.Web.HttpUtility.UrlEncode(key), System.Web.HttpUtility.UrlEncode(nvc[i]));
}
string sargs = args.ToString();
string lpdf =
string.Format("<a href=\"ShowReport.aspx?rs:url={0}&rs:Format=pdf{1}\" target=_blank>PDF</a>",
reportFile, sargs);
string lxml =
string.Format("<a href=\"ShowReport.aspx?rs:url={0}&rs:Format=xml{1}\" target=_blank>XML</a>",
reportFile, sargs);
string lcsv =
string.Format("<a href=\"ShowReport.aspx?rs:url={0}&rs:Format=csv{1}\" target=_blank>CSV</a>",
reportFile, sargs);
pHtml.AppendFormat("<tr><td align=right>{0}</td><td align=right>{1} {2}</td></tr></table></td>",
lpdf, lxml, lcsv);
}
}
}
| |
// Copyright (c) 2018-2021 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
namespace Sharpmake
{
public class IncludeAttributeParser : SimpleSourceAttributeParser
{
public IncludeAttributeParser() : base("Include", 1, 2, "Sharpmake")
{
}
private string MatchIncludeInParentPath(string filePath, string initialDirectory, IncludeType includeMatchType)
{
string matchPath = Path.Combine(initialDirectory, filePath);
bool matchPathExists = Util.FileExists(matchPath);
if (matchPathExists && includeMatchType == IncludeType.NearestMatchInParentPath)
{
return matchPath;
}
// backtrace one level in the path
string matchResult = null;
DirectoryInfo info = Directory.GetParent(initialDirectory);
if (info != null)
{
string parentPath = info.FullName;
if (!parentPath.Equals(initialDirectory))
{
matchResult = MatchIncludeInParentPath(filePath, parentPath, includeMatchType);
}
}
if (matchPathExists && matchResult == null)
return matchPath;
return matchResult;
}
public override void ParseParameter(string[] parameters, FileInfo sourceFilePath, int lineNumber, IAssemblerContext context)
{
string includeFilename = parameters[0];
IncludeType matchType = IncludeType.Relative;
if (parameters.Length > 1)
{
string incType = parameters[1].Replace("Sharpmake.", "");
incType = incType.Replace("IncludeType.", "");
if (!Enum.TryParse<IncludeType>(incType, out matchType))
{
throw new Error("\t" + sourceFilePath.FullName + "(" + lineNumber + "): error: Sharpmake.Include invalid include type used ({0})", parameters[1]);
}
}
string includeAbsolutePath = Path.IsPathRooted(includeFilename) ? includeFilename : null;
if (Util.IsPathWithWildcards(includeFilename))
{
if (matchType != IncludeType.Relative)
{
throw new Error("\t" + sourceFilePath.FullName + "(" + lineNumber + "): error: Sharpmake.Include with non-relative match types, wildcards are not supported ({0})", includeFilename);
}
includeAbsolutePath = includeAbsolutePath ?? Path.Combine(sourceFilePath.DirectoryName, includeFilename);
context.AddSourceFiles(Util.DirectoryGetFilesWithWildcards(includeAbsolutePath));
}
else
{
includeAbsolutePath = includeAbsolutePath ?? Util.PathGetAbsolute(sourceFilePath.DirectoryName, includeFilename);
if (matchType == IncludeType.Relative)
{
if (!Util.FileExists(includeAbsolutePath))
includeAbsolutePath = Util.GetCapitalizedPath(includeAbsolutePath);
}
else
{
string matchIncludeInParentPath = MatchIncludeInParentPath(includeFilename, sourceFilePath.DirectoryName, matchType);
if (matchIncludeInParentPath == null)
throw new Error("\t" + sourceFilePath.FullName + "(" + lineNumber + "): error: Sharpmake.Include file not found '{0}'[{1}]. Search started from '{2}'", includeFilename, matchType, sourceFilePath.DirectoryName);
includeAbsolutePath = Util.GetCapitalizedPath(matchIncludeInParentPath);
}
if (!Util.FileExists(includeAbsolutePath))
throw new Error("\t" + sourceFilePath.FullName + "(" + lineNumber + "): error: Sharpmake.Include file not found {0}", includeFilename);
context.AddSourceFile(includeAbsolutePath);
}
}
}
public class ReferenceAttributeParser : SimpleSourceAttributeParser
{
public ReferenceAttributeParser() : base("Reference", 1, "Sharpmake")
{
}
private IEnumerable<string> EnumerateReferencePathCandidates(FileInfo sourceFilePath, string reference)
{
// Try with the full path
if (Path.IsPathRooted(reference))
yield return reference;
// Try relative from the sharpmake file
yield return Util.PathGetAbsolute(sourceFilePath.DirectoryName, reference);
// Try next to the Sharpmake binary
string pathToBinary = System.Reflection.Assembly.GetEntryAssembly()?.Location;
if (!string.IsNullOrEmpty(pathToBinary))
yield return Util.PathGetAbsolute(Path.GetDirectoryName(pathToBinary), reference);
// In some cases, the main module is not the current binary, so try it if so
string mainModule = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
if (!string.IsNullOrEmpty(mainModule) && pathToBinary != mainModule)
yield return Util.PathGetAbsolute(Path.GetDirectoryName(mainModule), reference);
// Try in the current working directory
yield return Util.PathGetAbsolute(Directory.GetCurrentDirectory(), reference);
// Try using .net framework locations
foreach (string frameworkDirectory in Assembler.EnumeratePathToDotNetFramework())
yield return Path.Combine(Path.Combine(frameworkDirectory, reference));
}
public override void ParseParameter(string[] parameters, FileInfo sourceFilePath, int lineNumber, IAssemblerContext context)
{
string reference = parameters[0];
if (Util.IsPathWithWildcards(reference))
{
string referenceAbsolutePath = Path.IsPathRooted(reference) ? reference : null;
referenceAbsolutePath = referenceAbsolutePath ?? Path.Combine(sourceFilePath.DirectoryName, reference);
context.AddReferences(Util.DirectoryGetFilesWithWildcards(referenceAbsolutePath));
}
else
{
bool foundReference = false;
foreach (string candidateReferenceLocation in EnumerateReferencePathCandidates(sourceFilePath, reference))
{
if (Util.FileExists(candidateReferenceLocation))
{
context.AddReference(candidateReferenceLocation);
foundReference = true;
break;
}
}
if (!foundReference)
{
throw new Error(
"\t{0}({1}): error: Sharpmake.Reference file not found: {2}{3}Those paths were evaluated as candidates:{3} - {4}",
sourceFilePath.FullName,
lineNumber,
reference,
Environment.NewLine,
string.Join(Environment.NewLine + " - ", EnumerateReferencePathCandidates(sourceFilePath, reference))
);
}
}
}
}
public class PackageAttributeParser : SimpleSourceAttributeParser
{
private static readonly Dictionary<string, IAssemblyInfo> s_assemblies = new Dictionary<string, IAssemblyInfo>(StringComparer.OrdinalIgnoreCase);
public PackageAttributeParser() : base("Package", 1, "Sharpmake")
{
}
public override void ParseParameter(string[] parameters, FileInfo sourceFilePath, int lineNumber, IAssemblerContext context)
{
string includeFilename = parameters[0];
string includeAbsolutePath;
if (Path.IsPathRooted(includeFilename))
{
includeAbsolutePath = includeFilename;
}
else if (Util.IsPathWithWildcards(includeFilename))
{
includeAbsolutePath = Path.Combine(sourceFilePath.DirectoryName, includeFilename);
}
else
{
includeAbsolutePath = Util.PathGetAbsolute(sourceFilePath.DirectoryName, includeFilename);
}
IAssemblyInfo assemblyInfo;
if (s_assemblies.TryGetValue(includeAbsolutePath, out assemblyInfo))
{
if (assemblyInfo == null)
throw new Error($"Circular Sharpmake.Package dependency on {includeFilename}");
context.AddReference(assemblyInfo);
return;
}
s_assemblies[includeAbsolutePath] = null;
string[] files;
if (Util.IsPathWithWildcards(includeFilename))
{
files = Util.DirectoryGetFilesWithWildcards(includeAbsolutePath);
}
else
{
if (!Util.FileExists(includeAbsolutePath))
includeAbsolutePath = Util.GetCapitalizedPath(includeAbsolutePath);
if (!Util.FileExists(includeAbsolutePath))
throw new Error("\t" + sourceFilePath.FullName + "(" + lineNumber + "): error: Sharpmake.Package file not found {0}", includeFilename);
files = new string[] { includeAbsolutePath };
}
assemblyInfo = context.BuildLoadAndAddReferenceToSharpmakeFilesAssembly(files);
s_assemblies[includeAbsolutePath] = assemblyInfo;
}
}
public class DebugProjectNameAttributeParser : SimpleSourceAttributeParser
{
public DebugProjectNameAttributeParser() : base("DebugProjectName", 1, "Sharpmake")
{
}
public override void ParseParameter(string[] parameters, FileInfo sourceFilePath, int lineNumber, IAssemblerContext context)
{
context.SetDebugProjectName(parameters[0]);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace System.Data.Common
{
public abstract class DbDataReader : MarshalByRefObject, IDataReader, IEnumerable, IAsyncDisposable
{
protected DbDataReader() : base() { }
public abstract int Depth { get; }
public abstract int FieldCount { get; }
public abstract bool HasRows { get; }
public abstract bool IsClosed { get; }
public abstract int RecordsAffected { get; }
public virtual int VisibleFieldCount => FieldCount;
public abstract object this[int ordinal] { get; }
public abstract object this[string name] { get; }
public virtual void Close() { }
public virtual Task CloseAsync()
{
try
{
Close();
return Task.CompletedTask;
}
catch (Exception e)
{
return Task.FromException(e);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void Dispose() => Dispose(true);
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
public virtual ValueTask DisposeAsync()
{
Dispose();
return default;
}
public abstract string GetDataTypeName(int ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract IEnumerator GetEnumerator();
public abstract Type GetFieldType(int ordinal);
public abstract string GetName(int ordinal);
public abstract int GetOrdinal(string name);
public virtual DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public abstract bool GetBoolean(int ordinal);
public abstract byte GetByte(int ordinal);
public abstract long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length);
public abstract char GetChar(int ordinal);
public abstract long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length);
[EditorBrowsable(EditorBrowsableState.Never)]
public DbDataReader GetData(int ordinal) => GetDbDataReader(ordinal);
IDataReader IDataRecord.GetData(int ordinal) => GetDbDataReader(ordinal);
protected virtual DbDataReader GetDbDataReader(int ordinal)
{
throw ADP.NotSupported();
}
public abstract DateTime GetDateTime(int ordinal);
public abstract decimal GetDecimal(int ordinal);
public abstract double GetDouble(int ordinal);
public abstract float GetFloat(int ordinal);
public abstract Guid GetGuid(int ordinal);
public abstract short GetInt16(int ordinal);
public abstract int GetInt32(int ordinal);
public abstract long GetInt64(int ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Type GetProviderSpecificFieldType(int ordinal)
{
// NOTE: This is virtual because not all providers may choose to support
// this method, since it was added in Whidbey.
return GetFieldType(ordinal);
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public virtual object GetProviderSpecificValue(int ordinal)
{
// NOTE: This is virtual because not all providers may choose to support
// this method, since it was added in Whidbey
return GetValue(ordinal);
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public virtual int GetProviderSpecificValues(object[] values) => GetValues(values);
public abstract string GetString(int ordinal);
public virtual Stream GetStream(int ordinal)
{
using (MemoryStream bufferStream = new MemoryStream())
{
long bytesRead = 0;
long bytesReadTotal = 0;
byte[] buffer = new byte[4096];
do
{
bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length);
bufferStream.Write(buffer, 0, (int)bytesRead);
bytesReadTotal += bytesRead;
}
while (bytesRead > 0);
return new MemoryStream(bufferStream.ToArray(), false);
}
}
public virtual TextReader GetTextReader(int ordinal)
{
if (IsDBNull(ordinal))
{
return new StringReader(string.Empty);
}
else
{
return new StringReader(GetString(ordinal));
}
}
public abstract object GetValue(int ordinal);
public virtual T GetFieldValue<T>(int ordinal) => (T)GetValue(ordinal);
public Task<T> GetFieldValueAsync<T>(int ordinal) =>
GetFieldValueAsync<T>(ordinal, CancellationToken.None);
public virtual Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<T>();
}
else
{
try
{
return Task.FromResult<T>(GetFieldValue<T>(ordinal));
}
catch (Exception e)
{
return Task.FromException<T>(e);
}
}
}
public abstract int GetValues(object[] values);
public abstract bool IsDBNull(int ordinal);
public Task<bool> IsDBNullAsync(int ordinal) => IsDBNullAsync(ordinal, CancellationToken.None);
public virtual Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<bool>();
}
else
{
try
{
return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
public abstract bool NextResult();
public abstract bool Read();
public Task<bool> ReadAsync() => ReadAsync(CancellationToken.None);
public virtual Task<bool> ReadAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<bool>();
}
else
{
try
{
return Read() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
public Task<bool> NextResultAsync() => NextResultAsync(CancellationToken.None);
public virtual Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<bool>();
}
else
{
try
{
return NextResult() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to install, execute and perform the Spine Runtimes
* Software (the "Software") solely for internal use. Without the written
* permission of Esoteric Software (typically granted by licensing Spine), you
* may not (a) modify, translate, adapt or otherwise create derivative works,
* improvements of the Software or develop new applications using the Software
* 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 SOFTARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
#if WINDOWS_STOREAPP
using System.Threading.Tasks;
using Windows.Storage;
#endif
namespace Spine {
public class Atlas {
List<AtlasPage> pages = new List<AtlasPage>();
List<AtlasRegion> regions = new List<AtlasRegion>();
TextureLoader textureLoader;
#if WINDOWS_STOREAPP
private async Task ReadFile(string path, TextureLoader textureLoader) {
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false);
using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) {
try {
Load(reader, Path.GetDirectoryName(path), textureLoader);
} catch (Exception ex) {
throw new Exception("Error reading atlas file: " + path, ex);
}
}
}
public Atlas(String path, TextureLoader textureLoader) {
this.ReadFile(path, textureLoader).Wait();
}
#else
public Atlas (String path, TextureLoader textureLoader) {
#if WINDOWS_PHONE
Stream stream = Microsoft.Xna.Framework.TitleContainer.OpenStream(path);
using (StreamReader reader = new StreamReader(stream))
{
#else
using (StreamReader reader = new StreamReader(path)) {
#endif
try {
Load(reader, Path.GetDirectoryName(path), textureLoader);
} catch (Exception ex) {
throw new Exception("Error reading atlas file: " + path, ex);
}
}
}
#endif
public Atlas (TextReader reader, String dir, TextureLoader textureLoader) {
Load(reader, dir, textureLoader);
}
public Atlas (List<AtlasPage> pages, List<AtlasRegion> regions) {
this.pages = pages;
this.regions = regions;
this.textureLoader = null;
}
private void Load (TextReader reader, String imagesDir, TextureLoader textureLoader) {
if (textureLoader == null) throw new ArgumentNullException("textureLoader cannot be null.");
this.textureLoader = textureLoader;
String[] tuple = new String[4];
AtlasPage page = null;
while (true) {
String line = reader.ReadLine();
if (line == null) break;
if (line.Trim().Length == 0)
page = null;
else if (page == null) {
page = new AtlasPage();
page.name = line;
page.format = (Format)Enum.Parse(typeof(Format), readValue(reader), false);
readTuple(reader, tuple);
page.minFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[0], false);
page.magFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[1], false);
String direction = readValue(reader);
page.uWrap = TextureWrap.ClampToEdge;
page.vWrap = TextureWrap.ClampToEdge;
if (direction == "x")
page.uWrap = TextureWrap.Repeat;
else if (direction == "y")
page.vWrap = TextureWrap.Repeat;
else if (direction == "xy")
page.uWrap = page.vWrap = TextureWrap.Repeat;
textureLoader.Load(page, Path.Combine(imagesDir, line));
pages.Add(page);
} else {
AtlasRegion region = new AtlasRegion();
region.name = line;
region.page = page;
region.rotate = Boolean.Parse(readValue(reader));
readTuple(reader, tuple);
int x = int.Parse(tuple[0]);
int y = int.Parse(tuple[1]);
readTuple(reader, tuple);
int width = int.Parse(tuple[0]);
int height = int.Parse(tuple[1]);
region.u = x / (float)page.width;
region.v = y / (float)page.height;
if (region.rotate) {
region.u2 = (x + height) / (float)page.width;
region.v2 = (y + width) / (float)page.height;
} else {
region.u2 = (x + width) / (float)page.width;
region.v2 = (y + height) / (float)page.height;
}
region.x = x;
region.y = y;
region.width = Math.Abs(width);
region.height = Math.Abs(height);
if (readTuple(reader, tuple) == 4) { // split is optional
region.splits = new int[] {int.Parse(tuple[0]), int.Parse(tuple[1]),
int.Parse(tuple[2]), int.Parse(tuple[3])};
if (readTuple(reader, tuple) == 4) { // pad is optional, but only present with splits
region.pads = new int[] {int.Parse(tuple[0]), int.Parse(tuple[1]),
int.Parse(tuple[2]), int.Parse(tuple[3])};
readTuple(reader, tuple);
}
}
region.originalWidth = int.Parse(tuple[0]);
region.originalHeight = int.Parse(tuple[1]);
readTuple(reader, tuple);
region.offsetX = int.Parse(tuple[0]);
region.offsetY = int.Parse(tuple[1]);
region.index = int.Parse(readValue(reader));
regions.Add(region);
}
}
}
static String readValue (TextReader reader) {
String line = reader.ReadLine();
int colon = line.IndexOf(':');
if (colon == -1) throw new Exception("Invalid line: " + line);
return line.Substring(colon + 1).Trim();
}
/// <summary>Returns the number of tuple values read (2 or 4).</summary>
static int readTuple (TextReader reader, String[] tuple) {
String line = reader.ReadLine();
int colon = line.IndexOf(':');
if (colon == -1) throw new Exception("Invalid line: " + line);
int i = 0, lastMatch = colon + 1;
for (; i < 3; i++) {
int comma = line.IndexOf(',', lastMatch);
if (comma == -1) {
if (i == 0) throw new Exception("Invalid line: " + line);
break;
}
tuple[i] = line.Substring(lastMatch, comma - lastMatch).Trim();
lastMatch = comma + 1;
}
tuple[i] = line.Substring(lastMatch).Trim();
return i + 1;
}
public void FlipV () {
for (int i = 0, n = regions.Count; i < n; i++) {
AtlasRegion region = regions[i];
region.v = 1 - region.v;
region.v2 = 1 - region.v2;
}
}
/// <summary>Returns the first region found with the specified name. This method uses string comparison to find the region, so the result
/// should be cached rather than calling this method multiple times.</summary>
/// <returns>The region, or null.</returns>
public AtlasRegion FindRegion (String name) {
for (int i = 0, n = regions.Count; i < n; i++)
if (regions[i].name == name) return regions[i];
return null;
}
public void Dispose () {
if (textureLoader == null) return;
for (int i = 0, n = pages.Count; i < n; i++)
textureLoader.Unload(pages[i].rendererObject);
}
}
public enum Format {
Alpha,
Intensity,
LuminanceAlpha,
RGB565,
RGBA4444,
RGB888,
RGBA8888
}
public enum TextureFilter {
Nearest,
Linear,
MipMap,
MipMapNearestNearest,
MipMapLinearNearest,
MipMapNearestLinear,
MipMapLinearLinear
}
public enum TextureWrap {
MirroredRepeat,
ClampToEdge,
Repeat
}
public class AtlasPage {
public String name;
public Format format;
public TextureFilter minFilter;
public TextureFilter magFilter;
public TextureWrap uWrap;
public TextureWrap vWrap;
public Object rendererObject;
public int width, height;
}
public class AtlasRegion {
public AtlasPage page;
public String name;
public int x, y, width, height;
public float u, v, u2, v2;
public float offsetX, offsetY;
public int originalWidth, originalHeight;
public int index;
public bool rotate;
public int[] splits;
public int[] pads;
}
public interface TextureLoader {
void Load (AtlasPage page, String path);
void Unload (Object texture);
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.Automation;
using Microsoft.WindowsAzure.Management.Automation.Models;
namespace Microsoft.WindowsAzure.Management.Automation
{
public static partial class AutomationAccountOperationsExtensions
{
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create automation account.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static LongRunningOperationStatusResponse BeginCreate(this IAutomationAccountOperations operations, string clouldServiceName, AutomationAccountCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAutomationAccountOperations)s).BeginCreateAsync(clouldServiceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create automation account.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<LongRunningOperationStatusResponse> BeginCreateAsync(this IAutomationAccountOperations operations, string clouldServiceName, AutomationAccountCreateParameters parameters)
{
return operations.BeginCreateAsync(clouldServiceName, parameters, CancellationToken.None);
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='automationAccountName'>
/// Required. Automation account name.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static LongRunningOperationStatusResponse BeginDelete(this IAutomationAccountOperations operations, string clouldServiceName, string automationAccountName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAutomationAccountOperations)s).BeginDeleteAsync(clouldServiceName, automationAccountName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='automationAccountName'>
/// Required. Automation account name.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<LongRunningOperationStatusResponse> BeginDeleteAsync(this IAutomationAccountOperations operations, string clouldServiceName, string automationAccountName)
{
return operations.BeginDeleteAsync(clouldServiceName, automationAccountName, CancellationToken.None);
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create automation account.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static LongRunningOperationStatusResponse Create(this IAutomationAccountOperations operations, string clouldServiceName, AutomationAccountCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAutomationAccountOperations)s).CreateAsync(clouldServiceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create automation account.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<LongRunningOperationStatusResponse> CreateAsync(this IAutomationAccountOperations operations, string clouldServiceName, AutomationAccountCreateParameters parameters)
{
return operations.CreateAsync(clouldServiceName, parameters, CancellationToken.None);
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='automationAccountName'>
/// Required. Automation account name.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static LongRunningOperationStatusResponse Delete(this IAutomationAccountOperations operations, string clouldServiceName, string automationAccountName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAutomationAccountOperations)s).DeleteAsync(clouldServiceName, automationAccountName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IAutomationAccountOperations.
/// </param>
/// <param name='clouldServiceName'>
/// Required. Cloud service name.
/// </param>
/// <param name='automationAccountName'>
/// Required. Automation account name.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<LongRunningOperationStatusResponse> DeleteAsync(this IAutomationAccountOperations operations, string clouldServiceName, string automationAccountName)
{
return operations.DeleteAsync(clouldServiceName, automationAccountName, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Ookii.Dialogs.Wpf;
namespace Cocoa.Infrastructure.DialogService
{
enum DialogMessageResult
{
None,
OK,
Cancel,
Retry,
Yes,
No,
Close,
CustomButtonClicked,
}
[Flags]
enum DialogMessageButtons
{
None = 0x0000,
Ok = 0x0001,
Yes = 0x0002,
No = 0x0004,
Cancel = 0x0008,
Retry = 0x0010,
Close = 0x0020
}
enum DialogMessageIcon
{
None,
Error,
Question,
Warning,
Information,
Shield
}
internal class DialogMessageService
{
private readonly Window owner;
public DialogMessageService(Window owner)
{
this.owner = owner;
}
private DialogMessageResult DoOokiiMsgBox()
{
var td = new TaskDialog();
if ((Buttons & DialogMessageButtons.Ok) != 0) td.Buttons.Add(new TaskDialogButton(ButtonType.Ok));
if ((Buttons & DialogMessageButtons.Cancel) != 0) td.Buttons.Add(new TaskDialogButton(ButtonType.Cancel));
if ((Buttons & DialogMessageButtons.Yes) != 0) td.Buttons.Add(new TaskDialogButton(ButtonType.Yes));
if ((Buttons & DialogMessageButtons.No) != 0) td.Buttons.Add(new TaskDialogButton(ButtonType.No));
if ((Buttons & DialogMessageButtons.Close) != 0) td.Buttons.Add(new TaskDialogButton(ButtonType.Close));
if ((Buttons & DialogMessageButtons.Retry) != 0) td.Buttons.Add(new TaskDialogButton(ButtonType.Retry));
switch (Icon)
{
case DialogMessageIcon.Error:
td.MainIcon = TaskDialogIcon.Error;
break;
case DialogMessageIcon.Question:
td.MainIcon = TaskDialogIcon.Warning;
break;
case DialogMessageIcon.Warning:
td.MainIcon = TaskDialogIcon.Warning;
break;
case DialogMessageIcon.Information:
td.MainIcon = TaskDialogIcon.Information;
break;
case DialogMessageIcon.Shield:
td.MainIcon = TaskDialogIcon.Shield;
break;
}
td.WindowTitle = Title;
td.MainInstruction = Text;
td.Content = Extra;
var translation = new Dictionary<TaskDialogButton, ButtonType>();
if (ButtonExtras != null && ButtonExtras.Any())
{
td.ButtonStyle = TaskDialogButtonStyle.CommandLinks;
var buttonSet = td.Buttons.ToArray();
td.Buttons.Clear();
foreach (var extra in ButtonExtras)
{
foreach (var button in buttonSet.Where(b => b.ButtonType == extra.ButtonType))
{
button.ButtonType = ButtonType.Custom;
button.Text = extra.Text;
button.CommandLinkNote = extra.Note;
translation.Add(button, extra.ButtonType);
td.Buttons.Add(button);
}
}
foreach (var button in buttonSet.Where(b => b.ButtonType != ButtonType.Custom))
{
td.Buttons.Add(button);
}
}
TaskDialogButton result = null;
if (owner == null)
result = td.ShowDialog();
else
{
var dispatcher = owner.Dispatcher;
result = (TaskDialogButton)dispatcher.Invoke(
new Func<TaskDialogButton>(() => td.ShowDialog(owner)),
System.Windows.Threading.DispatcherPriority.Normal);
}
var resultButtonType = result.ButtonType;
if (resultButtonType == ButtonType.Custom)
{
if (ButtonExtras != null)
{
var button = ButtonExtras.SingleOrDefault(b => b.ButtonType == ButtonType.Custom && b.Text == result.Text);
if (button != null)
button.WasClicked = true;
}
resultButtonType = translation[result];
}
switch (resultButtonType)
{
case ButtonType.Cancel:
return DialogMessageResult.Cancel;
case ButtonType.Close:
return DialogMessageResult.Close;
case ButtonType.No:
return DialogMessageResult.No;
case ButtonType.Ok:
return DialogMessageResult.OK;
case ButtonType.Retry:
return DialogMessageResult.Retry;
case ButtonType.Yes:
return DialogMessageResult.Yes;
}
return DialogMessageResult.None;
}
private DialogMessageResult DoWin32MsgBox()
{
MessageBoxButton button = MessageBoxButton.OK;
if (Buttons == (DialogMessageButtons.Ok | DialogMessageButtons.Cancel))
button = MessageBoxButton.OKCancel;
else if (Buttons == (DialogMessageButtons.Yes | DialogMessageButtons.No))
button = MessageBoxButton.YesNo;
else if (Buttons == (DialogMessageButtons.Yes | DialogMessageButtons.No | DialogMessageButtons.Cancel))
button = MessageBoxButton.YesNoCancel;
MessageBoxImage icon = MessageBoxImage.None;
switch (Icon)
{
case DialogMessageIcon.Error:
icon = MessageBoxImage.Error;
break;
case DialogMessageIcon.Question:
icon = MessageBoxImage.Question;
break;
case DialogMessageIcon.Warning:
case DialogMessageIcon.Shield:
icon = MessageBoxImage.Warning;
break;
case DialogMessageIcon.Information:
icon = MessageBoxImage.Information;
break;
}
MessageBoxResult result = MessageBoxResult.None;
if (owner == null)
result = MessageBox.Show(string.Format("{0}{1}{1}{2}", Text, Environment.NewLine, Extra), Title, button, icon);
else
{
var dispatcher = owner.Dispatcher;
result = (MessageBoxResult)dispatcher.Invoke(
new Func<MessageBoxResult>(() => MessageBox.Show(owner, string.Format("{0}{1}{1}{2}", Text, Environment.NewLine, Extra), Title, button, icon)),
System.Windows.Threading.DispatcherPriority.Normal);
}
switch (result)
{
case MessageBoxResult.Cancel:
return DialogMessageResult.Cancel;
case MessageBoxResult.No:
return DialogMessageResult.No;
case MessageBoxResult.None:
return DialogMessageResult.None;
case MessageBoxResult.OK:
return DialogMessageResult.OK;
case MessageBoxResult.Yes:
return DialogMessageResult.Yes;
}
return DialogMessageResult.None;
}
public string Title { get; set; }
public string Extra { get; set; }
public string Text { get; set; }
public DialogMessageButtons Buttons { get; set; }
public DialogMessageIcon Icon { get; set; }
public ButtonExtras[] ButtonExtras { get; set; }
public DialogMessageResult Show()
{
if (TaskDialog.OSSupportsTaskDialogs)
{
return DoOokiiMsgBox();
}
return DoWin32MsgBox();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal class Test
{
[DllImport("kernel32.dll")]
private extern static IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll")]
private extern static IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, int flAllocationType, int flProtect);
private static void EatAddressSpace()
{
IntPtr clrDllHandle = GetModuleHandle("clr.dll");
long clrDll = (long)clrDllHandle;
for (long i = clrDll - 0x300000000; i < clrDll + 0x300000000; i += 0x10000)
{
}
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void Dummy()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void GenericRecursion<T, U>(int level)
{
if (level == 0) return;
level--;
GenericRecursion<KeyValuePair<T, U>, U>(level);
GenericRecursion<KeyValuePair<U, T>, U>(level);
GenericRecursion<T, KeyValuePair<T, U>>(level);
GenericRecursion<T, KeyValuePair<U, T>>(level);
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
}
private static int Main()
{
try
{
Console.WriteLine("Eating address space");
EatAddressSpace();
Console.WriteLine("Eating code heap");
GenericRecursion<int, uint>(5);
A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10();
B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10();
C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10();
D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10();
A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10();
B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10();
C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10();
D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10();
Console.WriteLine("Done");
return 100;
}
catch (Exception e)
{
Console.WriteLine(e);
return 101;
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class ImportPoolSpectraS3Request : Ds3Request
{
public string Pool { get; private set; }
private ImportConflictResolutionMode? _conflictResolutionMode;
public ImportConflictResolutionMode? ConflictResolutionMode
{
get { return _conflictResolutionMode; }
set { WithConflictResolutionMode(value); }
}
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private Priority? _priority;
public Priority? Priority
{
get { return _priority; }
set { WithPriority(value); }
}
private string _storageDomainId;
public string StorageDomainId
{
get { return _storageDomainId; }
set { WithStorageDomainId(value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { WithUserId(value); }
}
private Priority? _verifyDataAfterImport;
public Priority? VerifyDataAfterImport
{
get { return _verifyDataAfterImport; }
set { WithVerifyDataAfterImport(value); }
}
private bool? _verifyDataPriorToImport;
public bool? VerifyDataPriorToImport
{
get { return _verifyDataPriorToImport; }
set { WithVerifyDataPriorToImport(value); }
}
public ImportPoolSpectraS3Request WithConflictResolutionMode(ImportConflictResolutionMode? conflictResolutionMode)
{
this._conflictResolutionMode = conflictResolutionMode;
if (conflictResolutionMode != null)
{
this.QueryParams.Add("conflict_resolution_mode", conflictResolutionMode.ToString());
}
else
{
this.QueryParams.Remove("conflict_resolution_mode");
}
return this;
}
public ImportPoolSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public ImportPoolSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public ImportPoolSpectraS3Request WithPriority(Priority? priority)
{
this._priority = priority;
if (priority != null)
{
this.QueryParams.Add("priority", priority.ToString());
}
else
{
this.QueryParams.Remove("priority");
}
return this;
}
public ImportPoolSpectraS3Request WithStorageDomainId(Guid? storageDomainId)
{
this._storageDomainId = storageDomainId.ToString();
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId.ToString());
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public ImportPoolSpectraS3Request WithStorageDomainId(string storageDomainId)
{
this._storageDomainId = storageDomainId;
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId);
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public ImportPoolSpectraS3Request WithUserId(Guid? userId)
{
this._userId = userId.ToString();
if (userId != null)
{
this.QueryParams.Add("user_id", userId.ToString());
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public ImportPoolSpectraS3Request WithUserId(string userId)
{
this._userId = userId;
if (userId != null)
{
this.QueryParams.Add("user_id", userId);
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public ImportPoolSpectraS3Request WithVerifyDataAfterImport(Priority? verifyDataAfterImport)
{
this._verifyDataAfterImport = verifyDataAfterImport;
if (verifyDataAfterImport != null)
{
this.QueryParams.Add("verify_data_after_import", verifyDataAfterImport.ToString());
}
else
{
this.QueryParams.Remove("verify_data_after_import");
}
return this;
}
public ImportPoolSpectraS3Request WithVerifyDataPriorToImport(bool? verifyDataPriorToImport)
{
this._verifyDataPriorToImport = verifyDataPriorToImport;
if (verifyDataPriorToImport != null)
{
this.QueryParams.Add("verify_data_prior_to_import", verifyDataPriorToImport.ToString());
}
else
{
this.QueryParams.Remove("verify_data_prior_to_import");
}
return this;
}
public ImportPoolSpectraS3Request(string pool)
{
this.Pool = pool;
this.QueryParams.Add("operation", "import");
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.PUT;
}
}
internal override string Path
{
get
{
return "/_rest_/pool/" + Pool;
}
}
}
}
| |
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 Knockout_Webmail.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedViewAccessor.
/// </summary>
public class MemoryMappedViewAccessorTests : MemoryMappedFilesTestBase
{
/// <summary>
/// Test to validate the offset, size, and access parameters to MemoryMappedFile.CreateViewAccessor.
/// </summary>
[Fact]
public void InvalidArguments()
{
int mapLength = s_pageSize.Value;
foreach (MemoryMappedFile mmf in CreateSampleMaps(mapLength))
{
using (mmf)
{
// Offset
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength, MemoryMappedFileAccess.ReadWrite));
// Size
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1, MemoryMappedFileAccess.ReadWrite));
if (IntPtr.Size == 4)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue));
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
else
{
Assert.Throws<IOException>(() => mmf.CreateViewAccessor(0, long.MaxValue));
Assert.Throws<IOException>(() => mmf.CreateViewAccessor(0, long.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
// Offset + Size
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1, MemoryMappedFileAccess.ReadWrite));
// Access
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(42)));
}
}
}
[ConditionalTheory]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void ValidAccessLevelCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
AssertExtensions.ThrowsIf<IOException>(PlatformDetection.IsInAppContainer && mapAccess == MemoryMappedFileAccess.ReadWriteExecute && viewAccess == MemoryMappedFileAccess.ReadWriteExecute,
() =>
{
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, viewAccess))
{
ValidateMemoryMappedViewAccessor(acc, Capacity, viewAccess);
}
}
catch (UnauthorizedAccessException)
{
if (PlatformDetection.IsInContainer && (viewAccess == MemoryMappedFileAccess.ReadExecute || viewAccess == MemoryMappedFileAccess.ReadWriteExecute))
{
throw new SkipTestException("Execute permission failing in container.");
}
throw;
}
});
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
public void InvalidAccessLevelsCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, Capacity, viewAccess));
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
public void InvalidAccessLevels_ReadWrite_NonUwp(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, Capacity, viewAccess));
}
}
/// <summary>
/// Test to verify the accessor's PointerOffset.
/// </summary>
[Fact]
public void PointerOffsetMatchesViewStart()
{
const int MapLength = 4096;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength))
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(1, MapLength - 1))
{
Assert.Equal(1, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength - 1, 1))
{
Assert.Equal(MapLength - 1, acc.PointerOffset);
}
// On Unix creating a view of size zero will result in an offset and capacity
// of 0 due to mmap behavior, whereas on Windows it's possible to create a
// zero-size view anywhere in the created file mapping.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength, 0))
{
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MapLength : 0,
acc.PointerOffset);
}
}
}
}
/// <summary>
/// Test all of the Read/Write accessor methods against a variety of maps and accessors.
/// </summary>
[Theory]
[InlineData(0, 8192)]
[InlineData(8100, 92)]
[InlineData(0, 20)]
[InlineData(1, 8191)]
[InlineData(17, 8175)]
[InlineData(17, 20)]
public void AllReadWriteMethods(long offset, long size)
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(offset, size))
{
AssertWritesReads(acc);
}
}
}
/// <summary>Performs many reads and writes of various data types against the accessor.</summary>
private static unsafe void AssertWritesReads(MemoryMappedViewAccessor acc) // TODO: unsafe can be removed once using C# 6 compiler
{
// Successful reads and writes at the beginning for each data type
AssertWriteRead<bool>(false, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Successful reads and writes at the end for each data type
long end = acc.Capacity;
AssertWriteRead<bool>(false, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, end - sizeof(byte), (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', end - sizeof(char), (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, end - sizeof(decimal), (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, end - sizeof(double), (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, end - sizeof(short), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, end - sizeof(int), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, end - sizeof(long), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, end - sizeof(sbyte), (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, end - sizeof(float), (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, end - sizeof(ushort), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, end - sizeof(uint), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, end - sizeof(ulong), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Failed reads and writes just at the border of the end. This triggers different exception types
// for some types than when we're completely beyond the end.
long beyondEnd = acc.Capacity + 1;
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
// Failed reads and writes well past the end
beyondEnd = acc.Capacity + 20;
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
}
/// <summary>Performs and verifies a read and write against an accessor.</summary>
/// <typeparam name="T">The type of data being read and written.</typeparam>
/// <param name="expected">The data expected to be read.</param>
/// <param name="position">The position of the read and write.</param>
/// <param name="write">The function to perform the write, handed the position at which to write and the value to write.</param>
/// <param name="read">The function to perform the read, handed the position from which to read and returning the read value.</param>
private static void AssertWriteRead<T>(T expected, long position, Action<long, T> write, Func<long, T> read)
{
write(position, expected);
Assert.Equal(expected, read(position));
}
/// <summary>
/// Test to verify that Flush is supported regardless of the accessor's access level
/// </summary>
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite)]
public void FlushSupportedOnBothReadAndWriteAccessors(MemoryMappedFileAccess access)
{
const int Capacity = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(Capacity))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, access))
{
acc.Flush();
}
}
}
/// <summary>
/// Test to validate that multiple accessors over the same map share data appropriately.
/// </summary>
[Fact]
public void ViewsShareData()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create two views over the same map, and verify that data
// written to one is readable by the other.
using (MemoryMappedViewAccessor acc1 = mmf.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
acc1.Write(i, (byte)i);
}
acc1.Flush();
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc2.ReadByte(i));
}
}
// Then verify that after those views have been disposed of,
// we can create another view and still read the same data.
using (MemoryMappedViewAccessor acc3 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc3.ReadByte(i));
}
}
// Finally, make sure such data is also visible to a stream view
// created subsequently from the same map.
using (MemoryMappedViewStream stream4 = mmf.CreateViewStream())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, stream4.ReadByte());
}
}
}
}
}
/// <summary>
/// Test to verify copy-on-write behavior of accessors.
/// </summary>
[Fact]
public void CopyOnWrite()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create a normal view, make sure the original data is there, then write some new data.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.ReadWrite))
{
Assert.Equal(0, acc.ReadInt32(0));
acc.Write(0, 42);
}
// In a CopyOnWrite view, verify the previously written data is there, then write some new data
// and verify it's visible through this view.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.CopyOnWrite))
{
Assert.Equal(42, acc.ReadInt32(0));
acc.Write(0, 84);
Assert.Equal(84, acc.ReadInt32(0));
}
// Finally, verify that the CopyOnWrite data is not visible to others using the map.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.Read))
{
Assert.Equal(42, acc.ReadInt32(0));
}
}
}
}
/// <summary>
/// Test to verify that we can dispose of an accessor multiple times.
/// </summary>
[Fact]
public void DisposeMultipleTimes()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
acc.Dispose();
acc.Dispose();
}
}
}
/// <summary>
/// Test to verify that a view becomes unusable after it's been disposed.
/// </summary>
[Fact]
public void InvalidAfterDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
SafeMemoryMappedViewHandle handle = acc.SafeMemoryMappedViewHandle;
Assert.False(handle.IsClosed);
acc.Dispose();
Assert.True(handle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => acc.ReadByte(0));
Assert.Throws<ObjectDisposedException>(() => acc.Write(0, (byte)0));
Assert.Throws<ObjectDisposedException>(() => acc.Flush());
}
}
}
/// <summary>
/// Test to verify that we can still use a view after the associated map has been disposed.
/// </summary>
[Fact]
public void UseAfterMMFDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
// Create the view, then dispose of the map
MemoryMappedViewAccessor acc;
using (mmf) acc = mmf.CreateViewAccessor();
// Validate we can still use the view
ValidateMemoryMappedViewAccessor(acc, 8192, MemoryMappedFileAccess.ReadWrite);
acc.Dispose();
}
}
/// <summary>
/// Test to allow a map and view to be finalized, just to ensure we don't crash.
/// </summary>
[Fact]
public void AllowFinalization()
{
// Explicitly do not dispose, to allow finalization to happen, just to try to verify
// that nothing fails/throws when it does.
WeakReference<MemoryMappedFile> mmfWeak;
WeakReference<MemoryMappedViewAccessor> mmvaWeak;
CreateWeakMmfAndMmva(out mmfWeak, out mmvaWeak);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
MemoryMappedFile mmf;
Assert.False(mmfWeak.TryGetTarget(out mmf));
MemoryMappedViewAccessor mmva;
Assert.False(mmvaWeak.TryGetTarget(out mmva));
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreateWeakMmfAndMmva(out WeakReference<MemoryMappedFile> mmfWeak, out WeakReference<MemoryMappedViewAccessor> mmvaWeak)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
mmfWeak = new WeakReference<MemoryMappedFile>(mmf);
mmvaWeak = new WeakReference<MemoryMappedViewAccessor>(acc);
}
}
}
| |
// 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 PackSignedSaturateInt16()
{
var test = new SimpleBinaryOpTest__PackSignedSaturateInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__PackSignedSaturateInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__PackSignedSaturateInt16 testClass)
{
var result = Avx2.PackSignedSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__PackSignedSaturateInt16 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.PackSignedSaturate(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__PackSignedSaturateInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleBinaryOpTest__PackSignedSaturateInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.PackSignedSaturate(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.PackSignedSaturate(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.PackSignedSaturate(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.PackSignedSaturate), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.PackSignedSaturate), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.PackSignedSaturate), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.PackSignedSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.PackSignedSaturate(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.PackSignedSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.PackSignedSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.PackSignedSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__PackSignedSaturateInt16();
var result = Avx2.PackSignedSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__PackSignedSaturateInt16();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx2.PackSignedSaturate(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.PackSignedSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.PackSignedSaturate(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.PackSignedSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.PackSignedSaturate(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (short)Math.Clamp(left[0], short.MinValue, short.MaxValue))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 4 ? (short)Math.Clamp(left[i], short.MinValue, short.MaxValue) : (i < 8 && i > 3 ? (short)Math.Clamp(right[i%4], short.MinValue, short.MaxValue) : (i < 12 && i > 7 ? (short)Math.Clamp(left[i-4], short.MinValue, short.MaxValue) : (short)Math.Clamp(right[i-8], short.MinValue, short.MaxValue)))))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.PackSignedSaturate)}<Int16>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace CSharpMath.Editor {
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Timers;
using Atom;
using Display;
using Display.FrontEnd;
using Structures;
using Atoms = Atom.Atoms;
public class MathKeyboard<TFont, TGlyph> : IDisposable where TFont : IFont<TGlyph> {
protected Timer blinkTimer;
public const double DefaultBlinkMilliseconds = 800;
public MathKeyboard(TypesettingContext<TFont, TGlyph> context, TFont font, double blinkMilliseconds = DefaultBlinkMilliseconds) {
Context = context;
Font = font;
blinkTimer = new Timer(blinkMilliseconds);
blinkTimer.Elapsed += (sender, e) => {
if (!(MathList.AtomAt(_insertionIndex) is Atoms.Placeholder) || LaTeXSettings.PlaceholderBlinks)
InsertionPositionHighlighted = !InsertionPositionHighlighted;
};
blinkTimer.Start();
}
public bool ShouldDrawCaret => InsertionPositionHighlighted && !(MathList.AtomAt(_insertionIndex) is Atoms.Placeholder);
public void StartBlinking() => blinkTimer.Start();
public void StopBlinking() => blinkTimer.Stop();
protected TypesettingContext<TFont, TGlyph> Context { get; }
static void ResetPlaceholders(MathList mathList) {
foreach (var mathAtom in mathList.Atoms) {
ResetPlaceholders(mathAtom.Superscript);
ResetPlaceholders(mathAtom.Subscript);
switch (mathAtom) {
case Atoms.Placeholder placeholder:
placeholder.Color = LaTeXSettings.PlaceholderRestingColor;
placeholder.Nucleus = LaTeXSettings.PlaceholderRestingNucleus;
break;
case IMathListContainer container:
foreach (var list in container.InnerLists)
ResetPlaceholders(list);
break;
}
}
}
bool _insertionPositionHighlighted;
public bool InsertionPositionHighlighted {
get => _insertionPositionHighlighted;
set {
blinkTimer.Stop();
blinkTimer.Start();
_insertionPositionHighlighted = value;
if (MathList.AtomAt(_insertionIndex) is Atoms.Placeholder placeholder) {
(placeholder.Nucleus, placeholder.Color) =
_insertionPositionHighlighted
? (LaTeXSettings.PlaceholderActiveNucleus, LaTeXSettings.PlaceholderActiveColor)
: (LaTeXSettings.PlaceholderRestingNucleus, LaTeXSettings.PlaceholderRestingColor);
}
RecreateDisplayFromMathList();
RedrawRequested?.Invoke(this, EventArgs.Empty);
}
}
public Display.Displays.ListDisplay<TFont, TGlyph>? Display { get; protected set; }
public MathList MathList { get; } = new MathList();
public string LaTeX => LaTeXParser.MathListToLaTeX(MathList).ToString();
private MathListIndex _insertionIndex = MathListIndex.Level0Index(0);
public MathListIndex InsertionIndex {
get => _insertionIndex;
set {
_insertionIndex = value;
ResetPlaceholders(MathList);
InsertionPositionHighlighted = true;
}
}
public TFont Font { get; set; }
public LineStyle LineStyle { get; set; }
public Color SelectColor { get; set; }
public virtual RectangleF Measure => Display?.DisplayBounds() ?? RectangleF.Empty;
public bool HasText => MathList?.Atoms?.Count > 0;
public void RecreateDisplayFromMathList() {
var position = Display?.Position ?? default;
Display = Typesetter.CreateLine(MathList, Font, Context, LineStyle);
Display.Position = position;
}
/// <summary>Keyboard should now be hidden and input be discarded.</summary>
public event EventHandler? DismissPressed;
/// <summary>Keyboard should now be hidden and input be saved.</summary>
public event EventHandler? ReturnPressed;
/// <summary><see cref="Display"/> should be redrawn.</summary>
public event EventHandler? RedrawRequested;
public PointF? ClosestPointToIndex(MathListIndex index) =>
Display?.PointForIndex(Context, index);
public MathListIndex? ClosestIndexToPoint(PointF point) =>
Display?.IndexForPoint(Context, point);
public void KeyPress(params MathKeyboardInput[] inputs) {
foreach (var input in inputs) KeyPress(input);
}
public void KeyPress(MathKeyboardInput input) {
void HandleScriptButton(bool isSuperScript) {
var subIndexType = isSuperScript ? MathListSubIndexType.Superscript : MathListSubIndexType.Subscript;
MathList GetScript(MathAtom atom) => isSuperScript ? atom.Superscript : atom.Subscript;
void SetScript(MathAtom atom, MathList value) => GetScript(atom).Append(value);
void CreateEmptyAtom() {
// Create an empty atom and move the insertion index up.
var emptyAtom = LaTeXSettings.Placeholder;
SetScript(emptyAtom, LaTeXSettings.PlaceholderList);
MathList.InsertAndAdvance(ref _insertionIndex, emptyAtom, subIndexType);
}
static bool IsFullPlaceholderRequired(MathAtom mathAtom) =>
mathAtom switch
{
Atoms.BinaryOperator _ => true,
Atoms.UnaryOperator _ => true,
Atoms.Relation _ => true,
Atoms.Open _ => true,
Atoms.Punctuation _ => true,
_ => false
};
if (!(_insertionIndex.Previous is MathListIndex previous)) {
CreateEmptyAtom();
} else {
var isBetweenBaseAndScripts =
_insertionIndex.FinalSubIndexType is MathListSubIndexType.BetweenBaseAndScripts;
var prevIndexCorrected =
isBetweenBaseAndScripts
? _insertionIndex.LevelDown()
?? throw new InvalidCodePathException("BetweenBaseAndScripts index has null LevelDown")
: previous;
var prevAtom = MathList.AtomAt(prevIndexCorrected);
if (prevAtom is null)
throw new InvalidCodePathException("prevAtom is null");
if (!isBetweenBaseAndScripts && IsFullPlaceholderRequired(prevAtom)) {
CreateEmptyAtom();
} else {
var script = GetScript(prevAtom);
if (script.IsEmpty()) {
SetScript(prevAtom, LaTeXSettings.PlaceholderList);
}
_insertionIndex = prevIndexCorrected.LevelUpWithSubIndex
(subIndexType, MathListIndex.Level0Index(0));
}
}
}
void HandleSlashButton() {
// special / handling - makes the thing a fraction
var numerator = new Stack<MathAtom>();
var parenDepth = 0;
if (_insertionIndex.FinalSubIndexType == MathListSubIndexType.BetweenBaseAndScripts)
_insertionIndex = _insertionIndex.LevelDown()?.Next
?? throw new InvalidCodePathException("_insertionIndex.LevelDown() returned null");
for (; _insertionIndex.Previous != null; _insertionIndex = _insertionIndex.Previous) {
switch (MathList.AtomAt(_insertionIndex.Previous), parenDepth) {
case (null, _): throw new InvalidCodePathException("Invalid _insertionIndex");
// Stop looking behind upon encountering these atoms unparenthesized
case (Atoms.Open _, _) when --parenDepth < 0: goto stop;
case (Atoms.Close a, _): parenDepth++; numerator.Push(a); break;
case (Atoms.UnaryOperator _, 0): goto stop;
case (Atoms.BinaryOperator _, 0): goto stop;
case (Atoms.Relation _, 0): goto stop;
case (Atoms.Fraction _, 0): goto stop;
case (Atoms.Open _, _) when parenDepth < 0: goto stop;
// We don't put this atom on the fraction
case (var a, _): numerator.Push(a); break;
}
}
stop: MathList.RemoveAtoms(new MathListRange(_insertionIndex, numerator.Count));
if (numerator.Count == 0)
// so we didn't really find any numbers before this, so make the numerator 1
numerator.Push(new Atoms.Number("1"));
if (MathList.AtomAt(_insertionIndex.Previous) is Atoms.Fraction)
// Add a times symbol
MathList.InsertAndAdvance(ref _insertionIndex, LaTeXSettings.Times, MathListSubIndexType.None);
MathList.InsertAndAdvance(ref _insertionIndex, new Atoms.Fraction(
new MathList(numerator),
LaTeXSettings.PlaceholderList
), MathListSubIndexType.Denominator);
}
void InsertInner(string left, string right) =>
MathList.InsertAndAdvance(ref _insertionIndex,
new Atoms.Inner(new Boundary(left), LaTeXSettings.PlaceholderList, new Boundary(right)),
MathListSubIndexType.Inner);
void MoveCursorLeft() {
var prev = _insertionIndex.Previous;
switch (MathList.AtomAt(prev)) {
case var _ when prev is null:
case null: // At beginning of line
var levelDown = _insertionIndex.LevelDown();
switch (_insertionIndex.FinalSubIndexType) {
case MathListSubIndexType.None:
goto default;
case var _ when levelDown is null:
throw new InvalidCodePathException("Null levelDown despite non-None FinalSubIndexType");
case MathListSubIndexType.Superscript:
var scriptAtom = MathList.AtomAt(levelDown);
if (scriptAtom is null)
throw new InvalidCodePathException("Invalid levelDown");
if (scriptAtom.Subscript.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Subscript,
MathListIndex.Level0Index(scriptAtom.Subscript.Count));
else
goto case MathListSubIndexType.Subscript;
break;
case MathListSubIndexType.Subscript:
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.BetweenBaseAndScripts, MathListIndex.Level0Index(1));
break;
case MathListSubIndexType.BetweenBaseAndScripts:
if (MathList.AtomAt(levelDown) is Atoms.Radical rad && rad.Radicand.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Radicand,
MathListIndex.Level0Index(rad.Radicand.Count));
else if (MathList.AtomAt(levelDown) is Atoms.Fraction frac && frac.Denominator.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Denominator,
MathListIndex.Level0Index(frac.Denominator.Count));
else if (MathList.AtomAt(levelDown) is Atoms.Inner inner && inner.InnerList.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Inner,
MathListIndex.Level0Index(inner.InnerList.Count));
else goto case MathListSubIndexType.Radicand;
break;
case MathListSubIndexType.Radicand:
if (MathList.AtomAt(levelDown) is Atoms.Radical radDeg && radDeg.Degree.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Degree, MathListIndex.Level0Index(radDeg.Degree.Count));
else
goto case MathListSubIndexType.Denominator;
break;
case MathListSubIndexType.Denominator:
if (MathList.AtomAt(levelDown) is Atoms.Fraction fracNum && fracNum.Numerator.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Numerator, MathListIndex.Level0Index(fracNum.Numerator.Count));
else
goto default;
break;
case MathListSubIndexType.Degree:
case MathListSubIndexType.Numerator:
case MathListSubIndexType.Inner:
default:
_insertionIndex = levelDown ?? _insertionIndex;
break;
}
break;
case { Superscript: var s } when s.IsNonEmpty():
_insertionIndex = prev.LevelUpWithSubIndex
(MathListSubIndexType.Superscript, MathListIndex.Level0Index(s.Count));
break;
case { Subscript: var s } when s.IsNonEmpty():
_insertionIndex = prev.LevelUpWithSubIndex
(MathListSubIndexType.Subscript, MathListIndex.Level0Index(s.Count));
break;
case Atoms.Inner { InnerList: var l }:
_insertionIndex = prev.LevelUpWithSubIndex
(MathListSubIndexType.Inner, MathListIndex.Level0Index(l.Count));
break;
case Atoms.Radical { Radicand: var r }:
_insertionIndex = prev.LevelUpWithSubIndex
(MathListSubIndexType.Radicand, MathListIndex.Level0Index(r.Count));
break;
case Atoms.Fraction { Denominator: var d }:
_insertionIndex = prev.LevelUpWithSubIndex
(MathListSubIndexType.Denominator, MathListIndex.Level0Index(d.Count));
break;
default:
_insertionIndex = prev;
break;
}
if (_insertionIndex is null)
throw new InvalidOperationException($"{nameof(_insertionIndex)} is null.");
if (_insertionIndex.FinalSubIndexType is MathListSubIndexType.BetweenBaseAndScripts) {
var prevInd = _insertionIndex.LevelDown();
if (prevInd != null && MathList.AtomAt(prevInd) is Atoms.Placeholder)
_insertionIndex = prevInd;
} else if (MathList.AtomAt(_insertionIndex) is null
&& _insertionIndex?.Previous is MathListIndex previous) {
if (MathList.AtomAt(previous) is Atoms.Placeholder p && p.Superscript.IsEmpty() && p.Subscript.IsEmpty())
_insertionIndex = previous; // Skip right side of placeholders when end of line
}
}
void MoveCursorRight() {
if (_insertionIndex is null)
throw new InvalidOperationException($"{nameof(_insertionIndex)} is null.");
switch (MathList.AtomAt(_insertionIndex)) {
case null: //After Count
var levelDown = _insertionIndex.LevelDown();
var levelDownAtom = MathList.AtomAt(levelDown);
switch (_insertionIndex.FinalSubIndexType) {
case MathListSubIndexType.None:
goto default;
case var _ when levelDown is null:
throw new InvalidCodePathException("Null levelDown despite non-None FinalSubIndexType");
case var _ when levelDownAtom is null:
throw new InvalidCodePathException("Invalid levelDown");
case MathListSubIndexType.Degree:
if (levelDownAtom is Atoms.Radical)
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Radicand, MathListIndex.Level0Index(0));
else
throw new SubIndexTypeMismatchException(typeof(Atoms.Radical), levelDown);
break;
case MathListSubIndexType.Numerator:
if (levelDownAtom is Atoms.Fraction)
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Denominator, MathListIndex.Level0Index(0));
else
throw new SubIndexTypeMismatchException(typeof(Atoms.Fraction), levelDown);
break;
case MathListSubIndexType.Radicand:
case MathListSubIndexType.Denominator:
case MathListSubIndexType.Inner:
if (levelDownAtom.Superscript.IsNonEmpty() || levelDownAtom.Subscript.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.BetweenBaseAndScripts, MathListIndex.Level0Index(1));
else
goto default;
break;
case MathListSubIndexType.BetweenBaseAndScripts:
if (levelDownAtom.Subscript.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Subscript, MathListIndex.Level0Index(0));
else
goto case MathListSubIndexType.Subscript;
break;
case MathListSubIndexType.Subscript:
if (levelDownAtom.Superscript.IsNonEmpty())
_insertionIndex = levelDown.LevelUpWithSubIndex
(MathListSubIndexType.Superscript, MathListIndex.Level0Index(0));
else
goto default;
break;
case MathListSubIndexType.Superscript:
default:
_insertionIndex = levelDown?.Next ?? _insertionIndex;
break;
}
break;
case var a when _insertionIndex.FinalSubIndexType is MathListSubIndexType.BetweenBaseAndScripts:
levelDown = _insertionIndex.LevelDown();
if (levelDown is null)
throw new InvalidCodePathException
("_insertionIndex.FinalSubIndexType is BetweenBaseAndScripts but levelDown is null");
_insertionIndex = levelDown.LevelUpWithSubIndex(
a.Subscript.IsNonEmpty() ? MathListSubIndexType.Subscript : MathListSubIndexType.Superscript,
MathListIndex.Level0Index(0));
break;
case Atoms.Inner _:
_insertionIndex = _insertionIndex.LevelUpWithSubIndex(MathListSubIndexType.Inner, MathListIndex.Level0Index(0));
break;
case Atoms.Fraction _:
_insertionIndex = _insertionIndex.LevelUpWithSubIndex
(MathListSubIndexType.Numerator, MathListIndex.Level0Index(0));
break;
case Atoms.Radical rad:
_insertionIndex = _insertionIndex.LevelUpWithSubIndex(
rad.Degree.IsNonEmpty() ? MathListSubIndexType.Degree : MathListSubIndexType.Radicand,
MathListIndex.Level0Index(0));
break;
case var a when a.Superscript.IsNonEmpty() || a.Subscript.IsNonEmpty():
_insertionIndex = _insertionIndex.LevelUpWithSubIndex
(MathListSubIndexType.BetweenBaseAndScripts, MathListIndex.Level0Index(1));
break;
case Atoms.Placeholder _ when MathList.AtomAt(_insertionIndex.Next) is null:
// Skip right side of placeholders when end of line
goto case null;
default:
_insertionIndex = _insertionIndex.Next;
break;
}
if (_insertionIndex is null)
throw new InvalidOperationException($"{nameof(_insertionIndex)} is null.");
if (_insertionIndex.FinalSubIndexType is MathListSubIndexType.BetweenBaseAndScripts
&& MathList.AtomAt(_insertionIndex.LevelDown()) is Atoms.Placeholder)
MoveCursorRight();
}
void DeleteBackwards() {
// delete the last atom from the list
if (HasText && _insertionIndex.Previous is MathListIndex previous) {
_insertionIndex = previous;
MathList.RemoveAt(ref _insertionIndex);
}
}
static bool IsPlaceholderList(MathList ml) => ml.Count == 1 && ml[0] is Atoms.Placeholder;
void InsertAtom(MathAtom a) =>
MathList.InsertAndAdvance(ref _insertionIndex, a,
a switch
{
Atoms.Fraction _ => MathListSubIndexType.Numerator,
Atoms.Radical { Degree: { } d } when IsPlaceholderList(d) => MathListSubIndexType.Degree,
Atoms.Radical _ => MathListSubIndexType.Radicand,
_ => MathListSubIndexType.None
});
void InsertSymbolName(string name, bool subscript = false, bool superscript = false) {
var atom =
LaTeXSettings.AtomForCommand(name) ??
throw new InvalidCodePathException("Looks like someone mistyped a symbol name...");
InsertAtom(atom);
switch (subscript, superscript) {
case (true, true):
HandleScriptButton(true);
_insertionIndex = _insertionIndex.LevelDown()?.Next
?? throw new InvalidCodePathException(
"_insertionIndex.Previous returned null despite script button handling");
HandleScriptButton(false);
break;
case (false, true):
HandleScriptButton(true);
break;
case (true, false):
HandleScriptButton(false);
break;
case (false, false):
break;
}
}
switch (input) {
// TODO: Implement up/down buttons
case MathKeyboardInput.Up:
break;
case MathKeyboardInput.Down:
break;
case MathKeyboardInput.Left:
MoveCursorLeft();
break;
case MathKeyboardInput.Right:
MoveCursorRight();
break;
case MathKeyboardInput.Backspace:
DeleteBackwards();
break;
case MathKeyboardInput.Clear:
MathList.Clear();
InsertionIndex = MathListIndex.Level0Index(0);
break;
case MathKeyboardInput.Return:
ReturnPressed?.Invoke(this, EventArgs.Empty);
InsertionPositionHighlighted = false;
StopBlinking();
return;
case MathKeyboardInput.Dismiss:
DismissPressed?.Invoke(this, EventArgs.Empty);
InsertionPositionHighlighted = false;
StopBlinking();
return;
case MathKeyboardInput.Slash:
HandleSlashButton();
break;
case MathKeyboardInput.Power:
HandleScriptButton(true);
break;
case MathKeyboardInput.Subscript:
HandleScriptButton(false);
break;
case MathKeyboardInput.Fraction:
InsertAtom(new Atoms.Fraction(LaTeXSettings.PlaceholderList, LaTeXSettings.PlaceholderList));
break;
case MathKeyboardInput.SquareRoot:
InsertAtom(new Atoms.Radical(new MathList(), LaTeXSettings.PlaceholderList));
break;
case MathKeyboardInput.CubeRoot:
InsertAtom(new Atoms.Radical(new MathList(new Atoms.Number("3")), LaTeXSettings.PlaceholderList));
break;
case MathKeyboardInput.NthRoot:
InsertAtom(new Atoms.Radical(LaTeXSettings.PlaceholderList, LaTeXSettings.PlaceholderList));
break;
case MathKeyboardInput.BothRoundBrackets:
InsertInner("(", ")");
break;
case MathKeyboardInput.BothSquareBrackets:
InsertInner("[", "]");
break;
case MathKeyboardInput.BothCurlyBrackets:
InsertInner("{", "}");
break;
case MathKeyboardInput.Absolute:
InsertInner("|", "|");
break;
case MathKeyboardInput.BaseEPower:
InsertAtom(LaTeXSettings.AtomForCommand("e")
?? throw new InvalidCodePathException($"{nameof(LaTeXSettings.AtomForCommand)} returned null for e"));
HandleScriptButton(true);
break;
case MathKeyboardInput.Logarithm:
InsertSymbolName(@"\log");
break;
case MathKeyboardInput.NaturalLogarithm:
InsertSymbolName(@"\ln");
break;
case MathKeyboardInput.LogarithmWithBase:
InsertSymbolName(@"\log", subscript: true);
break;
case MathKeyboardInput.Sine:
InsertSymbolName(@"\sin");
break;
case MathKeyboardInput.Cosine:
InsertSymbolName(@"\cos");
break;
case MathKeyboardInput.Tangent:
InsertSymbolName(@"\tan");
break;
case MathKeyboardInput.Cotangent:
InsertSymbolName(@"\cot");
break;
case MathKeyboardInput.Secant:
InsertSymbolName(@"\sec");
break;
case MathKeyboardInput.Cosecant:
InsertSymbolName(@"\csc");
break;
case MathKeyboardInput.ArcSine:
InsertSymbolName(@"\arcsin");
break;
case MathKeyboardInput.ArcCosine:
InsertSymbolName(@"\arccos");
break;
case MathKeyboardInput.ArcTangent:
InsertSymbolName(@"\arctan");
break;
case MathKeyboardInput.ArcCotangent:
InsertSymbolName(@"\arccot");
break;
case MathKeyboardInput.ArcSecant:
InsertSymbolName(@"\arcsec");
break;
case MathKeyboardInput.ArcCosecant:
InsertSymbolName(@"\arccsc");
break;
case MathKeyboardInput.HyperbolicSine:
InsertSymbolName(@"\sinh");
break;
case MathKeyboardInput.HyperbolicCosine:
InsertSymbolName(@"\cosh");
break;
case MathKeyboardInput.HyperbolicTangent:
InsertSymbolName(@"\tanh");
break;
case MathKeyboardInput.HyperbolicCotangent:
InsertSymbolName(@"\coth");
break;
case MathKeyboardInput.HyperbolicSecant:
InsertSymbolName(@"\sech");
break;
case MathKeyboardInput.HyperbolicCosecant:
InsertSymbolName(@"\csch");
break;
case MathKeyboardInput.AreaHyperbolicSine:
InsertSymbolName(@"\arsinh");
break;
case MathKeyboardInput.AreaHyperbolicCosine:
InsertSymbolName(@"\arcosh");
break;
case MathKeyboardInput.AreaHyperbolicTangent:
InsertSymbolName(@"\artanh");
break;
case MathKeyboardInput.AreaHyperbolicCotangent:
InsertSymbolName(@"\arcoth");
break;
case MathKeyboardInput.AreaHyperbolicSecant:
InsertSymbolName(@"\arsech");
break;
case MathKeyboardInput.AreaHyperbolicCosecant:
InsertSymbolName(@"\arcsch");
break;
case MathKeyboardInput.LimitWithBase:
InsertSymbolName(@"\lim", subscript: true);
break;
case MathKeyboardInput.Integral:
InsertSymbolName(@"\int");
break;
case MathKeyboardInput.IntegralLowerLimit:
InsertSymbolName(@"\int", subscript: true);
break;
case MathKeyboardInput.IntegralUpperLimit:
InsertSymbolName(@"\int", superscript: true);
break;
case MathKeyboardInput.IntegralBothLimits:
InsertSymbolName(@"\int", subscript: true, superscript: true);
break;
case MathKeyboardInput.Summation:
InsertSymbolName(@"\sum");
break;
case MathKeyboardInput.SummationLowerLimit:
InsertSymbolName(@"\sum", subscript: true);
break;
case MathKeyboardInput.SummationUpperLimit:
InsertSymbolName(@"\sum", superscript: true);
break;
case MathKeyboardInput.SummationBothLimits:
InsertSymbolName(@"\sum", subscript: true, superscript: true);
break;
case MathKeyboardInput.Product:
InsertSymbolName(@"\prod");
break;
case MathKeyboardInput.ProductLowerLimit:
InsertSymbolName(@"\prod", subscript: true);
break;
case MathKeyboardInput.ProductUpperLimit:
InsertSymbolName(@"\prod", superscript: true);
break;
case MathKeyboardInput.ProductBothLimits:
InsertSymbolName(@"\prod", subscript: true, superscript: true);
break;
case MathKeyboardInput.DoubleIntegral:
InsertSymbolName(@"\iint");
break;
case MathKeyboardInput.TripleIntegral:
InsertSymbolName(@"\iiint");
break;
case MathKeyboardInput.QuadrupleIntegral:
InsertSymbolName(@"\iiiint");
break;
case MathKeyboardInput.ContourIntegral:
InsertSymbolName(@"\oint");
break;
case MathKeyboardInput.DoubleContourIntegral:
InsertSymbolName(@"\oiint");
break;
case MathKeyboardInput.TripleContourIntegral:
InsertSymbolName(@"\oiiint");
break;
case MathKeyboardInput.ClockwiseIntegral:
InsertSymbolName(@"\intclockwise");
break;
case MathKeyboardInput.ClockwiseContourIntegral:
InsertSymbolName(@"\varointclockwise");
break;
case MathKeyboardInput.CounterClockwiseContourIntegral:
InsertSymbolName(@"\ointctrclockwise");
break;
case MathKeyboardInput.LeftArrow:
InsertSymbolName(@"\leftarrow");
break;
case MathKeyboardInput.UpArrow:
InsertSymbolName(@"\uparrow");
break;
case MathKeyboardInput.RightArrow:
InsertSymbolName(@"\rightarrow");
break;
case MathKeyboardInput.DownArrow:
InsertSymbolName(@"\downarrow");
break;
case MathKeyboardInput.PartialDifferential:
InsertSymbolName(@"\partial");
break;
case MathKeyboardInput.NotEquals:
InsertSymbolName(@"\neq");
break;
case MathKeyboardInput.LessOrEquals:
InsertSymbolName(@"\leq");
break;
case MathKeyboardInput.GreaterOrEquals:
InsertSymbolName(@"\geq");
break;
case MathKeyboardInput.Multiply:
InsertSymbolName(@"\times");
break;
case MathKeyboardInput.Divide:
InsertSymbolName(@"\div");
break;
case MathKeyboardInput.Infinity:
InsertSymbolName(@"\infty");
break;
case MathKeyboardInput.Degree:
InsertSymbolName(@"\degree");
break;
case MathKeyboardInput.Angle:
InsertSymbolName(@"\angle");
break;
case MathKeyboardInput.LeftCurlyBracket:
InsertSymbolName(@"\{");
break;
case MathKeyboardInput.RightCurlyBracket:
InsertSymbolName(@"\}");
break;
case MathKeyboardInput.Percentage:
InsertSymbolName(@"\%");
break;
case MathKeyboardInput.Space:
InsertSymbolName(@"\ ");
break;
case MathKeyboardInput.Prime:
InsertAtom(new Atoms.Prime(1));
break;
case MathKeyboardInput.LeftRoundBracket:
case MathKeyboardInput.RightRoundBracket:
case MathKeyboardInput.LeftSquareBracket:
case MathKeyboardInput.RightSquareBracket:
case MathKeyboardInput.D0:
case MathKeyboardInput.D1:
case MathKeyboardInput.D2:
case MathKeyboardInput.D3:
case MathKeyboardInput.D4:
case MathKeyboardInput.D5:
case MathKeyboardInput.D6:
case MathKeyboardInput.D7:
case MathKeyboardInput.D8:
case MathKeyboardInput.D9:
case MathKeyboardInput.Decimal:
case MathKeyboardInput.Plus:
case MathKeyboardInput.Minus:
case MathKeyboardInput.Ratio:
case MathKeyboardInput.Comma:
case MathKeyboardInput.Semicolon:
case MathKeyboardInput.Factorial:
case MathKeyboardInput.VerticalBar:
case MathKeyboardInput.Equals:
case MathKeyboardInput.LessThan:
case MathKeyboardInput.GreaterThan:
case MathKeyboardInput.A:
case MathKeyboardInput.B:
case MathKeyboardInput.C:
case MathKeyboardInput.D:
case MathKeyboardInput.E:
case MathKeyboardInput.F:
case MathKeyboardInput.G:
case MathKeyboardInput.H:
case MathKeyboardInput.I:
case MathKeyboardInput.J:
case MathKeyboardInput.K:
case MathKeyboardInput.L:
case MathKeyboardInput.M:
case MathKeyboardInput.N:
case MathKeyboardInput.O:
case MathKeyboardInput.P:
case MathKeyboardInput.Q:
case MathKeyboardInput.R:
case MathKeyboardInput.S:
case MathKeyboardInput.T:
case MathKeyboardInput.U:
case MathKeyboardInput.V:
case MathKeyboardInput.W:
case MathKeyboardInput.X:
case MathKeyboardInput.Y:
case MathKeyboardInput.Z:
case MathKeyboardInput.SmallA:
case MathKeyboardInput.SmallB:
case MathKeyboardInput.SmallC:
case MathKeyboardInput.SmallD:
case MathKeyboardInput.SmallE:
case MathKeyboardInput.SmallF:
case MathKeyboardInput.SmallG:
case MathKeyboardInput.SmallH:
case MathKeyboardInput.SmallI:
case MathKeyboardInput.SmallJ:
case MathKeyboardInput.SmallK:
case MathKeyboardInput.SmallL:
case MathKeyboardInput.SmallM:
case MathKeyboardInput.SmallN:
case MathKeyboardInput.SmallO:
case MathKeyboardInput.SmallP:
case MathKeyboardInput.SmallQ:
case MathKeyboardInput.SmallR:
case MathKeyboardInput.SmallS:
case MathKeyboardInput.SmallT:
case MathKeyboardInput.SmallU:
case MathKeyboardInput.SmallV:
case MathKeyboardInput.SmallW:
case MathKeyboardInput.SmallX:
case MathKeyboardInput.SmallY:
case MathKeyboardInput.SmallZ:
InsertAtom(LaTeXSettings.AtomForCommand(new string((char)input, 1))
?? throw new InvalidCodePathException($"{nameof(LaTeXSettings.AtomForCommand)} returned null for {input}"));
break;
case MathKeyboardInput.Alpha:
case MathKeyboardInput.Beta:
case MathKeyboardInput.Gamma:
case MathKeyboardInput.Delta:
case MathKeyboardInput.Epsilon:
case MathKeyboardInput.Zeta:
case MathKeyboardInput.Eta:
case MathKeyboardInput.Theta:
case MathKeyboardInput.Iota:
case MathKeyboardInput.Kappa:
case MathKeyboardInput.Lambda:
case MathKeyboardInput.Mu:
case MathKeyboardInput.Nu:
case MathKeyboardInput.Xi:
case MathKeyboardInput.Omicron:
case MathKeyboardInput.Pi:
case MathKeyboardInput.Rho:
case MathKeyboardInput.Sigma:
case MathKeyboardInput.Tau:
case MathKeyboardInput.Upsilon:
case MathKeyboardInput.Phi:
case MathKeyboardInput.Chi:
case MathKeyboardInput.Psi:
case MathKeyboardInput.Omega:
case MathKeyboardInput.SmallAlpha:
case MathKeyboardInput.SmallBeta:
case MathKeyboardInput.SmallGamma:
case MathKeyboardInput.SmallDelta:
case MathKeyboardInput.SmallEpsilon:
case MathKeyboardInput.SmallEpsilon2:
case MathKeyboardInput.SmallZeta:
case MathKeyboardInput.SmallEta:
case MathKeyboardInput.SmallTheta:
case MathKeyboardInput.SmallIota:
case MathKeyboardInput.SmallKappa:
case MathKeyboardInput.SmallKappa2:
case MathKeyboardInput.SmallLambda:
case MathKeyboardInput.SmallMu:
case MathKeyboardInput.SmallNu:
case MathKeyboardInput.SmallXi:
case MathKeyboardInput.SmallOmicron:
case MathKeyboardInput.SmallPi:
case MathKeyboardInput.SmallPi2:
case MathKeyboardInput.SmallRho:
case MathKeyboardInput.SmallRho2:
case MathKeyboardInput.SmallSigma:
case MathKeyboardInput.SmallSigma2:
case MathKeyboardInput.SmallTau:
case MathKeyboardInput.SmallUpsilon:
case MathKeyboardInput.SmallPhi:
case MathKeyboardInput.SmallPhi2:
case MathKeyboardInput.SmallChi:
case MathKeyboardInput.SmallPsi:
case MathKeyboardInput.SmallOmega:
// All Greek letters are rendered as variables.
InsertAtom(new Atoms.Variable(((char)input).ToStringInvariant()));
break;
default:
break;
}
ResetPlaceholders(MathList);
InsertionPositionHighlighted = true;
}
public void MoveCaretToPoint(PointF point) {
point.Y *= -1; //inverted canvas, blah blah
InsertionIndex = ClosestIndexToPoint(point) ?? MathListIndex.Level0Index(MathList.Atoms.Count);
}
public void Clear() {
MathList.Clear();
InsertionIndex = MathListIndex.Level0Index(0);
}
// Insert a list at a given point.
public void InsertMathList(MathList list, PointF point) {
var detailedIndex = ClosestIndexToPoint(point) ?? MathListIndex.Level0Index(0);
// insert at the given index - but don't consider sublevels at this point
var index = MathListIndex.Level0Index(detailedIndex.AtomIndex);
foreach (var atom in list.Atoms) {
MathList.InsertAndAdvance(ref index, atom, MathListSubIndexType.None);
}
InsertionIndex = index; // move the index to the end of the new list.
}
public void HighlightCharacterAt(MathListIndex index, Color color) {
// setup highlights before drawing the MTLine
Display?.HighlightCharacterAt(index, color);
RedrawRequested?.Invoke(this, EventArgs.Empty);
}
public void ClearHighlights() {
RecreateDisplayFromMathList();
RedrawRequested?.Invoke(this, EventArgs.Empty);
}
public void Dispose() {
((IDisposable)blinkTimer).Dispose();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Talent.V4.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedTenantServiceClientSnippets
{
/// <summary>Snippet for CreateTenant</summary>
public void CreateTenantRequestObject()
{
// Snippet: CreateTenant(CreateTenantRequest, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
// Make the request
Tenant response = tenantServiceClient.CreateTenant(request);
// End snippet
}
/// <summary>Snippet for CreateTenantAsync</summary>
public async Task CreateTenantRequestObjectAsync()
{
// Snippet: CreateTenantAsync(CreateTenantRequest, CallSettings)
// Additional: CreateTenantAsync(CreateTenantRequest, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
// Make the request
Tenant response = await tenantServiceClient.CreateTenantAsync(request);
// End snippet
}
/// <summary>Snippet for CreateTenant</summary>
public void CreateTenant()
{
// Snippet: CreateTenant(string, Tenant, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
Tenant tenant = new Tenant();
// Make the request
Tenant response = tenantServiceClient.CreateTenant(parent, tenant);
// End snippet
}
/// <summary>Snippet for CreateTenantAsync</summary>
public async Task CreateTenantAsync()
{
// Snippet: CreateTenantAsync(string, Tenant, CallSettings)
// Additional: CreateTenantAsync(string, Tenant, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
Tenant tenant = new Tenant();
// Make the request
Tenant response = await tenantServiceClient.CreateTenantAsync(parent, tenant);
// End snippet
}
/// <summary>Snippet for CreateTenant</summary>
public void CreateTenantResourceNames()
{
// Snippet: CreateTenant(ProjectName, Tenant, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
Tenant tenant = new Tenant();
// Make the request
Tenant response = tenantServiceClient.CreateTenant(parent, tenant);
// End snippet
}
/// <summary>Snippet for CreateTenantAsync</summary>
public async Task CreateTenantResourceNamesAsync()
{
// Snippet: CreateTenantAsync(ProjectName, Tenant, CallSettings)
// Additional: CreateTenantAsync(ProjectName, Tenant, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
Tenant tenant = new Tenant();
// Make the request
Tenant response = await tenantServiceClient.CreateTenantAsync(parent, tenant);
// End snippet
}
/// <summary>Snippet for GetTenant</summary>
public void GetTenantRequestObject()
{
// Snippet: GetTenant(GetTenantRequest, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
// Make the request
Tenant response = tenantServiceClient.GetTenant(request);
// End snippet
}
/// <summary>Snippet for GetTenantAsync</summary>
public async Task GetTenantRequestObjectAsync()
{
// Snippet: GetTenantAsync(GetTenantRequest, CallSettings)
// Additional: GetTenantAsync(GetTenantRequest, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
// Make the request
Tenant response = await tenantServiceClient.GetTenantAsync(request);
// End snippet
}
/// <summary>Snippet for GetTenant</summary>
public void GetTenant()
{
// Snippet: GetTenant(string, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]";
// Make the request
Tenant response = tenantServiceClient.GetTenant(name);
// End snippet
}
/// <summary>Snippet for GetTenantAsync</summary>
public async Task GetTenantAsync()
{
// Snippet: GetTenantAsync(string, CallSettings)
// Additional: GetTenantAsync(string, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]";
// Make the request
Tenant response = await tenantServiceClient.GetTenantAsync(name);
// End snippet
}
/// <summary>Snippet for GetTenant</summary>
public void GetTenantResourceNames()
{
// Snippet: GetTenant(TenantName, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
// Make the request
Tenant response = tenantServiceClient.GetTenant(name);
// End snippet
}
/// <summary>Snippet for GetTenantAsync</summary>
public async Task GetTenantResourceNamesAsync()
{
// Snippet: GetTenantAsync(TenantName, CallSettings)
// Additional: GetTenantAsync(TenantName, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
// Make the request
Tenant response = await tenantServiceClient.GetTenantAsync(name);
// End snippet
}
/// <summary>Snippet for UpdateTenant</summary>
public void UpdateTenantRequestObject()
{
// Snippet: UpdateTenant(UpdateTenantRequest, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
UpdateTenantRequest request = new UpdateTenantRequest
{
Tenant = new Tenant(),
UpdateMask = new FieldMask(),
};
// Make the request
Tenant response = tenantServiceClient.UpdateTenant(request);
// End snippet
}
/// <summary>Snippet for UpdateTenantAsync</summary>
public async Task UpdateTenantRequestObjectAsync()
{
// Snippet: UpdateTenantAsync(UpdateTenantRequest, CallSettings)
// Additional: UpdateTenantAsync(UpdateTenantRequest, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateTenantRequest request = new UpdateTenantRequest
{
Tenant = new Tenant(),
UpdateMask = new FieldMask(),
};
// Make the request
Tenant response = await tenantServiceClient.UpdateTenantAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateTenant</summary>
public void UpdateTenant()
{
// Snippet: UpdateTenant(Tenant, FieldMask, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
Tenant tenant = new Tenant();
FieldMask updateMask = new FieldMask();
// Make the request
Tenant response = tenantServiceClient.UpdateTenant(tenant, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateTenantAsync</summary>
public async Task UpdateTenantAsync()
{
// Snippet: UpdateTenantAsync(Tenant, FieldMask, CallSettings)
// Additional: UpdateTenantAsync(Tenant, FieldMask, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
Tenant tenant = new Tenant();
FieldMask updateMask = new FieldMask();
// Make the request
Tenant response = await tenantServiceClient.UpdateTenantAsync(tenant, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteTenant</summary>
public void DeleteTenantRequestObject()
{
// Snippet: DeleteTenant(DeleteTenantRequest, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
// Make the request
tenantServiceClient.DeleteTenant(request);
// End snippet
}
/// <summary>Snippet for DeleteTenantAsync</summary>
public async Task DeleteTenantRequestObjectAsync()
{
// Snippet: DeleteTenantAsync(DeleteTenantRequest, CallSettings)
// Additional: DeleteTenantAsync(DeleteTenantRequest, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
// Make the request
await tenantServiceClient.DeleteTenantAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteTenant</summary>
public void DeleteTenant()
{
// Snippet: DeleteTenant(string, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]";
// Make the request
tenantServiceClient.DeleteTenant(name);
// End snippet
}
/// <summary>Snippet for DeleteTenantAsync</summary>
public async Task DeleteTenantAsync()
{
// Snippet: DeleteTenantAsync(string, CallSettings)
// Additional: DeleteTenantAsync(string, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]";
// Make the request
await tenantServiceClient.DeleteTenantAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteTenant</summary>
public void DeleteTenantResourceNames()
{
// Snippet: DeleteTenant(TenantName, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
// Make the request
tenantServiceClient.DeleteTenant(name);
// End snippet
}
/// <summary>Snippet for DeleteTenantAsync</summary>
public async Task DeleteTenantResourceNamesAsync()
{
// Snippet: DeleteTenantAsync(TenantName, CallSettings)
// Additional: DeleteTenantAsync(TenantName, CancellationToken)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
// Make the request
await tenantServiceClient.DeleteTenantAsync(name);
// End snippet
}
/// <summary>Snippet for ListTenants</summary>
public void ListTenantsRequestObject()
{
// Snippet: ListTenants(ListTenantsRequest, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
ListTenantsRequest request = new ListTenantsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenants(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Tenant item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTenantsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Tenant item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Tenant> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Tenant item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTenantsAsync</summary>
public async Task ListTenantsRequestObjectAsync()
{
// Snippet: ListTenantsAsync(ListTenantsRequest, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
ListTenantsRequest request = new ListTenantsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenantsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Tenant item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTenantsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Tenant item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Tenant> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Tenant item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTenants</summary>
public void ListTenants()
{
// Snippet: ListTenants(string, string, int?, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenants(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Tenant item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTenantsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Tenant item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Tenant> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Tenant item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTenantsAsync</summary>
public async Task ListTenantsAsync()
{
// Snippet: ListTenantsAsync(string, string, int?, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedAsyncEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenantsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Tenant item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTenantsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Tenant item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Tenant> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Tenant item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTenants</summary>
public void ListTenantsResourceNames()
{
// Snippet: ListTenants(ProjectName, string, int?, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = TenantServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenants(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Tenant item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTenantsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Tenant item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Tenant> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Tenant item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTenantsAsync</summary>
public async Task ListTenantsResourceNamesAsync()
{
// Snippet: ListTenantsAsync(ProjectName, string, int?, CallSettings)
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenantsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Tenant item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTenantsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Tenant item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Tenant> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Tenant item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.GoogleMaps;
namespace XFGoogleMapSample
{
public partial class BasicMapPage : ContentPage
{
public BasicMapPage()
{
InitializeComponent();
// MapTypes
var mapTypeValues = new List<MapType>();
foreach (var mapType in Enum.GetValues(typeof(MapType)))
{
mapTypeValues.Add((MapType)mapType);
pickerMapType.Items.Add(Enum.GetName(typeof(MapType), mapType));
}
pickerMapType.SelectedIndexChanged += (sender, e) =>
{
map.MapType = mapTypeValues[pickerMapType.SelectedIndex];
};
pickerMapType.SelectedIndex = 0;
// ZoomEnabled
switchHasZoomEnabled.Toggled += (sender, e) =>
{
map.HasZoomEnabled = e.Value;
};
switchHasZoomEnabled.IsToggled = map.HasZoomEnabled;
// ScrollEnabled
switchHasScrollEnabled.Toggled += (sender, e) =>
{
map.HasScrollEnabled = e.Value;
};
switchHasScrollEnabled.IsToggled = map.HasScrollEnabled;
// MyLocationEnabled
switchMyLocationEnabled.Toggled += (sender, e) =>
{
map.MyLocationEnabled = e.Value;
};
switchMyLocationEnabled.IsToggled = map.MyLocationEnabled;
// IsTrafficEnabled
switchIsTrafficEnabled.Toggled += (sender, e) =>
{
map.IsTrafficEnabled = e.Value;
};
switchIsTrafficEnabled.IsToggled = map.IsTrafficEnabled;
// IndoorEnabled
switchIndoorEnabled.Toggled += (sender, e) =>
{
map.IsIndoorEnabled = e.Value;
};
switchIndoorEnabled.IsToggled = map.IsIndoorEnabled;
// CompassEnabled
switchCompassEnabled.Toggled += (sender, e) =>
{
map.UiSettings.CompassEnabled = e.Value;
};
switchCompassEnabled.IsToggled = map.UiSettings.CompassEnabled;
// RotateGesturesEnabled
switchRotateGesturesEnabled.Toggled += (sender, e) =>
{
map.UiSettings.RotateGesturesEnabled = e.Value;
};
switchRotateGesturesEnabled.IsToggled = map.UiSettings.RotateGesturesEnabled;
// MyLocationButtonEnabled
switchMyLocationButtonEnabled.Toggled += (sender, e) =>
{
map.UiSettings.MyLocationButtonEnabled = e.Value;
};
switchMyLocationButtonEnabled.IsToggled = map.UiSettings.MyLocationButtonEnabled;
// IndoorLevelPickerEnabled
switchIndoorLevelPickerEnabled.Toggled += (sender, e) =>
{
map.UiSettings.IndoorLevelPickerEnabled = e.Value;
};
switchIndoorLevelPickerEnabled.IsToggled = map.UiSettings.IndoorLevelPickerEnabled;
// ScrollGesturesEnabled
switchScrollGesturesEnabled.Toggled += (sender, e) =>
{
map.UiSettings.ScrollGesturesEnabled = e.Value;
};
switchScrollGesturesEnabled.IsToggled = map.UiSettings.ScrollGesturesEnabled;
// TiltGesturesEnabled
switchTiltGesturesEnabled.Toggled += (sender, e) =>
{
map.UiSettings.TiltGesturesEnabled = e.Value;
};
switchTiltGesturesEnabled.IsToggled = map.UiSettings.TiltGesturesEnabled;
// ZoomControlsEnabled
switchZoomControlsEnabled.Toggled += (sender, e) =>
{
map.UiSettings.ZoomControlsEnabled = e.Value;
};
switchZoomControlsEnabled.IsToggled = map.UiSettings.ZoomControlsEnabled;
// ZoomGesturesEnabled
switchZoomGesturesEnabled.Toggled += (sender, e) =>
{
map.UiSettings.ZoomGesturesEnabled = e.Value;
};
switchZoomGesturesEnabled.IsToggled = map.UiSettings.ZoomGesturesEnabled;
// Map Clicked
map.MapClicked += (sender, e) =>
{
var lat = e.Point.Latitude.ToString("0.000");
var lng = e.Point.Longitude.ToString("0.000");
this.DisplayAlert("MapClicked", $"{lat}/{lng}", "CLOSE");
};
// Map Long clicked
map.MapLongClicked += (sender, e) =>
{
var lat = e.Point.Latitude.ToString("0.000");
var lng = e.Point.Longitude.ToString("0.000");
this.DisplayAlert("MapLongClicked", $"{lat}/{lng}", "CLOSE");
};
// Map MyLocationButton clicked
map.MyLocationButtonClicked += (sender, args) =>
{
args.Handled = switchHandleMyLocationButton.IsToggled;
if (switchHandleMyLocationButton.IsToggled)
{
this.DisplayAlert("MyLocationButtonClicked",
"If set MyLocationButtonClickedEventArgs.Handled = true then skip obtain current location",
"OK");
}
};
map.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == Map.HasZoomEnabledProperty.PropertyName)
{
switchHasZoomEnabled.IsToggled = map.HasZoomEnabled;
}
else if (e.PropertyName == Map.HasScrollEnabledProperty.PropertyName)
{
switchHasScrollEnabled.IsToggled = map.HasScrollEnabled;
}
else if (e.PropertyName == Map.MyLocationEnabledProperty.PropertyName)
{
switchMyLocationEnabled.IsToggled = map.MyLocationEnabled;
}
};
map.UiSettings.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == UiSettings.MyLocationButtonEnabledProperty.PropertyName)
{
switchMyLocationButtonEnabled.IsToggled = map.UiSettings.MyLocationButtonEnabled;
}
else if (e.PropertyName == UiSettings.IndoorLevelPickerEnabledProperty.PropertyName)
{
switchIndoorLevelPickerEnabled.IsToggled = map.UiSettings.IndoorLevelPickerEnabled;
}
else if (e.PropertyName == UiSettings.ScrollGesturesEnabledProperty.PropertyName)
{
switchScrollGesturesEnabled.IsToggled = map.UiSettings.ScrollGesturesEnabled;
}
};
map.CameraChanged += (sender, args) =>
{
var p = args.Position;
labelStatus.Text = $"Lat={p.Target.Latitude:0.00}, Long={p.Target.Longitude:0.00}, Zoom={p.Zoom:0.00}, Bearing={p.Bearing:0.00}, Tilt={p.Tilt:0.00}";
};
// Geocode
buttonGeocode.Clicked += async (sender, e) =>
{
var geocoder = new Xamarin.Forms.GoogleMaps.Geocoder();
var positions = await geocoder.GetPositionsForAddressAsync(entryAddress.Text);
if (positions.Count() > 0)
{
var pos = positions.First();
map.MoveToRegion(MapSpan.FromCenterAndRadius(pos, Distance.FromMeters(5000)));
var reg = map.VisibleRegion;
var format = "0.00";
labelStatus.Text = $"Center = {reg.Center.Latitude.ToString(format)}, {reg.Center.Longitude.ToString(format)}";
}
else
{
await this.DisplayAlert("Not found", "Geocoder returns no results", "Close");
}
};
// Snapshot
buttonTakeSnapshot.Clicked += async (sender, e) =>
{
var stream = await map.TakeSnapshot();
imageSnapshot.Source = ImageSource.FromStream(() => stream);
};
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.ComponentModel;
using System.Globalization;
using JetBrains.Annotations;
using NLog.Internal;
namespace NLog.Targets
{
/// <summary>
/// Line ending mode.
/// </summary>
#if !NETSTANDARD1_3
[TypeConverter(typeof(LineEndingModeConverter))]
#endif
public sealed class LineEndingMode : IEquatable<LineEndingMode>
{
/// <summary>
/// Insert platform-dependent end-of-line sequence after each line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LineEndingMode Default = new LineEndingMode("Default", EnvironmentHelper.NewLine);
/// <summary>
/// Insert CR LF sequence (ASCII 13, ASCII 10) after each line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LineEndingMode CRLF = new LineEndingMode("CRLF", "\r\n");
/// <summary>
/// Insert CR character (ASCII 13) after each line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LineEndingMode CR = new LineEndingMode("CR", "\r");
/// <summary>
/// Insert LF character (ASCII 10) after each line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LineEndingMode LF = new LineEndingMode("LF", "\n");
/// <summary>
/// Insert null terminator (ASCII 0) after each line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LineEndingMode Null = new LineEndingMode("Null", "\0");
/// <summary>
/// Do not insert any line ending.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LineEndingMode None = new LineEndingMode("None", string.Empty);
private readonly string _name;
private readonly string _newLineCharacters;
/// <summary>
/// Gets the name of the LineEndingMode instance.
/// </summary>
public string Name => _name;
/// <summary>
/// Gets the new line characters (value) of the LineEndingMode instance.
/// </summary>
public string NewLineCharacters => _newLineCharacters;
private LineEndingMode() { }
/// <summary>
/// Initializes a new instance of <see cref="LogLevel"/>.
/// </summary>
/// <param name="name">The mode name.</param>
/// <param name="newLineCharacters">The new line characters to be used.</param>
private LineEndingMode(string name, string newLineCharacters)
{
_name = name;
_newLineCharacters = newLineCharacters;
}
/// <summary>
/// Returns the <see cref="LineEndingMode"/> that corresponds to the supplied <paramref name="name"/>.
/// </summary>
/// <param name="name">
/// The textual representation of the line ending mode, such as CRLF, LF, Default etc.
/// Name is not case sensitive.
/// </param>
/// <returns>The <see cref="LineEndingMode"/> value, that corresponds to the <paramref name="name"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">There is no line ending mode with the specified name.</exception>
public static LineEndingMode FromString([NotNull] string name)
{
if (name == null) throw new ArgumentNullException(nameof(name));
if (name.Equals(CRLF.Name, StringComparison.OrdinalIgnoreCase)) return CRLF;
if (name.Equals(LF.Name, StringComparison.OrdinalIgnoreCase)) return LF;
if (name.Equals(CR.Name, StringComparison.OrdinalIgnoreCase)) return CR;
if (name.Equals(Default.Name, StringComparison.OrdinalIgnoreCase)) return Default;
if (name.Equals(Null.Name, StringComparison.OrdinalIgnoreCase)) return Null;
if (name.Equals(None.Name, StringComparison.OrdinalIgnoreCase)) return None;
#if !SILVERLIGHT
throw new ArgumentOutOfRangeException(nameof(name), name, "LineEndingMode is out of range");
#else
throw new ArgumentOutOfRangeException("name", "LineEndingMode is out of range");
#endif
}
/// <summary>
/// Compares two <see cref="LineEndingMode"/> objects and returns a
/// value indicating whether the first one is equal to the second one.
/// </summary>
/// <param name="mode1">The first level.</param>
/// <param name="mode2">The second level.</param>
/// <returns>The value of <c>mode1.NewLineCharacters == mode2.NewLineCharacters</c>.</returns>
public static bool operator ==(LineEndingMode mode1, LineEndingMode mode2)
{
if (ReferenceEquals(mode1, null))
{
return ReferenceEquals(mode2, null);
}
if (ReferenceEquals(mode2, null))
{
return false;
}
return mode1.NewLineCharacters == mode2.NewLineCharacters;
}
/// <summary>
/// Compares two <see cref="LineEndingMode"/> objects and returns a
/// value indicating whether the first one is not equal to the second one.
/// </summary>
/// <param name="mode1">The first mode</param>
/// <param name="mode2">The second mode</param>
/// <returns>The value of <c>mode1.NewLineCharacters != mode2.NewLineCharacters</c>.</returns>
public static bool operator !=(LineEndingMode mode1, LineEndingMode mode2)
{
if (ReferenceEquals(mode1, null))
{
return !ReferenceEquals(mode2, null);
}
if (ReferenceEquals(mode2, null))
{
return true;
}
return mode1.NewLineCharacters != mode2.NewLineCharacters;
}
/// <summary>
/// Returns a string representation of the log level.
/// </summary>
/// <returns>Log level name.</returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms
/// and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return (_newLineCharacters != null ? _newLineCharacters.GetHashCode() : 0);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is
/// equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with
/// this instance.</param>
/// <returns>
/// Value of <c>true</c> if the specified <see cref="System.Object"/>
/// is equal to this instance; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is LineEndingMode mode && Equals(mode);
}
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
/// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(LineEndingMode other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(_newLineCharacters, other._newLineCharacters);
}
#if !NETSTANDARD1_3
/// <summary>
/// Provides a type converter to convert <see cref="LineEndingMode"/> objects to and from other representations.
/// </summary>
public class LineEndingModeConverter : TypeConverter
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param><param name="sourceType">A <see cref="T:System.Type"/> that represents the type you want to convert from. </param>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
/// <returns>
/// An <see cref="T:System.Object"/> that represents the converted value.
/// </returns>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param><param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param><param name="value">The <see cref="T:System.Object"/> to convert. </param><exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var name = value as string;
return name != null ? FromString(name) : base.ConvertFrom(context, culture, value);
}
}
#endif
}
}
| |
using System;
using MonoBrick;
using System.Collections.Generic;
namespace MonoBrick.EV3
{
/// <summary>
/// Sensor ports
/// </summary>
public enum SensorPort {
#pragma warning disable
In1 = 0, In2 = 1, In3 = 2, In4 = 3
#pragma warning restore
};
/// <summary>
/// Device types
/// </summary>
public enum SensorType {
#pragma warning disable
Unknown = 0, NXTTouch = 1, NXTLight = 2, NXTSound = 3, NXTColor = 4, NXTUltraSonic = 5, NXTTemperature = 6, LMotor = 7 , MMotor = 8,
Touch = 16, Test = 21, I2C = 100, NXTTest = 101, Color = 29, UltraSonic = 30, Gyro = 32, IR = 33, None = 126
#pragma warning restore
};
/// <summary>
/// Sensor modes
/// </summary>
public enum SensorMode {
#pragma warning disable
Mode0 = 0, Mode1 = 1, Mode2 = 2, Mode3 = 3, Mode4 = 4, Mode5 = 5, Mode6 = 6
#pragma warning restore
};
/// <summary>
/// Class for creating a sensor
/// </summary>
public class Sensor : ISensor
{
internal SensorPort Port{get; set;}
internal Connection<Command,Reply> Connection {get;set;}
/// <summary>
/// Gets or sets the daisy chain layer.
/// </summary>
/// <value>The daisy chain layer.</value>
public DaisyChainLayer DaisyChainLayer{get;set;}
/// <summary>
/// Gets the sensor type
/// </summary>
/// <returns>The type.</returns>
public SensorType GetSensorType()
{
if(!isInitialized)
Initialize();
SensorType type;
SensorMode mode;
GetTypeAndMode(out type, out mode);
return type;
}
/// <summary>
/// Gets the sensor mode.
/// </summary>
/// <returns>The mode.</returns>
protected SensorMode GetSensorMode ()
{
SensorType type;
SensorMode mode;
GetTypeAndMode(out type, out mode);
return mode;
}
/// <summary>
/// Gets the sensor type and mode.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="mode">Mode.</param>
protected void GetTypeAndMode(out SensorType type, out SensorMode mode){
if(!isInitialized)
Initialize();
var command = new Command(2,0,200,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetTypeMode);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)0, VariableScope.Global);
command.Append((byte)1, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,200);
type = (SensorType) reply.GetByte(3);
mode = (SensorMode) reply.GetByte(4);
}
/// <summary>
/// Gets the name of the sensor
/// </summary>
/// <returns>The name.</returns>
public virtual string GetName ()
{
if(!isInitialized)
Initialize();
var command = new Command(Command.ShortValueMax,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetName);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(Command.ShortValueMax, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetString(3,(byte) Command.ShortValueMax);
}
/// <summary>
/// Get device symbol
/// </summary>
/// <returns>The symbole.</returns>
public virtual string GetSymbole ()
{
if(!isInitialized)
Initialize();
var command = new Command(Command.ShortValueMax,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetSymbol);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(Command.ShortValueMax, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetString(3,(byte) Command.ShortValueMax);
}
/// <summary>
/// Get sensor format
/// </summary>
/// <returns>The format.</returns>
protected string GetFormat ()
{
throw new NotSupportedException();
}
/// <summary>
/// Read the raw sensor value
/// </summary>
/// <returns>The raw sensor value.</returns>
protected Int32 GetRaw ()
{
if(!isInitialized)
Initialize();
var command = new Command(4,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetRaw);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetInt32(3);
}
/// <summary>
/// Get device mode name
/// </summary>
/// <returns>The device mode name.</returns>
protected string GetModeName ()
{
return GetModeName(this.mode);
}
/// <summary>
/// Get device mode name
/// </summary>
/// <returns>The device mode name.</returns>
/// <param name="mode">Mode to get name of.</param>
protected string GetModeName (SensorMode mode)
{
if(!isInitialized)
Initialize();
var command = new Command(Command.ShortValueMax,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetModeName);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte) mode, ConstantParameterType.Value);
command.Append(Command.ShortValueMax, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetString(3,(byte) Command.ShortValueMax);
}
/// <summary>
/// Gets figure layout.
/// </summary>
/// <param name="figures">Figures.</param>
/// <param name="decimals">Decimals.</param>
protected void GetFigures(out byte figures, out byte decimals){
if(!isInitialized)
Initialize();
var command = new Command(2,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetFigures);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)0, VariableScope.Global);
command.Append((byte)1, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
figures = reply.GetByte(3);
decimals = reply.GetByte(4);
}
/// <summary>
/// Gets the min and max values that can be returned.
/// </summary>
/// <param name="min">Minimum.</param>
/// <param name="max">Maxium.</param>
protected void GetMinMax(out float min, out float max){
if(!isInitialized)
Initialize();
var command = new Command(8,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetMinMax);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)0, VariableScope.Global);
command.Append((byte)4, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
min = reply.GetFloat(3);
max = reply.GetFloat(7);
}
/// <summary>
/// </summary>
protected byte ReadyPct ()
{
if(!isInitialized)
Initialize();
var command = new Command(1,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.ReadyPCT);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(0, ConstantParameterType.Value);
command.Append(mode);
command.Append(1, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetByte(3);
}
/// <summary>
/// </summary>
protected Int32 ReadyRaw ()
{
if(!isInitialized)
Initialize();
var command = new Command(4,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.ReadyRaw);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(0, ConstantParameterType.Value);
command.Append(mode);
command.Append(1, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetInt32(3);
}
/// <summary>
/// </summary>
protected float ReadySi ()
{
if(!isInitialized)
Initialize();
var command = new Command(4,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.ReadySI);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(0, ConstantParameterType.Value);
command.Append(mode);
command.Append(1, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetFloat(3);
}
/// <summary>
/// Get positive changes since last clear
/// </summary>
/// <returns>The changes.</returns>
protected float GetChanges ()
{
if(!isInitialized)
Initialize();
var command = new Command(4,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetChanges);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetFloat(3);
}
/// <summary>
/// Get the bolean count since the last clear
/// </summary>
/// <returns>The bumb count.</returns>
protected float GetBumbs ()
{
if(!isInitialized)
Initialize();
var command = new Command(4,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.GetBumps);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetFloat(3);
}
/// <summary>
/// Clear changes and bumps
/// </summary>
protected void ClearChanges ()
{
if(!isInitialized)
Initialize();
var command = new Command(0,0,201,false);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.ClrChanges);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
Connection.Send(command);
}
/// <summary>
/// Apply new minimum and maximum raw value for device type to be used in scaling PCT and SI
/// </summary>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
protected void CalcMinMax (UInt32 min, UInt32 max)
{
throw new NotImplementedException();
}
/// <summary>
/// Apply new minimum raw value for device type to be used in scaling PCT and SI
/// </summary>
/// <param name="min">Minimum.</param>
protected void CalcMin(UInt32 min)
{
throw new NotImplementedException();
}
/// <summary>
/// Apply new maximum raw value for device type to be used in scaling PCT and SI
/// </summary>
/// <param name="max">Max.</param>
protected void CalcMax (UInt32 max)
{
throw new NotImplementedException();
}
/// <summary>
/// Apply the default minimum and maximum raw value for device type to be used in scaling PCT and SI
/// </summary>
protected void CalcDefault()
{
throw new NotImplementedException();
}
/// <summary>
/// Generic setup/read IIC sensors
/// </summary>
/// <returns>DATA8 array (handle) to read into</returns>
/// <param name="repeat">Repeat setup/read "REPEAT" times (0 = infinite)</param>
/// <param name="reapeatTime">Time between repeats [10..1000mS] (0 = 10)</param>
/// <param name="writeData">Byte array to write</param>
protected byte SetUp (byte repeat, Int16 reapeatTime, byte[] writeData)
{
if(!isInitialized)
Initialize();
var command = new Command(4,0,201,true);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.Setup);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(repeat, ConstantParameterType.Value);
command.Append(repeat, ConstantParameterType.Value);
command.Append(writeData.Length, ConstantParameterType.Value);
command.Append(1, ConstantParameterType.Value);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,201);
return reply.GetByte(3);
}
/// <summary>
/// Clear all devices (e.c. counters, angle, ...)
/// </summary>
protected void ClearAll ()
{
if(!isInitialized)
Initialize();
var command = new Command(0,0,201,false);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.ClearAll);
command.Append(this.DaisyChainLayer);
Connection.Send(command);
}
/// <summary>
/// Stop all devices (e.c. motors, ...)
/// </summary>
protected void StopAll ()
{
if(!isInitialized)
Initialize();
var command = new Command(0,0,201,false);
command.Append(ByteCodes.InputDevice);
command.Append(InputSubCodes.StopAll);
command.Append(this.DaisyChainLayer);
Connection.Send(command);
}
/// <summary>
/// Read a sensor value
/// </summary>
/// <returns>The sensor value.</returns>
protected byte GetRead(){
if(!isInitialized)
Initialize();
var command = new Command(4,0, 123, true);
command.Append(ByteCodes.InputRead);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(0, ConstantParameterType.Value);
command.Append(mode);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,123);
return reply[3];
}
/// <summary>
/// Reads the si sensor value
/// </summary>
/// <returns>The si sensor value.</returns>
protected float ReadSi()
{
if(!isInitialized)
Initialize();
var command = new Command(4,0, 123, true);
command.Append(ByteCodes.InputReadSI);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(0, ConstantParameterType.Value);
command.Append(mode);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,123);
return reply.GetFloat(3);
}
/// <summary>
/// Sets the sensor mode
/// </summary>
/// <param name="mode">Mode to use.</param>
protected virtual void SetMode(SensorMode mode){
isInitialized = true;
this.mode = mode;
var command = new Command(4,0, 123, true);
command.Append(ByteCodes.InputReadSI);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append(0, ConstantParameterType.Value);
command.Append(mode);
command.Append((byte)0, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
Error.CheckForError(reply,123);
}
/// <summary>
/// Wait for device ready (wait for valid data)
/// </summary>
/// <returns><c>true</c> if this instance is ready; otherwise, <c>false</c>.</returns>
protected bool IsReady ()
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to device (only UART devices)
/// </summary>
/// <param name="data">Data array to write.</param>
protected void Write (byte[] data)
{
if(!isInitialized)
Initialize();
var command = new Command(0,0, 100, false);
command.Append(ByteCodes.InputWrite);
command.Append(this.DaisyChainLayer);
command.Append(this.Port);
command.Append((byte)data.Length, ParameterFormat.Short);
foreach(byte b in data)
command.Append(b);
Connection.Send(command);
}
/// <summary>
/// If initialized has been called
/// </summary>
protected bool isInitialized = false;
/// <summary>
/// Holds the sensor mode that is used.
/// </summary>
protected SensorMode mode = SensorMode.Mode0;
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.Sensor"/> class.
/// </summary>
public Sensor ()
{
mode = SensorMode.Mode0;
if(Connection != null && Connection.IsConnected)
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.Sensor"/> class.
/// </summary>
/// <param name="mode">Mode to use.</param>
public Sensor (SensorMode mode)
{
this.mode = mode;
if(Connection != null && Connection.IsConnected)
Initialize();
}
#region ISensor
/// <summary>
/// Initialize the sensor
/// </summary>
public void Initialize ()
{
SetMode(mode);
ReadyRaw();
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>
/// The value as a string
/// </returns>
public virtual string ReadAsString(){
return ReadSi().ToString();
}
/// <summary>
/// For Ultrasonic, Temperature and Gyro Sensors and other sensors
/// </summary>
/// <returns></returns>
public virtual float ReadAsFloat()
{
return ReadSi();
}
#endregion
}
/// <summary>
/// Sensor mode when using a touch sensor
/// </summary>
public enum TouchMode {
/// <summary>
/// On or off mode
/// </summary>
Boolean = SensorMode.Mode0,
/// <summary>
/// Bump mode
/// </summary>
Count = SensorMode.Mode1
};
/// <summary>
/// Class used for touch sensor. Works with both EV3 and NXT
/// </summary>
public class TouchSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.TouchSensor"/> class.
/// </summary>
public TouchSensor () : base((SensorMode)TouchMode.Boolean)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.TouchSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public TouchSensor (TouchMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
if (mode == (SensorMode)TouchMode.Count) {
s = Read() + " count";
}
if (mode == (SensorMode)TouchMode.Boolean) {
if( Convert.ToBoolean(ReadSi () ) ){
s = "On";
}
else{
s = "Off";
}
}
return s;
}
/// <summary>
/// This Func should return sensor value as float. Read() Should Works good. But maybe we need use another method
/// </summary>
/// <returns></returns>
public override float ReadAsFloat()
{
float i = 0;
if (mode == (SensorMode)TouchMode.Count)
{
i = Read();
}
if (mode == (SensorMode)TouchMode.Boolean)
{
if (Convert.ToBoolean(Read()))
{
i = 1;
}
else
{
i = 0;
}
}
return i;
}
/// <summary>
/// Read the value. In bump mode this will return the count
/// </summary>
public int Read ()
{
int value = 0;
if (mode == (SensorMode)TouchMode.Count) {
value = (int)GetBumbs();
}
if (mode == (SensorMode)TouchMode.Boolean) {
if(GetRead() > 50){
value = 1;
}
else{
value = 0;
}
}
return value;
}
/// <summary>
/// Reset the bumb count
/// </summary>
public void Reset()
{
this.ClearChanges();
}
/// <summary>
/// Gets or sets the mode.
/// </summary>
/// <value>The mode.</value>
public TouchMode Mode {
get{return (TouchMode) this.mode;}
set{SetMode((SensorMode) value);}
}
}
/// <summary>
/// Colors that can be read from the EV3 color sensor
/// </summary>
public enum Color{
#pragma warning disable
None = 0, Black = 1, Blue = 2, Green = 3,
Yellow = 4, Red = 5, White = 6, Brown = 7
#pragma warning restore
};
/// <summary>
/// Sensor mode when using a EV3 color sensor
/// </summary>
public enum ColorMode {
/// <summary>
/// Use the color sensor to read reflected light
/// </summary>
Reflection = SensorMode.Mode0,
/// <summary>
/// Use the color sensor to detect the light intensity
/// </summary>
Ambient = SensorMode.Mode1,
/// <summary>
/// Use the color sensor to distinguish between eight different colors
/// </summary>
Color = SensorMode.Mode2,
/// <summary>
/// Read the raw value of the reflected light
/// </summary>
Raw = SensorMode.Mode3,
/// <summary>
/// Activate the green light on the color sensor. Only works with the NXT Color sensor
/// </summary>
NXTGreen = SensorMode.Mode3,
/// <summary>
/// Activate the green blue on the color sensor. Only works with the NXT Color sensor
/// </summary>
NXTBlue = SensorMode.Mode4,
//Raw = SensorMode.Mode5
//RGBRaw = SensorMode.Mode4,
//ColorCalculated = SensorMode.Mode5,
};
/// <summary>
/// Class for EV3 and NXT Color sensor
/// </summary>
public class ColorSensor : Sensor{
private SensorType? type = null;
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.ColorSensor"/> class.
/// </summary>
public ColorSensor () : base((SensorMode)ColorMode.Color)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.ColorSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public ColorSensor (ColorMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Gets or sets the color mode.
/// </summary>
/// <value>The color mode.</value>
public ColorMode Mode {
get{return (ColorMode) this.mode;}
set{SetMode((SensorMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)ColorMode.Ambient:
s = Read().ToString();
break;
case (SensorMode)ColorMode.Color:
s = ReadColor().ToString();
break;
case (SensorMode)ColorMode.Reflection:
s = Read().ToString();
break;
case (SensorMode)ColorMode.Raw:
s = Read().ToString();
break;
default:
s = Read().ToString();
break;
}
return s;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override float ReadAsFloat()
{
return Read();
}
/// <summary>
/// Read the intensity of the reflected light
/// </summary>
public int Read()
{
int value = 0;
switch (mode)
{
case (SensorMode)ColorMode.Ambient:
value = GetRead();
break;
case (SensorMode)ColorMode.Color:
value = GetRaw();
if(type == null)
type = this.GetSensorType();
if(type == SensorType.NXTColor){
NXT.Color nxtColor = (NXT.Color) value;
switch(nxtColor){
case MonoBrick.NXT.Color.Black:
value = (int) Color.Black;
break;
case MonoBrick.NXT.Color.Blue:
value = (int) Color.Blue;
break;
case MonoBrick.NXT.Color.Green:
value = (int) Color.Green;
break;
case MonoBrick.NXT.Color.Red:
value = (int) Color.Red;
break;
case MonoBrick.NXT.Color.White:
value = (int) Color.White;
break;
case MonoBrick.NXT.Color.Yellow:
value = (int) Color.Yellow;
break;
}
}
break;
case (SensorMode)ColorMode.Reflection:
value = GetRead();
break;
case (SensorMode)ColorMode.Raw:
if(type == null)
type = this.GetSensorType();
if(type == SensorType.NXTColor){
if( ((ColorMode)mode) == ColorMode.Raw){
SetMode(SensorMode.Mode5);
}
}
value = GetRaw();
break;
default:
value = GetRaw();
break;
}
return value;
}
/// <summary>
/// Reads the color.
/// </summary>
/// <returns>The color.</returns>
public Color ReadColor()
{
Color color = Color.None;
if (mode == (SensorMode)ColorMode.Color) {
color = (Color) GetRaw();
}
return color;
}
}
/// <summary>
/// Sensor mode when using a EV3 IR Sensor
/// </summary>
public enum IRMode {
/// <summary>
/// Use the IR sensor as a distance sensor
/// </summary>
Proximity = SensorMode.Mode0,
/// <summary>
/// Use the IR sensor to detect the location of the IR Remote
/// </summary>
Seek = SensorMode.Mode1,
/// <summary>
/// Use the IR sensor to detect wich Buttons where pressed on the IR Remote
/// </summary>
Remote = SensorMode.Mode2,
};
/// <summary>
/// Class for the EV3 IR sensor - In seek or remote mode it only works with channel 0
/// </summary>
public class IRSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.IRSensor"/> class.
/// </summary>
public IRSensor () : base((SensorMode)IRMode.Proximity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.IRSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public IRSensor (IRMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Gets or sets the IR mode.
/// </summary>
/// <value>The mode.</value>
public IRMode Mode {
get{return (IRMode) this.mode;}
set{SetMode((SensorMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)IRMode.Proximity:
s = Read().ToString();
break;
case (SensorMode)IRMode.Remote:
s = Read().ToString();
break;
case (SensorMode)IRMode.Seek:
s = Read().ToString();
break;
}
return s;
}
public override float ReadAsFloat()
{
return Read();
}
/// <summary>
/// Read the value of the sensor. The result will vary depending on the mode
/// </summary>
public int Read()
{
int value = 0;
switch (mode)
{
case (SensorMode)IRMode.Proximity:
value = GetRead();
break;
case (SensorMode)IRMode.Remote:
value = GetRaw();
break;
case (SensorMode)IRMode.Seek:
value = GetRaw();
break;
}
return value;
}
/*public void SetChannel (int i)
{
throw new NotImplementedException();
//byte[] data = { 0x12, 0x01};
//Write(data);
}*/
}
/// <summary>
/// Sensor mode when using a NXT light sensor
/// </summary>
public enum LightMode {
/// <summary>
/// Use the lgith sensor to read reflected light
/// </summary>
Relection = SensorMode.Mode0,
/// <summary>
/// Use the light sensor to detect the light intensity
/// </summary>
Ambient = SensorMode.Mode1,
};
/// <summary>
/// Class for the NXT light sensor
/// </summary>
public class LightSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.LightSensor"/> class.
/// </summary>
public LightSensor () : base((SensorMode)LightMode.Relection)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.LightSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public LightSensor (LightMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Gets or sets the light mode.
/// </summary>
/// <value>The mode.</value>
public LightMode Mode {
get{return (LightMode) this.mode;}
set{SetMode((SensorMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)LightMode.Ambient:
s = Read().ToString();
break;
case (SensorMode)LightMode.Relection:
s = Read().ToString();
break;
}
return s;
}
public override float ReadAsFloat()
{
return Read();
}
/// <summary>
/// Read this instance.
/// </summary>
public int Read()
{
int value = 0;
switch (mode)
{
case (SensorMode)LightMode.Ambient:
value = GetRead();
break;
case (SensorMode)LightMode.Relection:
value = GetRead();
break;
}
return value;
}
/// <summary>
/// Reads the raw sensor value.
/// </summary>
/// <returns>The raw sensor value.</returns>
public int ReadRaw ()
{
return GetRaw();
}
}
/// <summary>
/// Sensor mode when using a sound sensor
/// </summary>
public enum SoundMode {
/// <summary>
/// The sound level is measured in A-weighting decibel
/// </summary>
SoundDBA = SensorMode.Mode1,
/// <summary>
/// The sound level is measured in decibel
/// </summary>
SoundDB = SensorMode.Mode0 };
/// <summary>
/// Class for the NXT sound sensor
/// </summary>
public class SoundSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.SoundSensor"/> class.
/// </summary>
public SoundSensor () : base((SensorMode)SoundMode.SoundDBA)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.SoundSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public SoundSensor (SoundMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)SoundMode.SoundDB:
s = Read().ToString();
break;
case (SensorMode)SoundMode.SoundDBA:
s = Read().ToString();
break;
}
return s;
}
/// <summary>
/// returns sensor value as Int
/// </summary>
/// <returns></returns>
public override float ReadAsFloat()
{
return Read();
}
/// <summary>
/// Read the sensor value
/// </summary>
public int Read()
{
int value = 0;
switch (mode)
{
case (SensorMode)SoundMode.SoundDB:
value = GetRead();
break;
case (SensorMode)SoundMode.SoundDBA:
value = GetRead();
break;
}
return value;
}
/// <summary>
/// Reads the raw sensor value
/// </summary>
/// <returns>The raw value.</returns>
public int ReadRaw ()
{
return GetRaw();
}
/// <summary>
/// Gets or set the sound mode.
/// </summary>
/// <value>The mode.</value>
public SoundMode Mode {
get{return (SoundMode) this.mode;}
set{SetMode((SensorMode) value);}
}
}
/// <summary>
/// Sensor modes when using a ultrasonic sensor
/// </summary>
public enum UltrasonicMode {
#pragma warning disable
/// <summary>
/// Result will be in centimeter
/// </summary>
Centimeter = SensorMode.Mode0,
/// <summary>
/// Result will be in inch
/// </summary>
Inch = SensorMode.Mode1,
/// <summary>
/// Sensor is in listen mode
/// </summary>
Listen = SensorMode.Mode2
#pragma warning restore
};
/// <summary>
/// Class for the EV3 and NXT ultrasonic sensor
/// </summary>
class UltrasonicSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.UltrasonicSensor"/> class.
/// </summary>
public UltrasonicSensor () : base((SensorMode)UltrasonicMode.Centimeter)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.UltrasonicSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public UltrasonicSensor (UltrasonicMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Gets or sets the ultrasonic mode.
/// </summary>
/// <value>The mode.</value>
public UltrasonicMode Mode {
get{return (UltrasonicMode) this.mode;}
set{SetMode((SensorMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)UltrasonicMode.Centimeter:
s = Read().ToString() + " cm";
break;
case (SensorMode)UltrasonicMode.Inch:
s = Read().ToString() + " inch";
break;
case (SensorMode)UltrasonicMode.Listen:
s = Read().ToString();
break;
}
return s;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override float ReadAsFloat()
{
return Read();
}
/// <summary>
/// Read the sensor value. Result depends on the mode
/// </summary>
public float Read()
{
return ReadSi();
}
}
/// <summary>
/// Sensor modes when using a Temperature sensor
/// </summary>
public enum TemperatureMode {
#pragma warning disable
/// <summary>
/// Result will be in celcius
/// </summary>
Celcius = SensorMode.Mode0,
/// <summary>
/// Result will be in fahrenheit
/// </summary>
Fahrenheit = SensorMode.Mode1,
#pragma warning restore
};
/// <summary>
/// Class for the EV3 temperature sensor
/// </summary>
class TemperatureSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.TemperatureSensor"/> class.
/// </summary>
public TemperatureSensor () : base((SensorMode)TemperatureMode.Celcius)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.TemperatureSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public TemperatureSensor (TemperatureMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Gets or sets the temperature mode.
/// </summary>
/// <value>The mode.</value>
public TemperatureMode Mode {
get{return (TemperatureMode) this.mode;}
set{SetMode((SensorMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)TemperatureMode.Celcius:
s = ReadTemperature().ToString() + " C";
break;
case (SensorMode)TemperatureMode.Fahrenheit:
s = ReadTemperature().ToString() + " F";
break;
}
return s;
}
public override float ReadAsFloat()
{
return ReadTemperature();
}
/// <summary>
/// Read the temperature.
/// </summary>
/// <returns>The temperature.</returns>
public float ReadTemperature()
{
return ReadSi();
}
}
/// <summary>
/// Sensor modes when using a Gyro sensor
/// </summary>
public enum GyroMode {
#pragma warning disable
/// <summary>
/// Result will be in degrees
/// </summary>
Angle = SensorMode.Mode0,
/// <summary>
/// Result will be in degrees per second
/// </summary>
AngularVelocity = SensorMode.Mode1,
#pragma warning restore
};
/// <summary>
/// Class for the EV3 gyro sensor
/// </summary>
class GyroSensor : Sensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.GyroSensor"/> class.
/// </summary>
public GyroSensor () : base((SensorMode)GyroMode.Angle)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.EV3.GyroSensor"/> class.
/// </summary>
/// <param name="mode">Mode.</param>
public GyroSensor (GyroMode mode) : base((SensorMode)mode)
{
}
/// <summary>
/// Gets or sets the gyro mode.
/// </summary>
/// <value>The mode.</value>
public GyroMode Mode {
get{return (GyroMode) this.mode;}
set{SetMode((SensorMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (mode)
{
case (SensorMode)GyroMode.Angle:
s = Read().ToString() + " degree";
break;
case (SensorMode)GyroMode.AngularVelocity:
s = Read().ToString() + " deg/sec";
break;
}
return s;
}
public override float ReadAsFloat()
{
return Read();
}
/// <summary>
/// Read the sensor value. The result will depend on the mode
/// </summary>
public float Read()
{
return ReadSi();
}
}
/// <summary>
/// Class to help with sensor setup
/// </summary>
public static class SensorHelper{
private const string Color = "Color";
private const string ColorAmbient = "Color Ambient";
private const string ColorReflection = "Color Reflection";
private const string ColorReflectionRaw = "Color Reflection Raw";
private const string Touch = "Touch";
private const string TouchCount = "Touch count";
private const string GyroAngle = "Gyro Angle";
private const string GyroAngularVelocity = "Gyro Angular Velocity";
private const string IrProximity = "IR Proximity";
private const string IrRemoteMode = "IR Remote mode";
private const string IrSeekMode = "IR Seek mode";
private const string LightAmbient = "Light Ambient";
private const string LightReflection = "Light Reflection";
private const string SounddBa = "Sound dBA";
private const string SounddB = "Sound dB";
private const string TemperatureCelcius = "Temperature Celcius";
private const string TemperatureFahrenheit = "Temperature Fahrenheit";
private const string UltrasonicCentimeter = "Ultrasonic Centimeter";
private const string UltrasonicInch = "Ultrasonic Inch";
private const string UltrasonicListenMode = "Ultrasonic Listen mode";
/// <summary>
/// Gets a dictionary of sensors that has been implemented. Can be use in a combobox or simular
/// </summary>
/// <value>The sensor dictionary.</value>
public static Dictionary<string,Sensor> SensorDictionary{
get{
Dictionary<string,Sensor> dictionary = new Dictionary<string, Sensor>();
dictionary.Add(Color, new ColorSensor(ColorMode.Color));
dictionary.Add(ColorAmbient, new ColorSensor(ColorMode.Ambient));
dictionary.Add(ColorReflection, new ColorSensor(ColorMode.Reflection));
dictionary.Add(ColorReflectionRaw, new ColorSensor(ColorMode.Raw));
dictionary.Add(Touch, new TouchSensor(TouchMode.Boolean));
dictionary.Add(TouchCount, new TouchSensor(TouchMode.Count));
dictionary.Add(GyroAngle, new GyroSensor(GyroMode.Angle));
dictionary.Add(GyroAngularVelocity, new GyroSensor(GyroMode.AngularVelocity));
dictionary.Add(IrProximity, new IRSensor(IRMode.Proximity));
dictionary.Add(IrRemoteMode, new IRSensor(IRMode.Remote));
dictionary.Add(IrSeekMode, new IRSensor(IRMode.Seek));
dictionary.Add(LightAmbient, new LightSensor(LightMode.Ambient));
dictionary.Add(LightReflection, new LightSensor(LightMode.Relection));
dictionary.Add(SounddBa, new SoundSensor(SoundMode.SoundDBA));
dictionary.Add(SounddB, new SoundSensor(SoundMode.SoundDB));
dictionary.Add(TemperatureCelcius, new TemperatureSensor(TemperatureMode.Celcius));
dictionary.Add(TemperatureFahrenheit, new TemperatureSensor(TemperatureMode.Fahrenheit));
dictionary.Add(UltrasonicCentimeter, new UltrasonicSensor(UltrasonicMode.Centimeter));
dictionary.Add(UltrasonicInch, new UltrasonicSensor(UltrasonicMode.Inch));
dictionary.Add(UltrasonicListenMode, new UltrasonicSensor(UltrasonicMode.Listen));
return dictionary;
}
}
/// <summary>
/// Convert a sensor type a to dictionary key.
/// </summary>
/// <returns>A dictionary key that can be used with the sensor dictionary. If no match is found an empty string is returned</returns>
/// <param name="type">Sensor type to convert.</param>
public static string TypeToKey (SensorType type)
{
string s = "";
switch(type){
case SensorType.Gyro:
s = GyroAngle;
break;
case SensorType.I2C:
s = Touch;
break;
case SensorType.IR:
s = IrProximity;
break;
case SensorType.Color:
s = Color;
break;
case SensorType.LMotor:
break;
case SensorType.MMotor:
break;
case SensorType.None:
break;
case SensorType.NXTColor:
s = Color;
break;
case SensorType.NXTLight:
s = LightReflection;
break;
case SensorType.NXTSound:
s = SounddB;
break;
case SensorType.NXTTemperature:
s = TemperatureCelcius;
break;
case SensorType.NXTTest:
break;
case SensorType.NXTTouch:
s = Touch;
break;
case SensorType.NXTUltraSonic:
s = UltrasonicCentimeter;
break;
case SensorType.Test:
break;
case SensorType.Touch:
s = Touch;
break;
case SensorType.UltraSonic:
s = UltrasonicCentimeter;
break;
}
return s;
}
}
}
| |
//
// ListView_Model.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using Gtk;
namespace Hyena.Data.Gui
{
public partial class ListView<T> : ListViewBase
{
#pragma warning disable 0067
public event EventHandler ModelChanged;
public event EventHandler ModelReloaded;
#pragma warning restore 0067
public void SetModel (IListModel<T> model)
{
SetModel (model, 0.0);
}
public virtual void SetModel (IListModel<T> value, double vpos)
{
if (model == value) {
return;
}
if (model != null) {
model.Cleared -= OnModelClearedHandler;
model.Reloaded -= OnModelReloadedHandler;
}
model = value;
if (model != null) {
model.Cleared += OnModelClearedHandler;
model.Reloaded += OnModelReloadedHandler;
selection_proxy.Selection = model.Selection;
IsEverReorderable = model.CanReorder;
}
if (ViewLayout != null) {
ViewLayout.Model = Model;
}
ISortable sortable = model as ISortable;
if (sortable != null && ColumnController != null) {
ISortableColumn sort_column = ColumnController.SortColumn ?? ColumnController.DefaultSortColumn;
if (sort_column != null) {
if (sortable.Sort (sort_column)) {
model.Reload ();
}
RecalculateColumnSizes ();
RegenerateColumnCache ();
InvalidateHeader ();
IsReorderable = sortable.SortColumn == null || sortable.SortColumn.SortType == SortType.None;
}
}
RefreshViewForModel (vpos);
var handler = ModelChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private void RefreshViewForModel (double? vpos)
{
if (Model == null) {
QueueDraw ();
return;
}
if (ViewLayout != null) {
ViewLayout.ModelUpdated ();
}
UpdateAdjustments ();
if (vpos != null) {
ScrollToY ((double) vpos);
} else if (Model.Count <= ItemsInView) {
// If our view fits all rows at once, make sure we're scrolled to the top
ScrollToY (0.0);
} else if (vadjustment != null) {
ScrollToY (vadjustment.Value);
}
if (Parent is ScrolledWindow) {
Parent.QueueDraw ();
}
}
private void OnModelClearedHandler (object o, EventArgs args)
{
OnModelCleared ();
}
private void OnModelReloadedHandler (object o, EventArgs args)
{
OnModelReloaded ();
var handler = ModelReloaded;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private void OnColumnControllerUpdatedHandler (object o, EventArgs args)
{
OnColumnControllerUpdated ();
}
protected virtual void OnModelCleared ()
{
RefreshViewForModel (null);
}
protected virtual void OnModelReloaded ()
{
RefreshViewForModel (null);
}
private IListModel<T> model;
public virtual IListModel<T> Model {
get { return model; }
}
private string row_opaque_property_name = "Sensitive";
private PropertyInfo row_opaque_property_info;
bool row_opaque_property_invalid = false;
public string RowOpaquePropertyName {
get { return row_opaque_property_name; }
set {
if (value == row_opaque_property_name) {
return;
}
row_opaque_property_name = value;
row_opaque_property_info = null;
row_opaque_property_invalid = false;
InvalidateList ();
}
}
private bool IsRowOpaque (object item)
{
if (item == null || row_opaque_property_invalid) {
return true;
}
if (row_opaque_property_info == null || row_opaque_property_info.ReflectedType != item.GetType ()) {
row_opaque_property_info = item.GetType ().GetProperty (row_opaque_property_name);
if (row_opaque_property_info == null || row_opaque_property_info.PropertyType != typeof (bool)) {
row_opaque_property_info = null;
row_opaque_property_invalid = true;
return true;
}
}
return (bool)row_opaque_property_info.GetValue (item, null);
}
private string row_bold_property_name = "IsBold";
private PropertyInfo row_bold_property_info;
bool row_bold_property_invalid = false;
public string RowBoldPropertyName {
get { return row_bold_property_name; }
set {
if (value == row_bold_property_name) {
return;
}
row_bold_property_name = value;
row_bold_property_info = null;
row_bold_property_invalid = false;
InvalidateList ();
}
}
private bool IsRowBold (object item)
{
if (item == null || row_bold_property_invalid) {
return false;
}
if (row_bold_property_info == null || row_bold_property_info.ReflectedType != item.GetType ()) {
row_bold_property_info = item.GetType ().GetProperty (row_bold_property_name);
if (row_bold_property_info == null || row_bold_property_info.PropertyType != typeof (bool)) {
row_bold_property_info = null;
row_bold_property_invalid = true;
return false;
}
}
return (bool)row_bold_property_info.GetValue (item, null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Timers;
using Android.App;
using Android.Content;
using Android.Locations;
using Android.OS;
namespace fleetTRACK.Model
{
class Journey : Activity, ILocationListener
{
#region Public methods
/// <summary>
/// Constructor for the journey class
/// </summary>
/// <param name="context"></param>
/// <param name="carType"></param>
/// <param name="carRegistration"></param>
/// <param name="projectNumber"></param>
/// <param name="costCentre"></param>
/// <param name="accountNumber"></param>
/// <param name="activityId"></param>
/// <param name="locationNumber"></param>
/// <param name="companyNumber"></param>
/// <param name="schoolArea"></param>
/// <param name="driverName"></param>
/// <param name="importantNotes"></param>
public Journey(Context context, string carType, string carRegistration, string projectNumber,
string costCentre, string accountNumber, string activityId, string locationNumber,
string companyNumber, string schoolArea, string driverName, string importantNotes)
{
// Define journey details
this._carType = carType;
this._carRegistration = carRegistration;
this._projectNumber = projectNumber;
this._costCentre = costCentre;
this._accoutNumber = accountNumber;
this._activityId = activityId;
this._locationNumber = locationNumber;
this._companyNumber = companyNumber;
this._schoolArea = schoolArea;
this._driverName = driverName;
this._importantNotes = importantNotes;
this._context = context;
// Instantiate the location manager and define our criteria for GPS updates
_locationManager = (LocationManager)this._context.GetSystemService(Context.LocationService);
Criteria criteriaForLocationService = new Criteria { Accuracy = Accuracy.Fine };
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
// Store the acceptable provider
if (acceptableLocationProviders.Any())
_locationProvider = acceptableLocationProviders.First();
else
throw new ApplicationException("No acceptable gps location providers found.");
// Create the timer and register for callbacks
_gpsTimer = new Timer(5000);
_gpsTimer.AutoReset = true;
_gpsTimer.Elapsed += RecordGpsLocation;
}
/// <summary>
/// Starts the journey logging process
/// </summary>
public void Start()
{
// Subscribe to GPS updates and start the timer that records them
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
_startDateTime = DateTime.Now;
_gpsTimer.Enabled = true;
}
/// <summary>
/// Stops the journey logging process
/// </summary>
public void Stop()
{
// Unsubscribe from the updates and pause the timer
_locationManager.RemoveUpdates(this);
_gpsTimer.Enabled = false;
_endDateTime = DateTime.Now;
}
/// <summary>
/// Resumes the journey logging process (is an alias of Start())
/// </summary>
public void Resume()
{
// Alias for Start()
this.Start();
}
/// <summary>
/// Sets important notes for the journey
/// </summary>
/// <param name="ImportantNotes"></param>
public void SetImportantNotes(string ImportantNotes)
{
_importantNotes = ImportantNotes;
}
/// <summary>
/// Creates new csv files for the current journey.
/// One file containing simple journey details and one file containing the extended detail set for auditing purposes.
/// </summary>
public void WriteLogFiles()
{
string rootLogDirectory = String.Format(
"{0}{1}{2}{1}",
Android.OS.Environment.ExternalStorageDirectory,
Java.IO.File.Separator,
_context.Resources.GetString(Resource.String.logDirectory));
if (!Directory.Exists(rootLogDirectory))
{
try
{
Directory.CreateDirectory(rootLogDirectory);
}
catch (Exception ex)
{
throw new UnauthorizedAccessException("Unable to create log directory", ex);
}
}
string simpleJourneyDetailsFilename = String.Format("Trip_{0}_{1:yy-MM-dd_H-mm}_simple.csv", _carRegistration, _startDateTime);
string extendedJourneyDetailsFilename = String.Format("Trip_{0}_{1:yy-MM-dd_H-mm}_extended.csv", _carRegistration, _startDateTime);
// Write to new CSV file with cartype, car rego, project number, distance travelled etc.
string simpleJourneyDetailsFilePath = String.Format(
"{0}{1}",
rootLogDirectory,
simpleJourneyDetailsFilename);
using (var sw = new StreamWriter(simpleJourneyDetailsFilePath))
{
// insert headings into CSV
sw.WriteLine("Vehicle,Registration,Start Time, End Time, Distance (km),GPS Accuracy,Project,Cost Centre,Account,Activity,Location,Company,School Area,Driver,Important Notes");
// Write to the CSV
sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14}", _carType, _carRegistration, _startDateTime, _endDateTime, CalculateTotalDistanceInKilometres(), CalculateTotalAveragedAccuracy(), _projectNumber, _costCentre, _accoutNumber, _activityId, _locationNumber, _companyNumber, _schoolArea, _driverName, _importantNotes));
}
// Create a CSV file and write all locations to it (This is for auditing if average accuracy is too high).
string extendedJourneyDetailsFilePath = String.Format(
"{0}{1}",
rootLogDirectory,
extendedJourneyDetailsFilename);
using (var sw = new StreamWriter(extendedJourneyDetailsFilePath))
{
sw.WriteLine("Longitude,Latitude,Accuracy");
foreach (Location location in _journeyLocations)
{
// Write to the CSV
sw.WriteLine(string.Format("{0},{1},{2}", location.Longitude, location.Latitude, ConvertMetresToKilometres(location.Accuracy)));
}
}
}
/// <summary>
/// Callback method that is invoked by the GPS provider when it has detected a change of location
/// </summary>
/// <param name="location"></param>
public void OnLocationChanged(Location location)
{
_currentLocation = location;
}
// Yeah... let's not talk about these...
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
#endregion
#region Private properties
// Misc properties
Context _context;
// GPS-specific properties
private Location _currentLocation;
private LocationManager _locationManager;
private string _locationProvider;
private static Timer _gpsTimer;
// fleetTrack-specific properties
private List<Location> _journeyLocations = new List<Location>();
private string _carType, _carRegistration, _projectNumber, _costCentre, _accoutNumber, _activityId,
_locationNumber, _companyNumber, _schoolArea, _driverName, _importantNotes;
private DateTime _startDateTime, _endDateTime;
#endregion
#region Private methods
/// <summary>
/// Calculates the total distance between all journey locations collected.
/// </summary>
/// <returns>Returns a double representing the total distance travelled in kilometres.</returns>
private Double CalculateTotalDistanceInKilometres()
{
Single totalDistanceInMetres = 0;
// Iterate through all journey locations collected
for (int i = 0; i < _journeyLocations.Count; i++)
{
// Ensure that we are not trying to calulate the difference between the first element
// and the one before (which would be null)
if (i != 0)
{
Single[] tempDistanceBetween = new Single[1];
// Calculate the distance between the current location and the one before
Location.DistanceBetween(
_journeyLocations[i].Latitude,
_journeyLocations[i].Longitude,
_journeyLocations[i - 1].Latitude,
_journeyLocations[i - 1].Longitude,
tempDistanceBetween);
// Add the distance to a total distance variable
totalDistanceInMetres += tempDistanceBetween[0];
}
}
// Convert the total distance into kilometres and then round to two decimal places
return ConvertMetresToKilometres(totalDistanceInMetres);
}
/// <summary>
/// Calculates the total averaged accuracy of all journey locations collected.
/// </summary>
/// <returns>Returns a double representing the total averaged accuracy in kilometres.</returns>
private Double CalculateTotalAveragedAccuracy()
{
Single totalAccuracyInMetres = 0;
// Iterate through all journey locations collected
foreach (Location location in _journeyLocations)
{
// Add the accuracy to total accuary variable
totalAccuracyInMetres += location.Accuracy;
}
return ConvertMetresToKilometres(totalAccuracyInMetres / _journeyLocations.Count);
}
/// <summary>
/// Converts the input from metres to kilometres and rounds to two decimal places.
/// </summary>
/// <param name="metres">Metres as a Single.</param>
/// <returns>Returns a double representing the input converted to kilometres and rounded to two decimal places.</returns>
private Double ConvertMetresToKilometres(Single metres)
{
return Math.Round(metres / 1000, 2);
}
/// <summary>
/// A callback function for a timer to record the current gps location information
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RecordGpsLocation(object sender, ElapsedEventArgs e)
{
_journeyLocations.Add(_currentLocation);
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.