context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* DokiScriptParser.cs
*
* THIS FILE HAS BEEN GENERATED AUTOMATICALLY. DO NOT EDIT!
*/
using System.IO;
using PerCederberg.Grammatica.Runtime;
/**
* <remarks>A token stream parser.</remarks>
*/
internal class DokiScriptParser : RecursiveDescentParser {
/**
* <summary>An enumeration with the generated production node
* identity constants.</summary>
*/
private enum SynteticPatterns {
SUBPRODUCTION_1 = 3001,
SUBPRODUCTION_2 = 3002,
SUBPRODUCTION_3 = 3003,
SUBPRODUCTION_4 = 3004,
SUBPRODUCTION_5 = 3005
}
/**
* <summary>Creates a new parser with a default analyzer.</summary>
*
* <param name='input'>the input stream to read from</param>
*
* <exception cref='ParserCreationException'>if the parser
* couldn't be initialized correctly</exception>
*/
public DokiScriptParser(TextReader input)
: base(input) {
CreatePatterns();
}
/**
* <summary>Creates a new parser.</summary>
*
* <param name='input'>the input stream to read from</param>
*
* <param name='analyzer'>the analyzer to parse with</param>
*
* <exception cref='ParserCreationException'>if the parser
* couldn't be initialized correctly</exception>
*/
public DokiScriptParser(TextReader input, DokiScriptAnalyzer analyzer)
: base(input, analyzer) {
CreatePatterns();
}
/**
* <summary>Creates a new tokenizer for this parser. Can be overridden
* by a subclass to provide a custom implementation.</summary>
*
* <param name='input'>the input stream to read from</param>
*
* <returns>the tokenizer created</returns>
*
* <exception cref='ParserCreationException'>if the tokenizer
* couldn't be initialized correctly</exception>
*/
protected override Tokenizer NewTokenizer(TextReader input) {
return new DokiScriptTokenizer(input);
}
/**
* <summary>Initializes the parser by creating all the production
* patterns.</summary>
*
* <exception cref='ParserCreationException'>if the parser
* couldn't be initialized correctly</exception>
*/
private void CreatePatterns() {
ProductionPattern pattern;
ProductionPatternAlternative alt;
pattern = new ProductionPattern((int) DokiScriptConstants.DOKI,
"Doki");
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.PART, 1, -1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.PART,
"Part");
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.BLOCK, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.FLAG, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.OPTION, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.JUMP, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.BLOCK,
"Block");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.WORLD, 1, 1);
alt.AddProduction((int) SynteticPatterns.SUBPRODUCTION_1, 1, -1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.RETURN, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddProduction((int) SynteticPatterns.SUBPRODUCTION_2, 1, -1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.RETURN, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.ACTION,
"Action");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TAB, 1, 1);
alt.AddProduction((int) DokiScriptConstants.VOICE_ACTION, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TAB, 1, 1);
alt.AddProduction((int) DokiScriptConstants.OTHER_ACTION, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TAB, 1, 1);
alt.AddToken((int) DokiScriptConstants.TEXT, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.VOICE_ACTION,
"VoiceAction");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.VOICE, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 1, 1);
alt.AddProduction((int) SynteticPatterns.SUBPRODUCTION_3, 0, -1);
alt.AddToken((int) DokiScriptConstants.TEXT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.OTHER_ACTION,
"OtherAction");
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.TAG, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 1, 1);
alt.AddProduction((int) SynteticPatterns.SUBPRODUCTION_4, 0, -1);
alt.AddToken((int) DokiScriptConstants.SEMICOLON, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.TAG,
"Tag");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.BACKGROUND, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.WEATHER, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.SOUND, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.BGM, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.VIDEO, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.MOVE, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.POSTURE, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.ROLE, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.OTHER, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.KEY,
"Key");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.SRC, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TRANSITION, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TIME, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TYPE, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.LEVEL, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.MODE, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.POSITION, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.NAME, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.ANCHOR, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.TAG_PARAMETER, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY1, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY2, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY3, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY4, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY5, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY6, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY7, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY8, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.KEY9, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.LIVE2D, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.ZOOM, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.VALUE,
"Value");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.PARENTHESE_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.DECIMAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.COMMA, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.DECIMAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.COMMA, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.DECIMAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_RIGHT, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.PARENTHESE_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.DECIMAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.COMMA, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.DECIMAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_RIGHT, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.DECIMAL, 1, 1);
pattern.AddAlternative(alt);
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.QUOTED_TEXT, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.FLAG,
"Flag");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.SQUARE_BRACKET_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.QUOTED_TEXT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.COMMA, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_RIGHT, 1, 1);
alt.AddProduction((int) SynteticPatterns.SUBPRODUCTION_5, 0, -1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.SQUARE_BRACKET_RIGHT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.RETURN, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.OPTION,
"Option");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.ANGLE_BRACKET_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.CLICK, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.RETURN, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) DokiScriptConstants.JUMP,
"Jump");
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.PARENTHESE_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_RIGHT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.RETURN, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) SynteticPatterns.SUBPRODUCTION_1,
"Subproduction1");
pattern.Synthetic = true;
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.RETURN, 0, 1);
alt.AddProduction((int) DokiScriptConstants.ACTION, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) SynteticPatterns.SUBPRODUCTION_2,
"Subproduction2");
pattern.Synthetic = true;
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.RETURN, 0, 1);
alt.AddProduction((int) DokiScriptConstants.ACTION, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) SynteticPatterns.SUBPRODUCTION_3,
"Subproduction3");
pattern.Synthetic = true;
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.KEY, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.EQUAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddProduction((int) DokiScriptConstants.VALUE, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) SynteticPatterns.SUBPRODUCTION_4,
"Subproduction4");
pattern.Synthetic = true;
alt = new ProductionPatternAlternative();
alt.AddProduction((int) DokiScriptConstants.KEY, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.EQUAL, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddProduction((int) DokiScriptConstants.VALUE, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
pattern = new ProductionPattern((int) SynteticPatterns.SUBPRODUCTION_5,
"Subproduction5");
pattern.Synthetic = true;
alt = new ProductionPatternAlternative();
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.OR, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.QUOTED_TEXT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_LEFT, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.COMMA, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.IDENTIFIER, 1, 1);
alt.AddToken((int) DokiScriptConstants.SPACE, 0, 1);
alt.AddToken((int) DokiScriptConstants.PARENTHESE_RIGHT, 1, 1);
pattern.AddAlternative(alt);
AddPattern(pattern);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Net.Security;
using System.ServiceModel.Security;
namespace System.ServiceModel.Description
{
[DebuggerDisplay("Name={_name}, Namespace={_ns}, ContractType={_contractType}")]
public class ContractDescription
{
private Type _callbackContractType;
private string _configurationName;
private Type _contractType;
private XmlName _name;
private string _ns;
private OperationDescriptionCollection _operations;
private SessionMode _sessionMode;
private KeyedByTypeCollection<IContractBehavior> _behaviors = new KeyedByTypeCollection<IContractBehavior>();
private ProtectionLevel _protectionLevel;
private bool _hasProtectionLevel;
public ContractDescription(string name)
: this(name, null)
{
}
public ContractDescription(string name, string ns)
{
// the property setter validates given value
this.Name = name;
if (!string.IsNullOrEmpty(ns))
NamingHelper.CheckUriParameter(ns, "ns");
_operations = new OperationDescriptionCollection();
_ns = ns ?? NamingHelper.DefaultNamespace; // ns can be ""
}
internal string CodeName
{
get { return _name.DecodedName; }
}
[DefaultValue(null)]
public string ConfigurationName
{
get { return _configurationName; }
set { _configurationName = value; }
}
public Type ContractType
{
get { return _contractType; }
set { _contractType = value; }
}
public Type CallbackContractType
{
get { return _callbackContractType; }
set { _callbackContractType = value; }
}
public string Name
{
get { return _name.EncodedName; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (value.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("value", SR.SFxContractDescriptionNameCannotBeEmpty));
}
_name = new XmlName(value, true /*isEncoded*/);
}
}
public string Namespace
{
get { return _ns; }
set
{
if (!string.IsNullOrEmpty(value))
NamingHelper.CheckUriProperty(value, "Namespace");
_ns = value;
}
}
public OperationDescriptionCollection Operations
{
get { return _operations; }
}
public ProtectionLevel ProtectionLevel
{
get { return _protectionLevel; }
set
{
if (!ProtectionLevelHelper.IsDefined(value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
_protectionLevel = value;
_hasProtectionLevel = true;
}
}
public bool ShouldSerializeProtectionLevel()
{
return this.HasProtectionLevel;
}
public bool HasProtectionLevel
{
get { return _hasProtectionLevel; }
}
[DefaultValue(SessionMode.Allowed)]
public SessionMode SessionMode
{
get { return _sessionMode; }
set
{
if (!SessionModeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
_sessionMode = value;
}
}
public KeyedCollection<Type, IContractBehavior> ContractBehaviors
{
get { return this.Behaviors; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public KeyedByTypeCollection<IContractBehavior> Behaviors
{
get { return _behaviors; }
}
public static ContractDescription GetContract(Type contractType)
{
if (contractType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType");
TypeLoader typeLoader = new TypeLoader();
return typeLoader.LoadContractDescription(contractType);
}
public static ContractDescription GetContract(Type contractType, Type serviceType)
{
if (contractType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType");
if (serviceType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceType");
TypeLoader typeLoader = new TypeLoader();
ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType);
return description;
}
public static ContractDescription GetContract(Type contractType, object serviceImplementation)
{
if (contractType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType");
if (serviceImplementation == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceImplementation");
TypeLoader typeLoader = new TypeLoader();
Type serviceType = serviceImplementation.GetType();
ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType, serviceImplementation);
return description;
}
public Collection<ContractDescription> GetInheritedContracts()
{
Collection<ContractDescription> result = new Collection<ContractDescription>();
for (int i = 0; i < Operations.Count; i++)
{
OperationDescription od = Operations[i];
if (od.DeclaringContract != this)
{
ContractDescription inheritedContract = od.DeclaringContract;
if (!result.Contains(inheritedContract))
{
result.Add(inheritedContract);
}
}
}
return result;
}
internal void EnsureInvariants()
{
if (string.IsNullOrEmpty(this.Name))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.AChannelServiceEndpointSContractSNameIsNull0));
}
if (this.Namespace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.AChannelServiceEndpointSContractSNamespace0));
}
if (this.Operations.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxContractHasZeroOperations, this.Name)));
}
bool thereIsAtLeastOneInitiatingOperation = false;
for (int i = 0; i < this.Operations.Count; i++)
{
OperationDescription operationDescription = this.Operations[i];
operationDescription.EnsureInvariants();
if (operationDescription.IsInitiating)
thereIsAtLeastOneInitiatingOperation = true;
if ((!operationDescription.IsInitiating || operationDescription.IsTerminating)
&& (this.SessionMode != SessionMode.Required))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.ContractIsNotSelfConsistentItHasOneOrMore2, this.Name)));
}
}
if (!thereIsAtLeastOneInitiatingOperation)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxContractHasZeroInitiatingOperations, this.Name)));
}
}
internal bool IsDuplex()
{
for (int i = 0; i < _operations.Count; ++i)
{
if (_operations[i].IsServerInitiated())
{
return true;
}
}
return false;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System
{
[Immutable]
public class Type
{
public string Namespace
{
get;
}
public bool IsMarshalByRef
{
get;
}
public System.Reflection.ConstructorInfo TypeInitializer
{
get;
}
public bool IsExplicitLayout
{
get;
}
public bool IsValueType
{
get;
}
public bool IsAutoClass
{
get;
}
public bool IsNestedPrivate
{
get;
}
public bool IsSerializable
{
get;
}
public System.Reflection.Assembly! Assembly
{
get;
}
public bool IsNestedAssembly
{
get;
}
public bool IsNotPublic
{
get;
}
public bool IsSealed
{
get;
}
public Guid GUID
{
get;
}
public bool IsLayoutSequential
{
get;
}
public bool IsNestedFamily
{
get;
}
public bool IsNestedFamORAssem
{
get;
}
public string FullName
{
get;
}
public virtual Type! MakeArrayType() {
return default(virtual);
}
public System.Reflection.MemberTypes MemberType
{
get;
}
public string AssemblyQualifiedName
{
get;
}
public Type BaseType
{
get;
}
public RuntimeTypeHandle TypeHandle
{
get;
}
public bool IsInterface
{
get;
}
public bool IsAnsiClass
{
get;
}
public bool IsAutoLayout
{
get;
}
public bool IsPointer
{
get;
}
public bool IsEnum
{
get;
}
public Type ReflectedType
{
get;
}
public System.Reflection.TypeAttributes Attributes
{
get;
}
public Type DeclaringType
{
get;
}
public bool IsNestedFamANDAssem
{
get;
}
public bool IsContextful
{
get;
}
public bool IsClass
{
get;
}
public bool IsPublic
{
get;
}
public bool IsAbstract
{
get;
}
public Type UnderlyingSystemType
{
get;
}
public bool IsPrimitive
{
get;
}
public System.Reflection.Module! Module
{
get;
}
public bool IsImport
{
get;
}
public bool IsArray
{
get;
}
public bool IsNestedPublic
{
get;
}
public bool IsByRef
{
get;
}
public bool IsSpecialName
{
get;
}
public bool IsUnicodeClass
{
get;
}
public static System.Reflection.Binder DefaultBinder
{
get;
}
public bool HasElementType
{
get;
}
public bool IsCOMObject
{
get;
}
public System.Reflection.InterfaceMapping GetInterfaceMap (Type interfaceType) {
return default(System.Reflection.InterfaceMapping);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int GetHashCode () {
return default(int);
}
public bool Equals (Type o) {
return default(bool);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public bool Equals (object o) {
return default(bool);
}
public static Type[] GetTypeArray (Object[]! args) {
CodeContract.Requires(args != null);
return default(Type[]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public string ToString () {
CodeContract.Ensures(CodeContract.Result<string>() != null);
return default(string);
}
public bool IsAssignableFrom (Type c) {
return default(bool);
}
public bool IsInstanceOfType (object o) {
return default(bool);
}
public bool IsSubclassOf (Type c) {
return default(bool);
}
public Type GetElementType () {
return default(Type);
}
public System.Reflection.MemberInfo[] FindMembers (System.Reflection.MemberTypes memberType, System.Reflection.BindingFlags bindingAttr, System.Reflection.MemberFilter filter, object filterCriteria) {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.MemberInfo[] GetDefaultMembers () {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.MemberInfo[] GetMembers (System.Reflection.BindingFlags arg0) {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.MemberInfo[] GetMembers () {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.MemberInfo[] GetMember (string name) {
return default(System.Reflection.MemberInfo[]);
}
public Type GetNestedType (string arg0, System.Reflection.BindingFlags arg1) {
return default(Type);
}
public Type GetNestedType (string name) {
return default(Type);
}
public Type[] GetNestedTypes (System.Reflection.BindingFlags arg0) {
return default(Type[]);
}
public Type[] GetNestedTypes () {
return default(Type[]);
}
public System.Reflection.PropertyInfo[] GetProperties () {
return default(System.Reflection.PropertyInfo[]);
}
public System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags arg0) {
return default(System.Reflection.PropertyInfo[]);
}
public System.Reflection.PropertyInfo GetProperty (string! name) {
CodeContract.Requires(name != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.PropertyInfo GetProperty (string! name, Type! returnType) {
CodeContract.Requires(name != null);
CodeContract.Requires(returnType != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.PropertyInfo GetProperty (string! name, Type[]! types) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.PropertyInfo GetProperty (string! name, Type returnType, Type[]! types) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.PropertyInfo GetProperty (string! name, System.Reflection.BindingFlags bindingAttr) {
CodeContract.Requires(name != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.PropertyInfo GetProperty (string! name, Type returnType, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.PropertyInfo GetProperty (string! name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.PropertyInfo);
}
public System.Reflection.EventInfo[] GetEvents (System.Reflection.BindingFlags arg0) {
return default(System.Reflection.EventInfo[]);
}
public System.Reflection.EventInfo[] GetEvents () {
return default(System.Reflection.EventInfo[]);
}
public System.Reflection.EventInfo GetEvent (string arg0, System.Reflection.BindingFlags arg1) {
return default(System.Reflection.EventInfo);
}
public System.Reflection.EventInfo GetEvent (string name) {
return default(System.Reflection.EventInfo);
}
public Type[] FindInterfaces (System.Reflection.TypeFilter! filter, object filterCriteria) {
CodeContract.Requires(filter != null);
return default(Type[]);
}
public Type[] GetInterfaces () {
return default(Type[]);
}
public Type GetInterface (string arg0, bool arg1) {
return default(Type);
}
public Type GetInterface (string name) {
return default(Type);
}
public System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags arg0) {
return default(System.Reflection.FieldInfo[]);
}
public System.Reflection.FieldInfo[] GetFields () {
return default(System.Reflection.FieldInfo[]);
}
public System.Reflection.FieldInfo GetField (string name) {
return default(System.Reflection.FieldInfo);
}
public System.Reflection.FieldInfo GetField (string arg0, System.Reflection.BindingFlags arg1) {
return default(System.Reflection.FieldInfo);
}
public System.Reflection.MethodInfo[] GetMethods (System.Reflection.BindingFlags arg0) {
return default(System.Reflection.MethodInfo[]);
}
public System.Reflection.MethodInfo[] GetMethods () {
return default(System.Reflection.MethodInfo[]);
}
public System.Reflection.MethodInfo GetMethod (string! name) {
CodeContract.Requires(name != null);
return default(System.Reflection.MethodInfo);
}
public System.Reflection.MethodInfo GetMethod (string! name, System.Reflection.BindingFlags bindingAttr) {
CodeContract.Requires(name != null);
return default(System.Reflection.MethodInfo);
}
public System.Reflection.MethodInfo GetMethod (string! name, Type[]! types) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.MethodInfo);
}
public System.Reflection.MethodInfo GetMethod (string! name, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.MethodInfo);
}
public System.Reflection.MethodInfo GetMethod (string! name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.MethodInfo);
}
public System.Reflection.MethodInfo GetMethod (string! name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(name != null);
CodeContract.Requires(types != null);
return default(System.Reflection.MethodInfo);
}
public System.Reflection.ConstructorInfo[] GetConstructors (System.Reflection.BindingFlags arg0) {
return default(System.Reflection.ConstructorInfo[]);
}
public System.Reflection.ConstructorInfo[] GetConstructors () {
return default(System.Reflection.ConstructorInfo[]);
}
public System.Reflection.ConstructorInfo GetConstructor (Type[] types) {
return default(System.Reflection.ConstructorInfo);
}
public System.Reflection.ConstructorInfo GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(types != null);
return default(System.Reflection.ConstructorInfo);
}
public System.Reflection.ConstructorInfo GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[]! types, System.Reflection.ParameterModifier[] modifiers) {
CodeContract.Requires(types != null);
return default(System.Reflection.ConstructorInfo);
}
public int GetArrayRank () {
return default(int);
}
public static Type GetTypeFromHandle (RuntimeTypeHandle handle) {
return default(Type);
}
public static RuntimeTypeHandle GetTypeHandle (object! o) {
CodeContract.Requires(o != null);
return default(RuntimeTypeHandle);
}
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, Object[] args) {
return default(object);
}
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, Object[] args, System.Globalization.CultureInfo culture) {
return default(object);
}
public object InvokeMember (string arg0, System.Reflection.BindingFlags arg1, System.Reflection.Binder arg2, object arg3, Object[] arg4, System.Reflection.ParameterModifier[] arg5, System.Globalization.CultureInfo arg6, String[] arg7) {
return default(object);
}
public static TypeCode GetTypeCode (Type type) {
return default(TypeCode);
}
public static Type GetTypeFromCLSID (Guid clsid, string server, bool throwOnError) {
return default(Type);
}
public static Type GetTypeFromCLSID (Guid clsid, string server) {
return default(Type);
}
public static Type GetTypeFromCLSID (Guid clsid, bool throwOnError) {
return default(Type);
}
public static Type GetTypeFromCLSID (Guid clsid) {
return default(Type);
}
public static Type GetTypeFromProgID (string progID, string server, bool throwOnError) {
return default(Type);
}
public static Type GetTypeFromProgID (string progID, string server) {
return default(Type);
}
public static Type GetTypeFromProgID (string progID, bool throwOnError) {
return default(Type);
}
public static Type GetTypeFromProgID (string progID) {
return default(Type);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)][ResultNotNewlyAllocated]
public Type GetType () {
CodeContract.Ensures(CodeContract.Result<Type>() != null);
return default(Type);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static Type GetType (string typeName) {
CodeContract.Ensures(CodeContract.Result<Type>() != null);
return default(Type);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static Type GetType (string typeName, bool throwOnError) {
CodeContract.Ensures(throwOnError ==> result != null);
return default(Type);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static Type GetType (string typeName, bool throwOnError, bool ignoreCase) {
CodeContract.Ensures(throwOnError ==> result != null);
return default(Type);
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using VirtualPath;
namespace VirtualPath.Common
{
public abstract class AbstractVirtualDirectoryBase : IVirtualDirectory
{
public IVirtualPathProvider VirtualPathProvider { get; private set; }
public IVirtualDirectory ParentDirectory { get; set; }
public IVirtualDirectory Directory { get { return this; } }
public abstract DateTime LastModified { get; }
public virtual string VirtualPath { get { return GetVirtualPathToRoot(); } }
public virtual string RealPath { get { return GetRealPathToRoot(); } }
public virtual bool IsDirectory { get { return true; } }
public virtual bool IsRoot { get { return ParentDirectory == null; } }
public abstract IEnumerable<IVirtualFile> Files { get; }
public abstract IEnumerable<IVirtualDirectory> Directories { get; }
public abstract string Name { get; }
protected AbstractVirtualDirectoryBase(IVirtualPathProvider owningProvider)
: this(owningProvider, null) {}
protected AbstractVirtualDirectoryBase(IVirtualPathProvider owningProvider, IVirtualDirectory parentDirectory)
{
if (owningProvider == null)
throw new ArgumentNullException("owningProvider");
this.VirtualPathProvider = owningProvider;
this.ParentDirectory = parentDirectory;
}
public virtual IVirtualFile GetFile(string virtualPath)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
return GetFile(tokens);
}
public virtual IVirtualDirectory GetDirectory(string virtualPath)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
return GetDirectory(tokens);
}
private string UntokenizeVirtualPath(Stack<string> virtualPath)
{
return virtualPath.Aggregate((a, b) => this.VirtualPathProvider.CombineVirtualPath(a, b));
}
public virtual IVirtualFile GetFile(Stack<string> virtualPath)
{
if (virtualPath.Count == 0)
return null;
var pathToken = virtualPath.Pop();
if (virtualPath.Count == 0)
return GetFileFromBackingDirectoryOrDefault(pathToken);
var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken);
return virtDir != null
? virtDir.GetFile(UntokenizeVirtualPath(virtualPath))
: null;
}
public virtual IVirtualDirectory GetDirectory(Stack<string> virtualPath)
{
if (virtualPath.Count == 0)
return null;
var pathToken = virtualPath.Pop();
var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken);
if (virtDir == null)
return null;
return virtualPath.Count == 0
? virtDir
: virtDir.GetDirectory(UntokenizeVirtualPath(virtualPath));
}
public virtual IEnumerable<IVirtualFile> GetAllMatchingFiles(string globPattern, int maxDepth = Int32.MaxValue)
{
if (maxDepth == 0)
yield break;
foreach (var f in GetMatchingFilesInDir(globPattern))
yield return f;
foreach (var childDir in Directories)
{
var matchingFilesInChildDir = childDir.GetAllMatchingFiles(globPattern, maxDepth - 1);
foreach (var f in matchingFilesInChildDir)
yield return f;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
protected virtual string GetVirtualPathToRoot()
{
if (IsRoot)
return VirtualPathProvider.VirtualPathSeparator;
return GetPathToRoot(VirtualPathProvider.VirtualPathSeparator, p => p.VirtualPath);
}
protected virtual string GetRealPathToRoot()
{
return GetPathToRoot(VirtualPathProvider.RealPathSeparator, p => p.RealPath);
}
protected virtual string GetPathToRoot(string separator, Func<IVirtualDirectory, string> pathSel)
{
var parentPath = ParentDirectory != null ? pathSel(ParentDirectory) : string.Empty;
if (parentPath == separator)
parentPath = string.Empty;
return string.Concat(parentPath, separator, Name);
}
public override bool Equals(object obj)
{
var other = obj as AbstractVirtualDirectoryBase;
if (other == null)
return false;
return other.VirtualPath == this.VirtualPath;
}
public override int GetHashCode()
{
return VirtualPath.GetHashCode();
}
public override string ToString()
{
return string.Format("{0} -> {1}", RealPath, VirtualPath);
}
public abstract IEnumerator<IVirtualNode> GetEnumerator();
protected abstract IVirtualFile GetFileFromBackingDirectoryOrDefault(string fileName);
protected virtual IEnumerable<IVirtualFile> GetMatchingFilesInDir(string globPattern)
{
return EnumerateFiles(globPattern);
}
public virtual IEnumerable<IVirtualFile> EnumerateFiles(string pattern)
{
return Files.Where(file => file.Name.Glob(pattern));
}
protected abstract IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName);
public IVirtualFile CreateFile(string virtualPath, string contents)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
return AddFile(tokens, contents);
}
public IVirtualFile CreateFile(string virtualPath, byte[] contents)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
return AddFile(tokens, contents);
}
public IVirtualFile AddFile(Stack<string> virtualPath, string contents)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(contents);
return AddFile(virtualPath, bytes);
}
public IVirtualFile AddFile(Stack<string> virtualPath, byte[] contents)
{
if (virtualPath.Count == 0)
return null;
var pathToken = virtualPath.Pop();
if (virtualPath.Count == 0)
{
return AddFileToBackingDirectoryOrDefault(pathToken, contents);
}
var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken);
if(virtDir != null)
{
return virtDir.CreateFile(UntokenizeVirtualPath(virtualPath), contents);
}
return null;
}
protected abstract IVirtualFile AddFileToBackingDirectoryOrDefault(string fileName, byte[] contents);
public void Delete(string virtualPath)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
Delete(tokens);
}
public void Delete(Stack<string> virtualPath)
{
if (virtualPath.Count == 0)
return;
var pathToken = virtualPath.Pop();
if (virtualPath.Count == 0)
{
DeleteBackingDirectoryOrFile(pathToken);
return;
}
var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken);
if (virtDir != null)
{
virtDir.Delete(UntokenizeVirtualPath(virtualPath));
}
}
protected abstract void DeleteBackingDirectoryOrFile(string pathToken);
public virtual void Delete()
{
var parentDir = (AbstractVirtualDirectoryBase)this.ParentDirectory;
if (parentDir == null)
{
throw new ArgumentException("Delete root directory not allowed.");
}
parentDir.Delete(this.Name);
}
public IVirtualDirectory CreateDirectory(string virtualPath)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
return AddDirectory(tokens);
}
public IVirtualDirectory AddDirectory(Stack<string> virtualPath)
{
if (virtualPath.Count == 0)
return null;
var pathToken = virtualPath.Pop();
if (virtualPath.Count == 0)
{
return AddDirectoryToBackingDirectoryOrDefault(pathToken);
}
var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken);
if (virtDir == null)
{
virtDir = AddDirectoryToBackingDirectoryOrDefault(pathToken);
}
return virtDir.CreateDirectory(UntokenizeVirtualPath(virtualPath));
}
protected abstract IVirtualDirectory AddDirectoryToBackingDirectoryOrDefault(string name);
public System.IO.Stream CreateFile(string virtualPath)
{
var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider);
return AddFile(tokens);
}
public virtual System.IO.Stream AddFile(Stack<string> virtualPath)
{
if (virtualPath.Count == 0)
return null;
var pathToken = virtualPath.Pop();
if (virtualPath.Count == 0)
{
return AddFileToBackingDirectoryOrDefault(pathToken);
}
var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken);
if (virtDir != null)
{
return virtDir.CreateFile(UntokenizeVirtualPath(virtualPath));
}
return null;
}
protected abstract System.IO.Stream AddFileToBackingDirectoryOrDefault(string fileName);
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using Boo.Lang.Resources;
using Boo.Lang.Runtime;
namespace Boo.Lang
{
public delegate TResult Function<in T1, out TResult>(T1 arg);
#if !NO_SERIALIZATION_INFO
[Serializable]
#endif
public class List<T> : IList<T>, IList, IEquatable<List<T>>
{
private static readonly T[] EmptyArray = new T[0];
protected T[] _items;
protected int _count;
public List()
{
_items = EmptyArray;
}
public List(IEnumerable enumerable) : this()
{
Extend(enumerable);
}
public List(int initialCapacity)
{
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException("initialCapacity");
_items = new T[initialCapacity];
_count = 0;
}
public List(T[] items, bool takeOwnership)
{
if (null == items)
throw new ArgumentNullException("items");
_items = takeOwnership ? items : (T[]) items.Clone();
_count = items.Length;
}
public static List<T> operator*(List<T> lhs, int count)
{
return lhs.Multiply(count);
}
public static List<T> operator*(int count, List<T> rhs)
{
return rhs.Multiply(count);
}
public static List<T> operator+(List<T> lhs, IEnumerable rhs)
{
var result = lhs.NewConcreteList(lhs.ToArray(), true);
result.Extend(rhs);
return result;
}
public List<T> Multiply(int count)
{
if (count < 0)
throw new ArgumentOutOfRangeException("count");
var items = new T[_count*count];
for (int i=0; i<count; ++i)
Array.Copy(_items, 0, items, i*_count, _count);
return NewConcreteList(items, true);
}
protected virtual List<T> NewConcreteList(T[] items, bool takeOwnership)
{
return new List<T>(items, takeOwnership);
}
public IEnumerable<T> Reversed
{
get
{
for (int i=_count-1; i>=0; --i)
yield return _items[i];
}
}
public int Count
{
get { return _count; }
}
void ICollection<T>.Add(T item)
{
Push(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>) this).GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
int originalCount = _count;
T[] originalItems = _items;
for (int i = 0; i < _count; ++i)
{
if (originalCount != _count || originalItems != _items)
throw new InvalidOperationException(StringResources.ListWasModified);
yield return _items[i];
}
}
public void CopyTo(T[] target, int index)
{
Array.Copy(_items, 0, target, index, _count);
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return _items; }
}
public bool IsReadOnly
{
get { return false; }
}
public T this[int index]
{
get { return _items[CheckIndex(NormalizeIndex(index))]; }
set { _items[CheckIndex(NormalizeIndex(index))] = value; }
}
public T FastAt(int normalizedIndex)
{
return _items[normalizedIndex];
}
public List<T> Push(T item)
{
return Add(item);
}
public virtual List<T> Add(T item)
{
EnsureCapacity(_count+1);
_items[_count] = item;
++_count;
return this;
}
public List<T> AddUnique(T item)
{
if (!Contains(item))
Add(item);
return this;
}
public List<T> Extend(IEnumerable enumerable)
{
AddRange(enumerable);
return this;
}
public void AddRange(IEnumerable enumerable)
{
foreach (T item in enumerable)
Add(item);
}
public List<T> ExtendUnique(IEnumerable enumerable)
{
foreach (T item in enumerable)
AddUnique(item);
return this;
}
public List<T> Collect(Predicate<T> condition)
{
if (null == condition)
throw new ArgumentNullException("condition");
var newList = NewConcreteList(new T[0], true);
InnerCollect(newList, condition);
return newList;
}
public List<T> Collect(List<T> target, Predicate<T> condition)
{
if (null == target)
throw new ArgumentNullException("target");
if (null == condition)
throw new ArgumentNullException("condition");
InnerCollect(target, condition);
return target;
}
public T[] ToArray()
{
if (_count == 0)
return EmptyArray;
var target = new T[_count];
CopyTo(target, 0);
return target;
}
public T[] ToArray(T[] array)
{
CopyTo(array, 0);
return array;
}
public TOut[] ToArray<TOut>(Function<T, TOut> selector)
{
var result = new TOut[_count];
for (var i = 0; i < _count; ++i)
result[i] = selector(_items[i]);
return result;
}
public List<T> Sort()
{
Array.Sort(_items, 0, _count, BooComparer.Default);
return this;
}
public List<T> Sort(IComparer comparer)
{
Array.Sort(_items, 0, _count, comparer);
return this;
}
private sealed class ComparisonComparer : IComparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
#region IComparer<T> Members
public int Compare(T x, T y)
{
return _comparison(x, y);
}
#endregion
}
public List<T> Sort(Comparison<T> comparison)
{
return Sort(new ComparisonComparer(comparison));
}
public List<T> Sort(IComparer<T> comparer)
{
Array.Sort(_items, 0, _count, comparer);
return this;
}
public List<T> Sort(Comparer<T> comparer)
{
if (null == comparer)
throw new ArgumentNullException("comparer");
Array.Sort(_items, 0, _count, comparer);
return this;
}
override public string ToString()
{
return "[" + Join(", ") + "]";
}
public string Join(string separator)
{
return Builtins.join(this, separator);
}
override public int GetHashCode()
{
var hash = _count;
for (var i=0; i<_count; ++i)
{
var item = _items[i];
if (item != null)
hash ^= item.GetHashCode();
}
return hash;
}
override public bool Equals(object other)
{
return this == other || Equals(other as List<T>);
}
public bool Equals(List<T> other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
if (_count != other.Count) return false;
for (var i=0; i < _count; ++i)
if (!RuntimeServices.EqualityOperator(_items[i], other[i]))
return false;
return true;
}
public void Clear()
{
for (int i=0; i<_count; ++i)
_items[i] = default(T);
_count = 0;
}
public List<T> GetRange(int begin)
{
return InnerGetRange(AdjustIndex(NormalizeIndex(begin)), _count);
}
public List<T> GetRange(int begin, int end)
{
return InnerGetRange(
AdjustIndex(NormalizeIndex(begin)),
AdjustIndex(NormalizeIndex(end)));
}
public bool Contains(T item)
{
return -1 != IndexOf(item);
}
public bool Contains(Predicate<T> condition)
{
return -1 != IndexOf(condition);
}
public bool Find(Predicate<T> condition, out T found)
{
int index = IndexOf(condition);
if (-1 != index)
{
found = _items[index];
return true;
}
found = default(T);
return false;
}
public List<T> FindAll(Predicate<T> condition)
{
var result = NewConcreteList(new T[0], true);
foreach (T item in this)
if (condition(item)) result.Add(item);
return result;
}
public int IndexOf(Predicate<T> condition)
{
if (null == condition)
throw new ArgumentNullException("condition");
for (int i=0; i<_count; ++i)
if (condition(_items[i]))
return i;
return -1;
}
public int IndexOf(T item)
{
for (int i=0; i<_count; ++i)
if (RuntimeServices.EqualityOperator(_items[i], item))
return i;
return -1;
}
public List<T> Insert(int index, T item)
{
int actual = NormalizeIndex(index);
EnsureCapacity(Math.Max(_count, actual) + 1);
if (actual < _count)
Array.Copy(_items, actual, _items, actual+1, _count-actual);
_items[actual] = item;
++_count;
return this;
}
public T Pop()
{
return Pop(-1);
}
public T Pop(int index)
{
int actualIndex = CheckIndex(NormalizeIndex(index));
T item = _items[actualIndex];
InnerRemoveAt(actualIndex);
return item;
}
public List<T> PopRange(int begin)
{
int actualIndex = AdjustIndex(NormalizeIndex(begin));
List<T> range = InnerGetRange(actualIndex, AdjustIndex(NormalizeIndex(_count)));
for (int i=actualIndex; i<_count; ++i)
_items[i] = default(T);
_count = actualIndex;
return range;
}
public List<T> RemoveAll(Predicate<T> match)
{
if (null == match) throw new ArgumentNullException("match");
for (int i=0; i<_count; ++i)
if (match(_items[i])) InnerRemoveAt(i--);
return this;
}
public List<T> Remove(T item)
{
InnerRemove(item);
return this;
}
public List<T> RemoveAt(int index)
{
InnerRemoveAt(CheckIndex(NormalizeIndex(index)));
return this;
}
void IList<T>.Insert(int index, T item)
{
Insert(index, item);
}
void IList<T>.RemoveAt(int index)
{
InnerRemoveAt(CheckIndex(NormalizeIndex(index)));
}
bool ICollection<T>.Remove(T item)
{
return InnerRemove(item);
}
void EnsureCapacity(int minCapacity)
{
if (minCapacity > _items.Length)
{
T[] items = NewArray(minCapacity);
Array.Copy(_items, 0, items, 0, _count);
_items = items;
}
}
T[] NewArray(int minCapacity)
{
int newLen = Math.Max(1, _items.Length)*2;
return new T[Math.Max(newLen, minCapacity)];
}
void InnerRemoveAt(int index)
{
--_count;
_items[index] = default(T);
if (index != _count)
Array.Copy(_items, index+1, _items, index, _count-index);
}
bool InnerRemove(T item)
{
int index = IndexOf(item);
if (index != -1)
{
InnerRemoveAt(index);
return true;
}
return false;
}
void InnerCollect(List<T> target, Predicate<T> condition)
{
for (int i=0; i<_count; ++i)
{
T item = _items[i];
if (condition(item))
target.Add(item);
}
}
List<T> InnerGetRange(int begin, int end)
{
int targetLen = end-begin;
if (targetLen > 0)
{
var target = new T[targetLen];
Array.Copy(_items, begin, target, 0, targetLen);
return NewConcreteList(target, true);
}
return NewConcreteList(new T[0], true);
}
int AdjustIndex(int index)
{
if (index > _count)
return _count;
if (index < 0)
return 0;
return index;
}
int CheckIndex(int index)
{
if (index >= _count)
throw new IndexOutOfRangeException();
return index;
}
int NormalizeIndex(int index)
{
return index < 0 ? index + _count : index;
}
#region IList Members
int IList.Add(object value)
{
Add((T)value);
return Count - 1;
}
void IList.Insert(int index, object value)
{
Insert(index, Coerce(value));
}
private static T Coerce(object value)
{
if (value is T) return (T) value;
return (T)RuntimeServices.Coerce(value, typeof(T));
}
void IList.Remove(object value)
{
Remove(Coerce(value));
}
int IList.IndexOf(object value)
{
return IndexOf(Coerce(value));
}
bool IList.Contains(object value)
{
return Contains(Coerce(value));
}
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = Coerce(value); }
}
void IList.RemoveAt(int index)
{
RemoveAt(index);
}
bool IList.IsFixedSize
{
get { return false; }
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
Array.Copy(_items, 0, array, index, _count);
}
#endregion
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Collections;
namespace log4net.Appender
{
/// <summary>
/// A strongly-typed collection of <see cref="IAppender"/> objects.
/// </summary>
#if !NETCF
[Serializable]
#endif
public class AppenderCollection : ICollection, IList, IEnumerable, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="AppenderCollection"/>.
/// </summary>
public interface IAppenderCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
IAppender Current {get;}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private IAppender[] m_array;
private int m_count = 0;
#if !NETCF
[NonSerialized]
#endif
private int m_version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a synchronized (thread-safe) wrapper for a
/// <c>AppenderCollection</c> instance.
/// </summary>
/// <returns>
/// An <c>AppenderCollection</c> wrapper that is synchronized (thread-safe).
/// </returns>
public static AppenderCollection Synchronized(AppenderCollection list)
{
if(list==null)
throw new ArgumentNullException("list");
return new SyncAppenderCollection(list);
}
/// <summary>
/// Creates a read-only wrapper for a
/// <c>AppenderCollection</c> instance.
/// </summary>
/// <returns>
/// An <c>AppenderCollection</c> wrapper that is read-only.
/// </returns>
public static AppenderCollection ReadOnly(AppenderCollection list)
{
if(list==null)
throw new ArgumentNullException("list");
return new ReadOnlyAppenderCollection(list);
}
#endregion
#region Static Fields
/// <summary>
/// An empty readonly static AppenderCollection
/// </summary>
public static readonly AppenderCollection EmptyCollection = ReadOnly(new AppenderCollection(0));
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public AppenderCollection()
{
m_array = new IAppender[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>AppenderCollection</c> is initially capable of storing.
/// </param>
public AppenderCollection(int capacity)
{
m_array = new IAppender[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <c>AppenderCollection</c>.
/// </summary>
/// <param name="c">The <c>AppenderCollection</c> whose elements are copied to the new collection.</param>
public AppenderCollection(AppenderCollection c)
{
m_array = new IAppender[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <see cref="IAppender"/> array.
/// </summary>
/// <param name="a">The <see cref="IAppender"/> array whose elements are copied to the new list.</param>
public AppenderCollection(IAppender[] a)
{
m_array = new IAppender[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <see cref="IAppender"/> collection.
/// </summary>
/// <param name="col">The <see cref="IAppender"/> collection whose elements are copied to the new list.</param>
public AppenderCollection(ICollection col)
{
m_array = new IAppender[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
protected enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="t"></param>
protected AppenderCollection(Tag t)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>AppenderCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>AppenderCollection</c> to a one-dimensional
/// <see cref="IAppender"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IAppender"/> array to copy to.</param>
public virtual void CopyTo(IAppender[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>AppenderCollection</c> to a one-dimensional
/// <see cref="IAppender"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IAppender"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(IAppender[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
throw new System.ArgumentException("Destination array was not long enough.");
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <returns>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</returns>
public virtual bool IsSynchronized
{
get { return m_array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return m_array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="IAppender"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual IAppender this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="IAppender"/> to the end of the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(IAppender item)
{
if (m_count == m_array.Length)
EnsureCapacity(m_count + 1);
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>AppenderCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new IAppender[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="AppenderCollection"/>.
/// </summary>
public virtual object Clone()
{
AppenderCollection newColl = new AppenderCollection(m_count);
Array.Copy(m_array, 0, newColl.m_array, 0, m_count);
newColl.m_count = m_count;
newColl.m_version = m_version;
return newColl;
}
/// <summary>
/// Determines whether a given <see cref="IAppender"/> is in the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>AppenderCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(IAppender item)
{
for (int i=0; i != m_count; ++i)
if (m_array[i].Equals(item))
return true;
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="IAppender"/>
/// in the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to locate in the <c>AppenderCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>AppenderCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(IAppender item)
{
for (int i=0; i != m_count; ++i)
if (m_array[i].Equals(item))
return i;
return -1;
}
/// <summary>
/// Inserts an element into the <c>AppenderCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="IAppender"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, IAppender item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
EnsureCapacity(m_count + 1);
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="IAppender"/> from the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to remove from the <c>AppenderCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="IAppender"/> was not found in the <c>AppenderCollection</c>.
/// </exception>
public virtual void Remove(IAppender item)
{
int i = IndexOf(item);
if (i < 0)
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>AppenderCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
IAppender[] temp = new IAppender[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>AppenderCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>AppenderCollection</c>.</returns>
public virtual Enumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>AppenderCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get { return m_array.Length; }
set
{
if (value < m_count)
value = m_count;
if (value != m_array.Length)
{
if (value > 0)
{
IAppender[] temp = new IAppender[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new IAppender[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>AppenderCollection</c> to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="x">The <c>AppenderCollection</c> whose elements should be added to the end of the current <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(AppenderCollection x)
{
if (m_count + x.Count >= m_array.Length)
EnsureCapacity(m_count + x.Count);
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IAppender"/> array to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="x">The <see cref="IAppender"/> array whose elements should be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(IAppender[] x)
{
if (m_count + x.Length >= m_array.Length)
EnsureCapacity(m_count + x.Length);
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IAppender"/> collection to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="col">The <see cref="IAppender"/> collection whose elements should be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
EnsureCapacity(m_count + col.Count);
foreach(object item in col)
{
Add((IAppender)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd)?(m_count):(m_count-1);
if (i < 0 || i > max)
throw new System.ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
newCapacity = min;
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
Array.Copy(m_array, 0, array, start, m_count);
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (IAppender)value; }
}
int IList.Add(object x)
{
return this.Add((IAppender)x);
}
bool IList.Contains(object x)
{
return this.Contains((IAppender)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((IAppender)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (IAppender)x);
}
void IList.Remove(object x)
{
this.Remove((IAppender)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="AppenderCollection"/>.
/// </summary>
public class Enumerator : IEnumerator, IAppenderCollectionEnumerator
{
#region Implementation (data)
private AppenderCollection m_collection;
private int m_index;
private int m_version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(AppenderCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public IAppender Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
++m_index;
return (m_index < m_collection.Count) ? true : false;
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return (object)(this.Current); }
}
#endregion
}
#endregion
#region Nested Syncronized Wrapper class
private class SyncAppenderCollection : AppenderCollection
{
#region Implementation (data)
private AppenderCollection m_collection;
private object m_root;
#endregion
#region Construction
internal SyncAppenderCollection(AppenderCollection list) : base(Tag.Default)
{
m_root = list.SyncRoot;
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(IAppender[] array)
{
lock(this.m_root)
m_collection.CopyTo(array);
}
public override void CopyTo(IAppender[] array, int start)
{
lock(this.m_root)
m_collection.CopyTo(array,start);
}
public override int Count
{
get
{
lock(this.m_root)
return m_collection.Count;
}
}
public override bool IsSynchronized
{
get { return true; }
}
public override object SyncRoot
{
get { return this.m_root; }
}
#endregion
#region Type-safe IList
public override IAppender this[int i]
{
get
{
lock(this.m_root)
return m_collection[i];
}
set
{
lock(this.m_root)
m_collection[i] = value;
}
}
public override int Add(IAppender x)
{
lock(this.m_root)
return m_collection.Add(x);
}
public override void Clear()
{
lock(this.m_root)
m_collection.Clear();
}
public override bool Contains(IAppender x)
{
lock(this.m_root)
return m_collection.Contains(x);
}
public override int IndexOf(IAppender x)
{
lock(this.m_root)
return m_collection.IndexOf(x);
}
public override void Insert(int pos, IAppender x)
{
lock(this.m_root)
m_collection.Insert(pos,x);
}
public override void Remove(IAppender x)
{
lock(this.m_root)
m_collection.Remove(x);
}
public override void RemoveAt(int pos)
{
lock(this.m_root)
m_collection.RemoveAt(pos);
}
public override bool IsFixedSize
{
get {return m_collection.IsFixedSize;}
}
public override bool IsReadOnly
{
get {return m_collection.IsReadOnly;}
}
#endregion
#region Type-safe IEnumerable
public override Enumerator GetEnumerator()
{
lock(m_root)
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get
{
lock(this.m_root)
return m_collection.Capacity;
}
set
{
lock(this.m_root)
m_collection.Capacity = value;
}
}
public override int AddRange(AppenderCollection x)
{
lock(this.m_root)
return m_collection.AddRange(x);
}
public override int AddRange(IAppender[] x)
{
lock(this.m_root)
return m_collection.AddRange(x);
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
private class ReadOnlyAppenderCollection : AppenderCollection
{
#region Implementation (data)
private AppenderCollection m_collection;
#endregion
#region Construction
internal ReadOnlyAppenderCollection(AppenderCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(IAppender[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(IAppender[] array, int start)
{
m_collection.CopyTo(array,start);
}
public override int Count
{
get {return m_collection.Count;}
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override IAppender this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(IAppender x)
{
return m_collection.Contains(x);
}
public override int IndexOf(IAppender x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get {return true;}
}
public override bool IsReadOnly
{
get {return true;}
}
#endregion
#region Type-safe IEnumerable
public override Enumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(AppenderCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(IAppender[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
namespace NQuery.Compilation
{
internal sealed class Compiler
{
private const string PHASE_NORMALIZATION = "Normalization";
private const string PHASE_RESOLUTION = "Resolution";
private const string PHASE_AGGREGATE_BINDING = "AggregateBinding";
private const string PHASE_CONSTANT_FOLDING = "ConstantFolding";
private const string PHASE_VALIDATION = "Validation";
private const string PHASE_ALGEBRAIZATION = "Algebraization";
private const string PHASE_SEMI_JOIN_SIMPLIFICATION = "SemiJoinSimplification";
private const string PHASE_DECORRELATION = "Decorrelation";
private const string PHASE_SELECTION_PUSHING = "SelectionPushing";
private const string PHASE_JOIN_LINEARIZATION = "JoinLinearization";
private const string PHASE_OUTER_JOIN_REORDERING = "OuterJoinReordering";
private const string PHASE_OUTER_REFERENCE_LABELING = "OuterReferenceLabeling";
private const string PHASE_JOIN_ORDER_OPTIMIZATION = "JoinOrderOptimization";
private const string PHASE_AT_MOST_ONE_ROW_REORDERING = "AtMostOneRowReordering";
private const string PHASE_PUSH_COMPUTATIONS = "PushComputations";
private const string PHASE_OUTPUTLIST_GENERATION = "OutputListGeneration";
private const string PHASE_NULL_SCAN_OPTIMIZATION = "NullScanOptimization";
private const string PHASE_OUTPUTLIST_OPTIMIZATION = "OutputListOptimization";
private const string PHASE_ROW_BUFFER_ENTRY_NAMING = "RowBufferEntryNaming";
private const string PHASE_COLUMN_AND_AGGREGATE_EXPRESSION_REPLACEMENT = "ColumnAndAggregateExpressionReplacement";
private const string PHASE_ROW_BUFFER_ENTRY_INLINING = "RowBufferEntryInlining";
private const string PHASE_OUTER_JOIN_REMOVAL = "OuterJoinRemoval";
private const string PHASE_SPOOL_INSERTION = "SpoolInsertion";
private const string PHASE_PHYSICAL_JOIN_OP_CHOOSING = "PhysicalJoinOperationChoosing";
private const string PHASE_FULL_OUTER_JOIN_EXPANSION = "FullOuterJoinExpansion";
private const string PHASE_CONVERSION_TO_TARGET_TYPE = "ConversionToTargetType";
private IErrorReporter _errorReporter;
public Compiler(IErrorReporter errorReporter)
{
_errorReporter = errorReporter;
}
#region Phase Runner
private delegate AstNode PhaseOutputHandler(AstNode input);
private class Phase
{
private string _name;
private PhaseOutputHandler _outputHandler;
private AstNode _result;
private bool _logResult;
public Phase(string name, PhaseOutputHandler outputHandler, bool logResult)
{
_name = name;
_outputHandler = outputHandler;
_logResult = logResult;
}
public string Name
{
get { return _name; }
}
public PhaseOutputHandler OutputHandler
{
get { return _outputHandler; }
}
public AstNode Result
{
get { return _result; }
set { _result = value; }
}
public bool LogResult
{
get { return _logResult; }
}
}
private class PhaseCollection : Collection<Phase>
{
public void Add(string name, PhaseOutputHandler outputHandler)
{
Add(new Phase(name, outputHandler, false));
}
public void Add(string name, StandardVisitor visitor)
{
Add(new Phase(name, delegate(AstNode input)
{
return visitor.Visit(input);
}, false));
}
}
private class PhaseRunner
{
private IErrorReporter _errorReporter;
private AstNode _astNode;
private PhaseCollection _phases = new PhaseCollection();
public PhaseRunner(IErrorReporter errorReporter, AstNode astNode)
{
_errorReporter = errorReporter;
_astNode = astNode;
}
public AstNode Run()
{
AstNode currentNode = _astNode;
int phaseNumber = 1;
foreach (Phase phase in _phases)
{
phase.Result = phase.OutputHandler(currentNode);
if (phase.LogResult)
WriteAstToFile(phase.Result, phase.Name, phaseNumber++);
if (_errorReporter.ErrorsSeen)
return null;
currentNode = phase.Result;
}
return currentNode;
}
private static void WriteAstToFile(AstNode node, string phaseName, int phaseNumber)
{
string numberedPhaseName = String.Format(CultureInfo.InvariantCulture, "{0}-{1}", phaseNumber, phaseName);
string fileName = Path.ChangeExtension(numberedPhaseName, ".xml");
fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
XmlProducer.ProduceFile(fileName, node);
}
public PhaseCollection Phases
{
get { return _phases; }
}
}
#endregion
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public ResultAlgebraNode CompileQuery(string queryText, Scope scope)
{
// Algebraization
Parser parser = new Parser(_errorReporter);
QueryNode parsedQuery = parser.ParseQuery(queryText);
// When the parser detected errors or could not even construct an AST it
// does not make any sense to go ahead.
if (_errorReporter.ErrorsSeen || parsedQuery == null)
return null;
PhaseRunner phaseRunner = new PhaseRunner(_errorReporter, parsedQuery);
phaseRunner.Phases.Add(PHASE_NORMALIZATION, new Normalizer());
phaseRunner.Phases.Add(PHASE_RESOLUTION, new Resolver(_errorReporter, scope));
phaseRunner.Phases.Add(PHASE_AGGREGATE_BINDING, new AggregateBinder(_errorReporter));
phaseRunner.Phases.Add(PHASE_VALIDATION, new Validator(_errorReporter, scope.DataContext.MetadataContext));
phaseRunner.Phases.Add(PHASE_CONSTANT_FOLDING, new ConstantFolder(_errorReporter));
phaseRunner.Phases.Add(PHASE_COLUMN_AND_AGGREGATE_EXPRESSION_REPLACEMENT, new ColumnAndAggregateExpressionReplacer());
phaseRunner.Phases.Add(PHASE_ALGEBRAIZATION, delegate(AstNode input)
{
return Algebrizer.Convert((QueryNode)input);
});
phaseRunner.Phases.Add(PHASE_ROW_BUFFER_ENTRY_INLINING, new RowBufferEntryInliner());
phaseRunner.Phases.Add(PHASE_SEMI_JOIN_SIMPLIFICATION, new SemiJoinSimplifier());
phaseRunner.Phases.Add(PHASE_DECORRELATION, new Decorrelator());
phaseRunner.Phases.Add(PHASE_OUTER_JOIN_REMOVAL, new OuterJoinRemover());
phaseRunner.Phases.Add(PHASE_SELECTION_PUSHING, new SelectionPusher());
phaseRunner.Phases.Add(PHASE_JOIN_LINEARIZATION, new JoinLinearizer());
phaseRunner.Phases.Add(PHASE_OUTER_JOIN_REORDERING, new OuterJoinReorderer());
phaseRunner.Phases.Add(PHASE_JOIN_ORDER_OPTIMIZATION, new JoinOrderOptimizer());
phaseRunner.Phases.Add(PHASE_AT_MOST_ONE_ROW_REORDERING, new AtMostOneRowReorderer());
phaseRunner.Phases.Add(PHASE_OUTER_REFERENCE_LABELING, new OuterReferenceLabeler());
phaseRunner.Phases.Add(PHASE_SPOOL_INSERTION, new SpoolInserter());
phaseRunner.Phases.Add(PHASE_PUSH_COMPUTATIONS, new ComputationPusher());
phaseRunner.Phases.Add(PHASE_PHYSICAL_JOIN_OP_CHOOSING, new PhysicalJoinOperationChooser());
phaseRunner.Phases.Add(PHASE_OUTPUTLIST_GENERATION, new OutputListGenerator());
phaseRunner.Phases.Add(PHASE_NULL_SCAN_OPTIMIZATION, new NullScanOptimizer());
phaseRunner.Phases.Add(PHASE_FULL_OUTER_JOIN_EXPANSION, new FullOuterJoinExpander());
phaseRunner.Phases.Add(PHASE_OUTPUTLIST_OPTIMIZATION, new OutputListOptimizer());
phaseRunner.Phases.Add(PHASE_ROW_BUFFER_ENTRY_NAMING, new RowBufferEntryNamer());
// TODO: Acutally, we should perform "PushComputations" after "NullScanOptimization" since
// we can merge some ComputeScalar nodes there. But currently the "PushComputations"
// visitor does not correctly update the OutputList so later phases will fail.
// TODO: The phases "SpoolInsertion" and "PhysicalJoinOperationChoosing" should be the last
// entries but currently they must precede PHASE_OUTPUTLIST_GENERATION, PHASE_OUTPUTLIST_OPTIMIZATION,
// and PHASE_ROW_BUFFER_ENTRY_NAMING.
return (ResultAlgebraNode)phaseRunner.Run();
}
public ExpressionNode CompileExpression(string expressionText, Type targetType, Scope scope)
{
// Parse the expression.
Parser parser = new Parser(_errorReporter);
ExpressionNode expressionNode = parser.ParseExpression(expressionText);
// When the parser detected errors or could not even construct an AST it
// does not make any sense to go ahead.
if (_errorReporter.ErrorsSeen || expressionNode == null)
return null;
PhaseRunner phaseRunner = new PhaseRunner(_errorReporter, expressionNode);
phaseRunner.Phases.Add(PHASE_NORMALIZATION, new Normalizer());
phaseRunner.Phases.Add(PHASE_RESOLUTION, new Resolver(_errorReporter, scope));
phaseRunner.Phases.Add(PHASE_CONSTANT_FOLDING, new ConstantFolder(_errorReporter));
phaseRunner.Phases.Add(PHASE_VALIDATION, new Validator(_errorReporter, scope.DataContext.MetadataContext));
phaseRunner.Phases.Add(PHASE_CONVERSION_TO_TARGET_TYPE, delegate(AstNode input)
{
if (input == null || _errorReporter.ErrorsSeen)
return null;
ExpressionNode expr = (ExpressionNode)input;
Binder binder = new Binder(_errorReporter);
return binder.ConvertExpressionIfRequired(expr, targetType);
});
return (ExpressionNode)phaseRunner.Run();
}
}
}
| |
// 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.Threading; // For Thread, Mutex
/// <summary>
/// WaitOne()
/// </summary>
///
// Tests that Mutex.WaitOne will block when another
// thread holds the mutex, and then will grab the mutex
// when it is released. Also that appropriate exceptions
// are thrown if the other thread abandons or disposes of
// the mutex
public class MutexWaitOne1
{
#region Private Fields
private const int c_DEFAULT_SLEEP_TIME = 1000; // 1 second
private Mutex m_Mutex = null;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest1: WaitOne returns true when current instance receives a signal");
try
{
do
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(SignalMutex));
thread.Start();
if (m_Mutex.WaitOne() != true)
{
TestLibrary.TestFramework.LogError("001", "WaitOne returns false when current instance receives a signal.");
retVal = false;
break;
}
m_Mutex.ReleaseMutex();
} while (false); // do
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
m_Mutex.Dispose();
}
return retVal;
}
#endregion
#region Negative Test Cases
public bool NegTest1()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("NegTest1: AbandonedMutexException should be thrown if a thread exited without releasing a mutex");
using (m_Mutex = new Mutex(false))
{
try
{
thread = new Thread(new ThreadStart(NeverReleaseMutex));
thread.Start();
thread.Join();
m_Mutex.WaitOne();
TestLibrary.TestFramework.LogError("101", "AbandonedMutexException is not thrown if a thread exited without releasing a mutex");
retVal = false;
}
catch (AbandonedMutexException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("NegTest2: ObjectDisposedException should be thrown if current instance has already been disposed");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(DisposeMutex));
thread.Start();
thread.Join();
m_Mutex.WaitOne();
TestLibrary.TestFramework.LogError("103", "ObjectDisposedException is not thrown if current instance has already been disposed");
retVal = false;
}
catch (ObjectDisposedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != m_Mutex)
{
((IDisposable)m_Mutex).Dispose();
}
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
MutexWaitOne1 test = new MutexWaitOne1();
TestLibrary.TestFramework.BeginTestCase("MutexWaitOne1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private void SignalMutex()
{
m_Mutex.WaitOne();
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
m_Mutex.ReleaseMutex();
}
private void NeverReleaseMutex()
{
m_Mutex.WaitOne();
}
private void DisposeMutex()
{
((IDisposable)m_Mutex).Dispose();
}
#endregion
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.IO;
using Microsoft.Research.DryadLinq;
namespace Microsoft.Research.DryadLinq.Internal
{
internal unsafe struct DataBlockInfo
{
internal byte* DataBlock;
internal Int32 BlockSize;
internal IntPtr ItemHandle;
}
/// <summary>
/// Represents the abstraction of a native stream. This NativeBlockStream class is public
/// because auto-generated vertex code needs to pass around references to it.
/// </summary>
public abstract class NativeBlockStream
{
internal abstract Int64 GetTotalLength();
internal abstract unsafe DataBlockInfo ReadDataBlock();
internal abstract unsafe bool WriteDataBlock(IntPtr itemHandle, Int32 numBytesToWrite);
internal abstract unsafe DataBlockInfo AllocateDataBlock(Int32 size);
internal abstract unsafe void ReleaseDataBlock(IntPtr itemHandle);
internal abstract void Flush();
internal abstract void Close();
internal virtual string GetURI()
{
throw new DryadLinqException(DryadLinqErrorCode.GetURINotSupported,
SR.GetURINotSupported);
}
internal virtual void SetCalcFP()
{
throw new DryadLinqException(DryadLinqErrorCode.SetCalcFPNotSupported,
SR.SetCalcFPNotSupported);
}
internal virtual UInt64 GetFingerPrint()
{
throw new DryadLinqException(DryadLinqErrorCode.GetFPNotSupported,
SR.GetFPNotSupported);
}
}
internal sealed class DryadLinqChannel : NativeBlockStream
{
private IntPtr m_vertexInfo;
private UInt32 m_portNum;
private bool m_isInput;
private bool m_isClosed;
internal DryadLinqChannel(IntPtr vertexInfo, UInt32 portNum, bool isInput)
{
this.m_vertexInfo = vertexInfo;
this.m_portNum = portNum;
this.m_isInput = isInput;
this.m_isClosed = false;
}
~DryadLinqChannel()
{
this.Close();
}
internal IntPtr NativeHandle
{
get { return this.m_vertexInfo; }
}
internal UInt32 PortNumber
{
get { return this.m_portNum; }
}
internal override unsafe Int64 GetTotalLength()
{
if (this.m_isInput)
{
return DryadLinqNative.GetExpectedLength(this.m_vertexInfo, this.m_portNum);
}
else
{
throw new NotImplementedException();
}
}
internal override unsafe DataBlockInfo AllocateDataBlock(Int32 size)
{
DataBlockInfo blockInfo;
blockInfo.ItemHandle =
DryadLinqNative.AllocateDataBlock(this.m_vertexInfo, size, &blockInfo.DataBlock);
blockInfo.BlockSize = size;
if (blockInfo.ItemHandle == IntPtr.Zero)
{
throw new DryadLinqException(DryadLinqErrorCode.FailedToAllocateNewNativeBuffer,
String.Format(SR.FailedToAllocateNewNativeBuffer, size));
}
// DryadLinqLog.AddInfo("Allocated data block {0} of {1} bytes.", blockInfo.itemHandle, size);
return blockInfo;
}
internal override unsafe void ReleaseDataBlock(IntPtr itemHandle)
{
if (itemHandle != IntPtr.Zero)
{
DryadLinqNative.ReleaseDataBlock(this.m_vertexInfo, itemHandle);
}
// DryadLinqLog.AddInfo("Released data block {0}.", itemHandle);
}
internal override unsafe DataBlockInfo ReadDataBlock()
{
DataBlockInfo blockInfo;
Int32 errorCode = 0;
blockInfo.ItemHandle = DryadLinqNative.ReadDataBlock(this.m_vertexInfo,
this.m_portNum,
&blockInfo.DataBlock,
&blockInfo.BlockSize,
&errorCode);
if (errorCode != 0)
{
VertexEnv.ErrorCode = errorCode;
throw new DryadLinqException(DryadLinqErrorCode.FailedToReadFromInputChannel,
String.Format(SR.FailedToReadFromInputChannel,
this.m_portNum, errorCode));
}
return blockInfo;
}
internal override unsafe bool WriteDataBlock(IntPtr itemHandle, Int32 numBytesToWrite)
{
bool success = true;
if (numBytesToWrite > 0)
{
success = DryadLinqNative.WriteDataBlock(this.m_vertexInfo,
this.m_portNum,
itemHandle,
numBytesToWrite);
if (!success)
{
throw new DryadLinqException(DryadLinqErrorCode.FailedToWriteToOutputChannel,
String.Format(SR.FailedToWriteToOutputChannel,
this.m_portNum));
}
}
return success;
}
internal override void SetCalcFP()
{
throw new DryadLinqException(DryadLinqErrorCode.SetCalcFPNotSupported,
SR.SetCalcFPNotSupported);
}
internal override UInt64 GetFingerPrint()
{
throw new DryadLinqException(DryadLinqErrorCode.GetFPNotSupported,
SR.GetFPNotSupported);
}
internal override unsafe string GetURI()
{
IntPtr uriPtr;
if (this.m_isInput)
{
uriPtr = DryadLinqNative.GetInputChannelURI(this.m_vertexInfo, this.m_portNum);
}
else
{
uriPtr = DryadLinqNative.GetOutputChannelURI(this.m_vertexInfo, this.m_portNum);
}
return Marshal.PtrToStringAnsi(uriPtr);
}
internal override void Flush()
{
DryadLinqNative.Flush(this.m_vertexInfo, this.m_portNum);
}
internal override void Close()
{
if (!this.m_isClosed)
{
this.m_isClosed = true;
this.Flush();
DryadLinqNative.Close(this.m_vertexInfo, this.m_portNum);
string ctype = (this.m_isInput) ? "Input" : "Output";
DryadLinqLog.AddInfo(ctype + " channel {0} was closed.", this.m_portNum);
}
GC.SuppressFinalize(this);
}
public override string ToString()
{
return "DryadChannel[" + PortNumber + "]";
}
}
}
| |
// 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 Internal.Runtime.CompilerServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace System.Runtime.InteropServices
{
[Flags]
public enum McgInterfaceFlags : byte
{
None = 0x00,
isIInspectable = 0x01, // this interface derives from IInspectable
isDelegate = 0x02, // this entry is for a WinRT delegate type, ItfType is the type of a managed delegate type
isInternal = 0x04,
useSharedCCW = 0x08, // this entry uses shared ccwVTable + thunk function
SharedCCWMask = 0xF8,
useSharedCCW_IVector = 0x08, // 4-bit shared ccw index: 16 max, 8 used
useSharedCCW_IVectorView = 0x18,
useSharedCCW_IIterable = 0x28,
useSharedCCW_IIterator = 0x38,
useSharedCCW_AsyncOperationCompletedHandler = 0x48,
useSharedCCW_IVectorBlittable = 0x58,
useSharedCCW_IVectorViewBlittable = 0x68,
useSharedCCW_IIteratorBlittable = 0x78,
}
[Flags]
public enum McgClassFlags : int
{
None = 0,
/// <summary>
/// This represents the types MarshalingBehavior.
/// </summary>
MarshalingBehavior_Inhibit = 1,
MarshalingBehavior_Free = 2,
MarshalingBehavior_Standard = 3,
MarshalingBehavior_Mask = 3,
/// <summary>
/// GCPressureRange
/// </summary>
GCPressureRange_WinRT_Default = 1 << 2,
GCPressureRange_WinRT_Low = 2 << 2,
GCPressureRange_WinRT_Medium = 3 << 2,
GCPressureRange_WinRT_High = 4 << 2,
GCPressureRange_Mask = 7 << 2,
/// <summary>
/// Either a WinRT value type, or a projected class type
/// In either case, it is not a __ComObject and we can't create it using CreateComObject
/// </summary>
NotComObject = 32,
/// <summary>
/// This type is sealed
/// </summary>
IsSealed = 64,
/// <summary>
/// This type is a WinRT type and we'll return Kind=Metadata in type name marshalling
/// </summary>
IsWinRT = 128
}
/// <summary>
/// Per-native-interface information generated by MCG
/// </summary>
[CLSCompliant(false)]
public struct McgInterfaceData // 36 bytes on 32-bit platforms
{
/// <summary>
/// NOTE: Managed debugger depends on field name: "FixupItfType" and field type must be FixupRuntimeTypeHandle
/// Update managed debugger whenever field name/field type is changed.
/// See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp
/// </summary>
public FixupRuntimeTypeHandle FixupItfType; // 1 pointer
// Optional fields(FixupDispatchClassType and FixupDynamicAdapterClassType)
public FixupRuntimeTypeHandle FixupDispatchClassType; // 1 pointer, around 80% usage
public FixupRuntimeTypeHandle FixupDynamicAdapterClassType; // 1 pointer, around 20% usage
public RuntimeTypeHandle ItfType
{
get
{
return FixupItfType.RuntimeTypeHandle;
}
set
{
FixupItfType = new FixupRuntimeTypeHandle(value);
}
}
public RuntimeTypeHandle DispatchClassType
{
get
{
return FixupDispatchClassType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle DynamicAdapterClassType
{
get
{
return FixupDynamicAdapterClassType.RuntimeTypeHandle;
}
}
// Fixed fields
public Guid ItfGuid; // 16 bytes
/// <summary>
/// NOTE: Managed debugger depends on field name: "Flags" and field type must be an enum type
/// Update managed debugger whenever field name/field type is changed.
/// See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp
/// </summary>
public McgInterfaceFlags Flags; // 1 byte
/// <summary>
/// Whether this type is a IInspectable type
/// </summary>
internal bool IsIInspectable
{
get
{
return (Flags & McgInterfaceFlags.isIInspectable) != McgInterfaceFlags.None;
}
}
internal bool IsIInspectableOrDelegate
{
get
{
return (Flags & (McgInterfaceFlags.isIInspectable | McgInterfaceFlags.isDelegate)) != McgInterfaceFlags.None;
}
}
public short MarshalIndex; // 2 bytes: Index into InterfaceMarshalData array for shared CCW, also used for internal module sequential type index
// Optional fields(CcwVtable)
// TODO fyuan define larger McgInterfaceData for merging interop code (shared CCW, default eventhandler)
public IntPtr CcwVtable; // 1 pointer, around 20-40% usage
public IntPtr DelegateInvokeStub; // only used for RCW delegate
}
[CLSCompliant(false)]
public struct McgGenericArgumentMarshalInfo // Marshal information for generic argument T
{
// sizeOf(T)
public uint ElementSize;
// Class Type Handle for sealed T winrt class
public FixupRuntimeTypeHandle FixupElementClassType;
// Interface Type Handle for T interface type
public FixupRuntimeTypeHandle FixupElementInterfaceType;
// Type Handle for IAsyncOperation<T>
public FixupRuntimeTypeHandle FixupAsyncOperationType;
// Type Handle for Iterator<T>
public FixupRuntimeTypeHandle FixupIteratorType;
// Type Handle for VectorView<T>
public FixupRuntimeTypeHandle FixupVectorViewType;
public RuntimeTypeHandle AsyncOperationType
{
get
{
return FixupAsyncOperationType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle ElementClassType
{
get
{
return FixupElementClassType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle ElementInterfaceType
{
get
{
return FixupElementInterfaceType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle IteratorType
{
get
{
return FixupIteratorType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle VectorViewType
{
get
{
return FixupVectorViewType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Per-WinRT-class information generated by MCG. This is used for TypeName marshalling and for
/// CreateComObject. For the TypeName marshalling case, we have Nullable<T> / KeyValuePair<K,V> value
/// classes as the ClassType field and WinRT names like Windows.Foundation.IReference`1<blah> in the name
/// field. These entries are filtered out by CreateComObject using the Flags field.
/// </summary>
[CLSCompliant(false)]
public struct McgClassData
{
public FixupRuntimeTypeHandle FixupClassType; // FixupRuntimeTypeHandle for type in CLR (projected) view
public RuntimeTypeHandle ClassType // RuntimeTypeHandle of FixupRuntimeTypeHandle
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
public McgClassFlags Flags; // Flags (whether it is a ComObject, whether it can be boxed, etc)
internal GCPressureRange GCPressureRange
{
get
{
switch (Flags & McgClassFlags.GCPressureRange_Mask)
{
case McgClassFlags.GCPressureRange_WinRT_Default:
return GCPressureRange.WinRT_Default;
case McgClassFlags.GCPressureRange_WinRT_Low:
return GCPressureRange.WinRT_Low;
case McgClassFlags.GCPressureRange_WinRT_Medium:
return GCPressureRange.WinRT_Medium;
case McgClassFlags.GCPressureRange_WinRT_High:
return GCPressureRange.WinRT_High;
default:
return GCPressureRange.None;
}
}
}
internal ComMarshalingType MarshalingType
{
get
{
switch (Flags & McgClassFlags.MarshalingBehavior_Mask)
{
case McgClassFlags.MarshalingBehavior_Inhibit:
return ComMarshalingType.Inhibit;
case McgClassFlags.MarshalingBehavior_Free:
return ComMarshalingType.Free;
case McgClassFlags.MarshalingBehavior_Standard:
return ComMarshalingType.Standard;
default:
return ComMarshalingType.Unknown;
}
}
}
/// <summary>
/// The type handle for its base class
///
/// There are two ways to access base class: RuntimeTypeHandle or Index
/// Ideally we want to use typehandle for everything - but DR throws it away and breaks the inheritance chain
/// - therefore we would only use index for "same module" and type handle for "cross module"
///
/// Code Pattern:
/// if (BaseClassIndex >=0) { // same module }
/// else if(!BaseClassType.Equals(default(RuntimeTypeHandle)) { // cross module}
/// else { // it doesn't have base}
/// </summary>
public FixupRuntimeTypeHandle FixupBaseClassType; // FixupRuntimeTypeHandle for Base class type in CLR (projected) view
public RuntimeTypeHandle BaseClassType // RuntimeTypeHandle of BaseClass
{
get
{
return FixupBaseClassType.RuntimeTypeHandle;
}
}
public short BaseClassIndex; // Index to the base class;
/// <summary>
/// The type handle for its default Interface
/// The comment above for BaseClassType applies for DefaultInterface as well
/// </summary>
public FixupRuntimeTypeHandle FixupDefaultInterfaceType; // FixupRuntimeTypeHandle for DefaultInterface type in CLR (projected) view
public RuntimeTypeHandle DefaultInterfaceType // RuntimeTypeHandle of DefaultInterface
{
get
{
return FixupDefaultInterfaceType.RuntimeTypeHandle;
}
}
public short DefaultInterfaceIndex; // Index to the default interface
}
[CLSCompliant(false)]
public struct McgHashcodeVerifyEntry
{
public FixupRuntimeTypeHandle FixupTypeHandle;
public RuntimeTypeHandle TypeHandle
{
get
{
return FixupTypeHandle.RuntimeTypeHandle;
}
}
public uint HashCode;
}
/// <summary>
/// Mcg data used for boxing
/// Boxing refers to IReference/IReferenceArray boxing, as well as projection support when marshalling
/// IInspectable, such as IKeyValuePair, System.Uri, etc.
/// So this supports boxing in a broader sense that it supports WinRT type <-> native type projection
/// There are 3 cases:
/// 1. IReference<T> / IReferenceArray<T>. It is boxed to a managed wrapper and unboxed either from the wrapper or from native IReference/IReferenceArray RCW (through unboxing stub)
/// 2. IKeyValuePair<K, V>. Very similiar to #1 except that it does not have propertyType
/// 3. All other cases, including System.Uri, NotifyCollectionChangedEventArgs, etc. They go through boxing stub and unboxing stub.
///
/// NOTE: Even though this struct doesn't have a name in itself, there is a parallel array
/// m_boxingDataNameMap that holds the corresponding class names for each boxing data
/// </summary>
[CLSCompliant(false)]
public struct McgBoxingData
{
/// <summary>
/// The target type that triggers the boxing. Used in search
/// </summary>
public FixupRuntimeTypeHandle FixupManagedClassType;
/// <summary>
/// HIDDEN
/// This is actually saved in m_boxingDataNameMap
/// The runtime class name that triggers the unboxing. Used in search.
/// </summary>
/// public string Name;
/// <summary>
/// A managed wrapper for IReference/IReferenceArray/IKeyValuePair boxing
/// We create the wrapper directly instead of going through a boxing stub. This saves us some
/// disk space (300+ boxing stub in a typical app), but we need to see whether this trade off
/// makes sense long term.
/// </summary>
public FixupRuntimeTypeHandle FixupCLRBoxingWrapperType;
public RuntimeTypeHandle ManagedClassType
{
get
{
return FixupManagedClassType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle CLRBoxingWrapperType
{
get
{
return FixupCLRBoxingWrapperType.RuntimeTypeHandle;
}
}
/// <summary>
/// General boxing stub - boxing an managed object instance into a native object instance (RCW)
/// This is used for special cases where managed wrappers aren't suitable, mainly for projected types
/// such as System.Uri.
///
/// Prototype:
/// object Boxing_Stub(object target)
/// </summary>
public IntPtr BoxingStub;
/// <summary>
/// General unboxing stub - unbox a native object instance (RCW) into a managed object (interestingly,
/// can be boxed in the managed sense)
///
/// object UnboxingStub(object target)
/// </summary>
public IntPtr UnboxingStub;
/// <summary>
/// Corresponding PropertyType
/// Only used when boxing into a managed wrapper - because it is only meaningful in IReference
/// & IReferenceArray
/// </summary>
public short PropertyType;
}
/// <summary>
/// This information is separate from the McgClassData[]
/// as its captures the types which are not imported by the MCG.
/// </summary>
[CLSCompliant(false)]
public struct McgTypeNameMarshalingData
{
public FixupRuntimeTypeHandle FixupClassType;
public RuntimeTypeHandle ClassType
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
}
public enum McgStructMarshalFlags
{
None,
/// <summary>
/// This struct has invalid layout information, most likely because it is marked LayoutKind.Auto
/// </summary>
HasInvalidLayout
}
[CLSCompliant(false)]
public struct McgStructMarshalData
{
public FixupRuntimeTypeHandle FixupSafeStructType;
public FixupRuntimeTypeHandle FixupUnsafeStructType;
public RuntimeTypeHandle SafeStructType
{
get
{
return FixupSafeStructType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle UnsafeStructType
{
get
{
return FixupUnsafeStructType.RuntimeTypeHandle;
}
}
public IntPtr MarshalStub;
public IntPtr UnmarshalStub;
public IntPtr DestroyStructureStub;
public McgStructMarshalFlags Flags;
/// <summary>
/// This struct has invalid layout information, most likely because it is marked LayoutKind.Auto
/// We'll throw exception when this struct is getting marshalled
/// </summary>
internal bool HasInvalidLayout
{
get
{
return (Flags & McgStructMarshalFlags.HasInvalidLayout) != 0;
}
}
public int FieldOffsetStartIndex; // start index to its field offset data
public int NumOfFields; // number of fields
}
[CLSCompliant(false)]
public struct McgUnsafeStructFieldOffsetData
{
public uint Offset; // offset value in bytes
}
/// <summary>
/// Base class for KeyValuePairImpl<T>
/// </summary>
public abstract class BoxedKeyValuePair : IManagedWrapper
{
// Called by public object McgModule.Box(object obj, int boxingIndex) after allocating instance
public abstract object Initialize(object val);
public abstract object GetTarget();
}
/// <summary>
/// Supports unboxing managed wrappers such as ReferenceImpl / KeyValuePair
/// </summary>
public interface IManagedWrapper
{
object GetTarget();
}
/// <summary>
/// Base class for ReferenceImpl<T>/ReferenceArrayImpl<T>
/// </summary>
public class BoxedValue : IManagedWrapper
{
protected object m_data; // boxed value
protected short m_type; // Windows.Foundation.PropertyType
protected bool m_unboxed; // false if T ReferenceImpl<T>.m_value needs to be unboxed from m_data when needed
public BoxedValue(object val, int type)
{
m_data = val;
m_type = (short)type;
}
// Called by public object Box(object obj, int boxingIndex) after allocating instance
// T ReferenceImpl<T>.m_value needs to be unboxed from m_data when needed
virtual public void Initialize(object val, int type)
{
m_data = val;
m_type = (short)type;
}
public object GetTarget()
{
return m_data;
}
public override string ToString()
{
if (m_data != null)
{
return m_data.ToString();
}
else
{
return "null";
}
}
}
/// <summary>
/// Entries for WinRT classes that MCG didn't see in user code
/// We need to make sure when we are marshalling these types, we need to hand out the closest match
/// For example, if MCG only sees DependencyObject but native is passing MatrixTransform, we need
/// to give user the next best thing - dependencyObject, so that user can cast it to DependencyObject
///
/// MatrixTransform -> DependencyObject
/// </summary>
[CLSCompliant(false)]
public struct McgAdditionalClassData
{
public int ClassDataIndex; // Pointing to the "next best" class (DependencyObject, for example)
public FixupRuntimeTypeHandle FixupClassType; // Pointing to the "next best" class (DependencyObject, for example)
public RuntimeTypeHandle ClassType
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Maps from an ICollection or IReadOnlyCollection type to the corresponding entries in m_interfaceTypeInfo
/// for IList, IDictionary, IReadOnlyList, IReadOnlyDictionary
/// </summary>
[CLSCompliant(false)]
public struct McgCollectionData
{
public FixupRuntimeTypeHandle FixupCollectionType;
public RuntimeTypeHandle CollectionType
{
get
{
return FixupCollectionType.RuntimeTypeHandle;
}
}
public FixupRuntimeTypeHandle FixupFirstType;
public RuntimeTypeHandle FirstType
{
get
{
return FixupFirstType.RuntimeTypeHandle;
}
}
public FixupRuntimeTypeHandle FixupSecondType;
public RuntimeTypeHandle SecondType
{
get
{
return FixupSecondType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Captures data for each P/invoke delegate type we decide to import
/// </summary>
[CLSCompliant(false)]
public struct McgPInvokeDelegateData
{
/// <summary>
/// Type of the delegate
/// </summary>
public FixupRuntimeTypeHandle FixupDelegate;
public RuntimeTypeHandle Delegate
{
get
{
return FixupDelegate.RuntimeTypeHandle;
}
}
/// <summary>
/// The stub called from thunk that does the marshalling when calling managed delegate (as a function
/// pointer) from native code
/// </summary>
public IntPtr ReverseStub;
/// <summary>
/// The stub called from thunk that does the marshalling when calling managed open static delegate (as a function
/// pointer) from native code
/// </summary>
public IntPtr ReverseOpenStaticDelegateStub;
/// <summary>
/// This creates a delegate wrapper class that wraps the native function pointer and allows managed
/// code to call it
/// </summary>
public IntPtr ForwardDelegateCreationStub;
}
/// <summary>
/// Base class for all 'wrapper' classes that wraps a native function pointer
/// The forward delegates (that wraps native function pointers) points to derived Invoke method of this
/// class, and the Invoke method would implement the marshalling and making the call
/// </summary>
public abstract class NativeFunctionPointerWrapper
{
public NativeFunctionPointerWrapper(IntPtr nativeFunctionPointer)
{
m_nativeFunctionPointer = nativeFunctionPointer;
}
IntPtr m_nativeFunctionPointer;
public IntPtr NativeFunctionPointer
{
get { return m_nativeFunctionPointer; }
}
}
[CLSCompliant(false)]
public struct McgCCWFactoryInfoEntry
{
public FixupRuntimeTypeHandle FixupFactoryType;
public RuntimeTypeHandle FactoryType
{
get
{
return FixupFactoryType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Static per-type CCW information
/// </summary>
[CLSCompliant(false)]
public struct CCWTemplateData
{
/// <summary>
/// RuntimeTypeHandle of the class that this CCWTemplateData is for
/// </summary>
public FixupRuntimeTypeHandle FixupClassType;
public RuntimeTypeHandle ClassType
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
/// <summary>
/// The type handle for its base class (that is also a managed type)
///
/// There are two ways to access base class: RuntimeTypeHandle or Index
/// Ideally we want to use typehandle for everything - but DR throws it away and breaks the inheritance chain
/// - therefore we would only use index for "same module" and type handle for "cross module"
///
/// Code Pattern:
/// if (ParentCCWTemplateIndex >=0) { // same module }
/// else if(!BaseClassType.Equals(default(RuntimeTypeHandle)) { // cross module}
/// else { // it doesn't have base}
/// </summary>
public FixupRuntimeTypeHandle FixupBaseType;
public RuntimeTypeHandle BaseType
{
get
{
return FixupBaseType.RuntimeTypeHandle;
}
}
/// <summary>
/// The index of the CCWTemplateData for its base class (that is also a managed type)
/// < 0 if does not exist or there are multiple module involved(use its BaseType property instead)
/// </summary>
public int ParentCCWTemplateIndex;
/// <summary>
/// The beginning index of list of supported interface
/// NOTE: The list for this specific type only, excluding base classes
/// </summary>
public int SupportedInterfaceListBeginIndex;
/// <summary>
/// The total number of supported interface
/// NOTE: The list for this specific type only, excluding base classes
/// </summary>
public int NumberOfSupportedInterface;
/// <summary>
/// Whether this CCWTemplateData belongs to a WinRT type
/// Typically this only happens when we import a managed class that implements a WinRT type and
/// we'll import the base WinRT type as CCW template too, as a way to capture interfaces in the class
/// hierarchy and also know which are the ones implemented by managed class
/// </summary>
public bool IsWinRTType;
}
/// <summary>
/// Extra type/marshalling information for a given type used in MCG. You can think this as a more
/// complete version of System.Type.
/// </summary>
internal unsafe class McgInterfaceInfo
{
int m_TypeIndex;
int m_ModuleIndex;
internal McgInterfaceData InterfaceData
{
get
{
return McgModuleManager.GetInterfaceDataByIndex(m_ModuleIndex, m_TypeIndex);
}
}
/// <summary>
/// Constructor
/// </summary>
public McgInterfaceInfo(int moduleIndex, int typeIndex)
{
m_TypeIndex = typeIndex;
m_ModuleIndex = moduleIndex;
}
/// <summary>
/// The guid of this type
/// </summary>
public Guid ItfGuid
{
get
{
return InterfaceData.ItfGuid;
}
}
public RuntimeTypeHandle ItfType
{
get
{
return InterfaceData.ItfType;
}
}
public McgInterfaceFlags Flags
{
get
{
return InterfaceData.Flags;
}
}
public short MarshalIndex
{
get
{
return InterfaceData.MarshalIndex;
}
}
static IntPtr[] SharedCCWList = new IntPtr[] {
#if ENABLE_WINRT
SharedCcw_IVector.GetVtable(),
SharedCcw_IVectorView.GetVtable(),
SharedCcw_IIterable.GetVtable(),
SharedCcw_IIterator.GetVtable(),
#if RHTESTCL || CORECLR
default(IntPtr),
#else
SharedCcw_AsyncOperationCompletedHandler.GetVtable(),
#endif
SharedCcw_IVector_Blittable.GetVtable(),
SharedCcw_IVectorView_Blittable.GetVtable(),
#if RHTESTCL || CORECLR
default(IntPtr)
#else
SharedCcw_IIterator_Blittable.GetVtable()
#endif
#endif //ENABLE_WINRT
};
internal unsafe IntPtr CcwVtable
{
get
{
McgInterfaceFlags flag = InterfaceData.Flags & McgInterfaceFlags.SharedCCWMask;
if (flag != 0)
{
return SharedCCWList[(int)flag >> 4];
}
if (InterfaceData.CcwVtable == IntPtr.Zero)
return IntPtr.Zero;
return CalliIntrinsics.Call__GetCcwVtable(InterfaceData.CcwVtable);
}
}
/// <summary>
/// Returns the corresponding interface type for this type
/// </summary>
internal RuntimeTypeHandle InterfaceType
{
get
{
return InterfaceData.ItfType;
}
}
/// <summary>
/// Returns the corresponding dispatch class type for this type
/// </summary>
internal RuntimeTypeHandle DispatchClassType
{
get
{
return InterfaceData.DispatchClassType;
}
}
internal RuntimeTypeHandle DynamicAdapterClassType
{
get
{
return InterfaceData.DynamicAdapterClassType;
}
}
internal bool HasDynamicAdapterClass
{
get { return !DynamicAdapterClassType.IsNull(); }
}
internal IntPtr DelegateInvokeStub
{
get { return InterfaceData.DelegateInvokeStub; }
}
}
/// <summary>
/// Extra information for all the class types encoded by MCG
/// </summary>
internal unsafe class McgClassInfo
{
int m_ClassDataIndex;
int m_ModuleIndex;
public McgClassInfo(int moduleIndex, int classDataIndex)
{
m_ClassDataIndex = classDataIndex;
m_ModuleIndex = moduleIndex;
}
private McgClassData ClassData
{
get
{
return McgModuleManager.GetClassDataByIndex(m_ModuleIndex, m_ClassDataIndex);
}
}
internal RuntimeTypeHandle ClassType
{
get
{
return ClassData.ClassType;
}
}
internal RuntimeTypeHandle BaseClassType
{
get
{
int baseClassIndex = ClassData.BaseClassIndex;
if (baseClassIndex >= 0)
{
return McgModuleManager.GetClassDataByIndex(m_ModuleIndex, baseClassIndex).ClassType;
}
else if (!ClassData.BaseClassType.Equals(default(RuntimeTypeHandle)))
{
return ClassData.BaseClassType;
}
// doesn't have base class
return default(RuntimeTypeHandle);
}
}
internal RuntimeTypeHandle DefaultInterface
{
get
{
int defaultInterfaceIndex = ClassData.DefaultInterfaceIndex;
if (defaultInterfaceIndex >= 0)
{
return McgModuleManager.GetInterfaceDataByIndex(m_ModuleIndex, defaultInterfaceIndex).ItfType;
}
else
{
return ClassData.DefaultInterfaceType;
}
}
}
internal bool Equals(McgClassInfo classInfo)
{
if (classInfo == null)
return false;
return m_ClassDataIndex == classInfo.m_ClassDataIndex && m_ModuleIndex == classInfo.m_ModuleIndex;
}
internal bool IsSealed
{
get
{
return ((ClassData.Flags & McgClassFlags.IsSealed) != 0);
}
}
internal bool IsWinRT
{
get
{
return ((ClassData.Flags & McgClassFlags.IsWinRT) != 0);
}
}
internal ComMarshalingType MarshalingType
{
get
{
return ClassData.MarshalingType;
}
}
internal GCPressureRange GCPressureRange
{
get
{
return ClassData.GCPressureRange;
}
}
}
internal unsafe class CCWTemplateInfo
{
int m_TypeIndex;
int m_ModuleIndex;
/// <summary>
/// Constructor
/// </summary>
public CCWTemplateInfo(int moduleIndex, int typeIndex)
{
m_ModuleIndex = moduleIndex;
m_TypeIndex = typeIndex;
}
private CCWTemplateData CCWTemplate
{
get
{
return McgModuleManager.GetCCWTemplateDataByIndex(m_ModuleIndex, m_TypeIndex);
}
}
public bool IsWinRTType
{
get
{
return CCWTemplate.IsWinRTType;
}
}
public IEnumerable<RuntimeTypeHandle> ImplementedInterfaces
{
get
{
return McgModuleManager.GetImplementedInterfacesByIndex(m_ModuleIndex, m_TypeIndex);
}
}
public RuntimeTypeHandle BaseClass
{
get
{
int parentCCWTemplateIndex = CCWTemplate.ParentCCWTemplateIndex;
if (parentCCWTemplateIndex >= 0)
{
return McgModuleManager.GetCCWTemplateDataByIndex(m_ModuleIndex, parentCCWTemplateIndex).ClassType;
}
else if (!CCWTemplate.BaseType.Equals(default(RuntimeTypeHandle)))
{
return CCWTemplate.BaseType;
}
// doesn't have base class
return default(RuntimeTypeHandle);
}
}
}
}
| |
// 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.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Json.Tests
{
public static partial class JsonEncodedTextTests
{
[Fact]
public static void LatinCharsSameAsDefaultEncoder()
{
for (int i = 0; i <= 127; i++)
{
JsonEncodedText textBuiltin = JsonEncodedText.Encode(((char)i).ToString());
JsonEncodedText textEncoder = JsonEncodedText.Encode(((char)i).ToString(), JavaScriptEncoder.Default);
Assert.Equal(textEncoder, textBuiltin);
}
}
[Fact]
public static void Default()
{
JsonEncodedText text = default;
Assert.True(text.EncodedUtf8Bytes.IsEmpty);
Assert.Equal(0, text.GetHashCode());
Assert.Equal("", text.ToString());
Assert.True(text.Equals(default));
Assert.True(text.Equals(text));
Assert.False(text.Equals(null));
JsonEncodedText defaultText = default;
object obj = defaultText;
Assert.True(text.Equals(obj));
Assert.True(text.Equals(defaultText));
Assert.True(defaultText.Equals(text));
JsonEncodedText textByteEmpty = JsonEncodedText.Encode(Array.Empty<byte>());
Assert.True(textByteEmpty.EncodedUtf8Bytes.IsEmpty);
Assert.Equal("", textByteEmpty.ToString());
JsonEncodedText textCharEmpty = JsonEncodedText.Encode(Array.Empty<char>());
Assert.True(textCharEmpty.EncodedUtf8Bytes.IsEmpty);
Assert.Equal("", textCharEmpty.ToString());
Assert.True(textCharEmpty.Equals(textByteEmpty));
Assert.Equal(textByteEmpty.GetHashCode(), textCharEmpty.GetHashCode());
}
[Theory]
[MemberData(nameof(JsonEncodedTextStrings))]
public static void NullEncoder(string message, string expectedMessage)
{
JsonEncodedText text = JsonEncodedText.Encode(message, null);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan(), null);
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message), null);
Assert.Equal(expectedMessage, text.ToString());
Assert.Equal(expectedMessage, textSpan.ToString());
Assert.Equal(expectedMessage, textUtf8Span.ToString());
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
[Theory]
[MemberData(nameof(JsonEncodedTextStringsCustom))]
public static void CustomEncoder(string message, string expectedMessage)
{
// Latin-1 Supplement block starts from U+0080 and ends at U+00FF
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRange.Create((char)0x0080, (char)0x00FF));
JsonEncodedText text = JsonEncodedText.Encode(message, encoder);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan(), encoder);
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message), encoder);
Assert.Equal(expectedMessage, text.ToString());
Assert.Equal(expectedMessage, textSpan.ToString());
Assert.Equal(expectedMessage, textUtf8Span.ToString());
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
[Theory]
[MemberData(nameof(JsonEncodedTextStrings))]
public static void CustomEncoderCantOverrideHtml(string message, string expectedMessage)
{
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRange.Create(' ', '}'));
JsonEncodedText text = JsonEncodedText.Encode(message, encoder);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan(), encoder);
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message), encoder);
Assert.Equal(expectedMessage, text.ToString());
Assert.Equal(expectedMessage, textSpan.ToString());
Assert.Equal(expectedMessage, textUtf8Span.ToString());
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
[Fact]
public static void Equals()
{
string message = "message";
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textCopy = text;
JsonEncodedText textDuplicate = JsonEncodedText.Encode(message);
JsonEncodedText textDuplicateDiffStringRef = JsonEncodedText.Encode(string.Concat("mess", "age"));
JsonEncodedText differentText = JsonEncodedText.Encode("message1");
Assert.True(text.Equals(text));
Assert.True(text.Equals(textCopy));
Assert.True(textCopy.Equals(text));
Assert.True(text.Equals(textDuplicate));
Assert.True(textDuplicate.Equals(text));
Assert.True(text.Equals(textDuplicateDiffStringRef));
Assert.True(textDuplicateDiffStringRef.Equals(text));
Assert.False(text.Equals(differentText));
Assert.False(differentText.Equals(text));
}
[Fact]
public static void EqualsObject()
{
string message = "message";
JsonEncodedText text = JsonEncodedText.Encode(message);
object textCopy = text;
object textDuplicate = JsonEncodedText.Encode(message);
object textDuplicateDiffStringRef = JsonEncodedText.Encode(string.Concat("mess", "age"));
object differentText = JsonEncodedText.Encode("message1");
Assert.True(text.Equals(text));
Assert.True(text.Equals(textCopy));
Assert.True(textCopy.Equals(text));
Assert.True(text.Equals(textDuplicate));
Assert.True(textDuplicate.Equals(text));
Assert.True(text.Equals(textDuplicateDiffStringRef));
Assert.True(textDuplicateDiffStringRef.Equals(text));
Assert.False(text.Equals(differentText));
Assert.False(differentText.Equals(text));
Assert.False(text.Equals(null));
}
[Fact]
public static void GetHashCodeTest()
{
string message = "message";
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textCopy = text;
JsonEncodedText textDuplicate = JsonEncodedText.Encode(message);
JsonEncodedText textDuplicateDiffStringRef = JsonEncodedText.Encode(string.Concat("mess", "age"));
JsonEncodedText differentText = JsonEncodedText.Encode("message1");
int expectedHashCode = text.GetHashCode();
Assert.NotEqual(0, expectedHashCode);
Assert.Equal(expectedHashCode, textCopy.GetHashCode());
Assert.Equal(expectedHashCode, textDuplicate.GetHashCode());
Assert.Equal(expectedHashCode, textDuplicateDiffStringRef.GetHashCode());
Assert.NotEqual(expectedHashCode, differentText.GetHashCode());
}
[Theory]
[MemberData(nameof(JsonEncodedTextStrings))]
public static void ToStringTest(string message, string expectedMessage)
{
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan());
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message));
Assert.Equal(expectedMessage, text.ToString());
Assert.Equal(expectedMessage, textSpan.ToString());
Assert.Equal(expectedMessage, textUtf8Span.ToString());
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
[Theory]
[InlineData(100)]
[InlineData(1_000)]
[InlineData(10_000)]
public static void ToStringLargeTest(int stringLength)
{
{
var message = new string('a', stringLength);
var expectedMessage = new string('a', stringLength);
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan());
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message));
Assert.Equal(expectedMessage, text.ToString());
Assert.Equal(expectedMessage, textSpan.ToString());
Assert.Equal(expectedMessage, textUtf8Span.ToString());
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
{
var message = new string('>', stringLength);
var builder = new StringBuilder();
for (int i = 0; i < stringLength; i++)
{
builder.Append("\\u003E");
}
string expectedMessage = builder.ToString();
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan());
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message));
Assert.Equal(expectedMessage, text.ToString());
Assert.Equal(expectedMessage, textSpan.ToString());
Assert.Equal(expectedMessage, textUtf8Span.ToString());
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
}
[Theory]
[MemberData(nameof(JsonEncodedTextStrings))]
public static void GetUtf8BytesTest(string message, string expectedMessage)
{
byte[] expectedBytes = Encoding.UTF8.GetBytes(expectedMessage);
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan());
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message));
Assert.True(text.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(textSpan.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(textUtf8Span.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
[Theory]
[InlineData(100)]
[InlineData(1_000)]
[InlineData(10_000)]
public static void GetUtf8BytesLargeTest(int stringLength)
{
{
var message = new string('a', stringLength);
byte[] expectedBytes = Encoding.UTF8.GetBytes(message);
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan());
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message));
Assert.True(text.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(textSpan.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(textUtf8Span.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
{
var message = new string('>', stringLength);
var builder = new StringBuilder();
for (int i = 0; i < stringLength; i++)
{
builder.Append("\\u003E");
}
byte[] expectedBytes = Encoding.UTF8.GetBytes(builder.ToString());
JsonEncodedText text = JsonEncodedText.Encode(message);
JsonEncodedText textSpan = JsonEncodedText.Encode(message.AsSpan());
JsonEncodedText textUtf8Span = JsonEncodedText.Encode(Encoding.UTF8.GetBytes(message));
Assert.True(text.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(textSpan.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(textUtf8Span.EncodedUtf8Bytes.SequenceEqual(expectedBytes));
Assert.True(text.Equals(textSpan));
Assert.True(text.Equals(textUtf8Span));
Assert.Equal(text.GetHashCode(), textSpan.GetHashCode());
Assert.Equal(text.GetHashCode(), textUtf8Span.GetHashCode());
}
}
[Fact]
public static void InvalidUTF16()
{
var invalid = new char[5] { 'a', 'b', 'c', (char)0xDC00, 'a' };
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(invalid));
invalid = new char[5] { 'a', 'b', 'c', (char)0xD800, 'a' };
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(invalid));
invalid = new char[5] { 'a', 'b', 'c', (char)0xDC00, (char)0xD800 };
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(invalid));
var valid = new char[5] { 'a', 'b', 'c', (char)0xD800, (char)0xDC00 };
JsonEncodedText _ = JsonEncodedText.Encode(valid);
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(new string(valid).Substring(0, 4)));
}
[Theory]
[MemberData(nameof(UTF8ReplacementCharacterStrings))]
public static void ReplacementCharacterUTF8(byte[] dataUtf8, string expected)
{
JsonEncodedText text = JsonEncodedText.Encode(dataUtf8);
Assert.Equal(expected, text.ToString());
}
[Fact]
public static void InvalidEncode()
{
Assert.Throws<ArgumentNullException>(() => JsonEncodedText.Encode((string)null));
}
[ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))]
[OuterLoop]
public static void InvalidLargeEncode()
{
try
{
var largeValueString = new string('a', 400_000_000);
var utf8Value = new byte[400_000_000];
utf8Value.AsSpan().Fill((byte)'a');
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(largeValueString));
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(largeValueString.AsSpan()));
Assert.Throws<ArgumentException>(() => JsonEncodedText.Encode(utf8Value));
}
catch (OutOfMemoryException)
{
return;
}
}
public static IEnumerable<object[]> UTF8ReplacementCharacterStrings
{
get
{
return new List<object[]>
{
new object[] { new byte[] { 34, 97, 0xc3, 0x28, 98, 34 }, "\\u0022a\\uFFFD(b\\u0022" },
new object[] { new byte[] { 34, 97, 0xa0, 0xa1, 98, 34 }, "\\u0022a\\uFFFD\\uFFFDb\\u0022" },
new object[] { new byte[] { 34, 97, 0xe2, 0x28, 0xa1, 98, 34 }, "\\u0022a\\uFFFD(\\uFFFDb\\u0022" },
new object[] { new byte[] { 34, 97, 0xe2, 0x82, 0x28, 98, 34 }, "\\u0022a\\uFFFD(b\\u0022" },
new object[] { new byte[] { 34, 97, 0xf0, 0x28, 0x8c, 0xbc, 98, 34 }, "\\u0022a\\uFFFD(\\uFFFD\\uFFFDb\\u0022" },
new object[] { new byte[] { 34, 97, 0xf0, 0x90, 0x28, 0xbc, 98, 34 }, "\\u0022a\\uFFFD(\\uFFFDb\\u0022" },
new object[] { new byte[] { 34, 97, 0xf0, 0x28, 0x8c, 0x28, 98, 34 }, "\\u0022a\\uFFFD(\\uFFFD(b\\u0022" },
};
}
}
public static IEnumerable<object[]> JsonEncodedTextStrings
{
get
{
return new List<object[]>
{
new object[] {"", "" },
new object[] { "message", "message" },
new object[] { "mess\"age", "mess\\u0022age" },
new object[] { "mess\\u0022age", "mess\\\\u0022age" },
new object[] { ">>>>>", "\\u003E\\u003E\\u003E\\u003E\\u003E" },
new object[] { "\\u003e\\u003e\\u003e\\u003e\\u003e", "\\\\u003e\\\\u003e\\\\u003e\\\\u003e\\\\u003e" },
new object[] { "\\u003E\\u003E\\u003E\\u003E\\u003E", "\\\\u003E\\\\u003E\\\\u003E\\\\u003E\\\\u003E" },
};
}
}
public static IEnumerable<object[]> JsonEncodedTextStringsCustom
{
get
{
return new List<object[]>
{
new object[] {"", "" },
new object[] { "age", "\\u0061\\u0067\\u0065" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\"\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0032\\u0032\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9>>>>>\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\\u003E\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003e\\u003e\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\u00EA\u00EA\u00EA\u00EA\u00EA" },
};
}
}
/// <summary>
/// This is not a recommended way to customize the escaping, but is present here for test purposes.
/// </summary>
public sealed class CustomEncoderAllowingPlusSign : JavaScriptEncoder
{
public CustomEncoderAllowingPlusSign() { }
public override bool WillEncode(int unicodeScalar)
{
if (unicodeScalar == '+')
{
return false;
}
return Default.WillEncode(unicodeScalar);
}
public unsafe override int FindFirstCharacterToEncode(char* text, int textLength)
{
return Default.FindFirstCharacterToEncode(text, textLength);
}
public override int MaxOutputCharactersPerInputCharacter
{
get
{
return Default.MaxOutputCharactersPerInputCharacter;
}
}
public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten)
{
return Default.TryEncodeUnicodeScalar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten);
}
}
[Fact]
public static void CustomEncoderClass()
{
const string message = "a+";
const string expected = "a\\u002B";
JsonEncodedText text;
text = JsonEncodedText.Encode(message);
Assert.Equal(expected, text.ToString());
text = JsonEncodedText.Encode(message, null);
Assert.Equal(expected, text.ToString());
text = JsonEncodedText.Encode(message, JavaScriptEncoder.Default);
Assert.Equal(expected, text.ToString());
text = JsonEncodedText.Encode(message, new CustomEncoderAllowingPlusSign());
Assert.Equal("a+", text.ToString());
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
namespace NUnit.Framework
{
public abstract partial class Assert
{
#region Greater
#region Ints
/// <summary>
/// Verifies that the first int is greater than the second
/// int. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Greater(int arg1, int arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first int is greater than the second
/// int. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void Greater(int arg1, int arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region Unsigned Ints
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void Greater(uint arg1, uint arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
[CLSCompliant(false)]
public static void Greater(uint arg1, uint arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region Longs
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Greater(long arg1, long arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void Greater(long arg1, long arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region Unsigned Longs
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void Greater(ulong arg1, ulong arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
[CLSCompliant(false)]
public static void Greater(ulong arg1, ulong arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region Decimals
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Greater(decimal arg1, decimal arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void Greater(decimal arg1, decimal arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region Doubles
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Greater(double arg1, double arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void Greater(double arg1, double arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region Floats
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Greater(float arg1, float arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void Greater(float arg1, float arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#region IComparables
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Greater(IComparable arg1, IComparable arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void Greater(IComparable arg1, IComparable arg2)
{
Assert.That(arg1, Is.GreaterThan(arg2), null, null);
}
#endregion
#endregion
#region Less
#region Ints
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Less(int arg1, int arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void Less(int arg1, int arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region Unsigned Ints
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void Less(uint arg1, uint arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
[CLSCompliant(false)]
public static void Less(uint arg1, uint arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region Longs
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Less(long arg1, long arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void Less(long arg1, long arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region Unsigned Longs
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void Less(ulong arg1, ulong arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
[CLSCompliant(false)]
public static void Less(ulong arg1, ulong arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region Decimals
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Less(decimal arg1, decimal arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void Less(decimal arg1, decimal arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region Doubles
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Less(double arg1, double arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void Less(double arg1, double arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region Floats
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Less(float arg1, float arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void Less(float arg1, float arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#region IComparables
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Less(IComparable arg1, IComparable arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThan(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void Less(IComparable arg1, IComparable arg2)
{
Assert.That(arg1, Is.LessThan(arg2), null, null);
}
#endregion
#endregion
#region GreaterOrEqual
#region Ints
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void GreaterOrEqual(int arg1, int arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void GreaterOrEqual(int arg1, int arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region Unsigned Ints
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void GreaterOrEqual(uint arg1, uint arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
[CLSCompliant(false)]
public static void GreaterOrEqual(uint arg1, uint arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region Longs
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void GreaterOrEqual(long arg1, long arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void GreaterOrEqual(long arg1, long arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region Unsigned Longs
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void GreaterOrEqual(ulong arg1, ulong arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
[CLSCompliant(false)]
public static void GreaterOrEqual(ulong arg1, ulong arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region Decimals
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void GreaterOrEqual(decimal arg1, decimal arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void GreaterOrEqual(decimal arg1, decimal arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region Doubles
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void GreaterOrEqual(double arg1, double arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void GreaterOrEqual(double arg1, double arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region Floats
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void GreaterOrEqual(float arg1, float arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void GreaterOrEqual(float arg1, float arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#region IComparables
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void GreaterOrEqual(IComparable arg1, IComparable arg2, string message, params object[] args)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is greater than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be greater</param>
/// <param name="arg2">The second value, expected to be less</param>
public static void GreaterOrEqual(IComparable arg1, IComparable arg2)
{
Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
}
#endregion
#endregion
#region LessOrEqual
#region Ints
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void LessOrEqual(int arg1, int arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void LessOrEqual(int arg1, int arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region Unsigned Ints
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void LessOrEqual(uint arg1, uint arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
[CLSCompliant(false)]
public static void LessOrEqual(uint arg1, uint arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region Longs
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void LessOrEqual(long arg1, long arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void LessOrEqual(long arg1, long arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region Unsigned Longs
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
[CLSCompliant(false)]
public static void LessOrEqual(ulong arg1, ulong arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
[CLSCompliant(false)]
public static void LessOrEqual(ulong arg1, ulong arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region Decimals
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void LessOrEqual(decimal arg1, decimal arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void LessOrEqual(decimal arg1, decimal arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region Doubles
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void LessOrEqual(double arg1, double arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void LessOrEqual(double arg1, double arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region Floats
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void LessOrEqual(float arg1, float arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void LessOrEqual(float arg1, float arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#region IComparables
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void LessOrEqual(IComparable arg1, IComparable arg2, string message, params object[] args)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
}
/// <summary>
/// Verifies that the first value is less than or equal to the second
/// value. If it is not, then an
/// <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="arg1">The first value, expected to be less</param>
/// <param name="arg2">The second value, expected to be greater</param>
public static void LessOrEqual(IComparable arg1, IComparable arg2)
{
Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
}
#endregion
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
namespace System.ServiceModel.Dispatcher
{
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Compat", Justification = "Compat is an accepted abbreviation")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ClientOperationCompatBase
{
internal ClientOperationCompatBase() { }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public IList<IParameterInspector> ParameterInspectors
{
get
{
return this.parameterInspectors;
}
}
internal SynchronizedCollection<IParameterInspector> parameterInspectors;
}
public sealed class ClientOperation : ClientOperationCompatBase
{
private string _action;
private SynchronizedCollection<FaultContractInfo> _faultContractInfos;
private bool _serializeRequest;
private bool _deserializeReply;
private IClientMessageFormatter _formatter;
private IClientFaultFormatter _faultFormatter;
private bool _isInitiating = true;
private bool _isOneWay;
private bool _isTerminating;
private bool _isSessionOpenNotificationEnabled;
private string _name;
private ClientRuntime _parent;
private string _replyAction;
private MethodInfo _beginMethod;
private MethodInfo _endMethod;
private MethodInfo _syncMethod;
private MethodInfo _taskMethod;
private Type _taskTResult;
private bool _isFaultFormatterSetExplicit = false;
public ClientOperation(ClientRuntime parent, string name, string action)
: this(parent, name, action, null)
{
}
public ClientOperation(ClientRuntime parent, string name, string action, string replyAction)
{
if (parent == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
_parent = parent;
_name = name;
_action = action;
_replyAction = replyAction;
_faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>();
this.parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>();
}
public string Action
{
get { return _action; }
}
public SynchronizedCollection<FaultContractInfo> FaultContractInfos
{
get { return _faultContractInfos; }
}
public MethodInfo BeginMethod
{
get { return _beginMethod; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_beginMethod = value;
}
}
}
public MethodInfo EndMethod
{
get { return _endMethod; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_endMethod = value;
}
}
}
public MethodInfo SyncMethod
{
get { return _syncMethod; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_syncMethod = value;
}
}
}
public IClientMessageFormatter Formatter
{
get { return _formatter; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_formatter = value;
}
}
}
internal IClientFaultFormatter FaultFormatter
{
get
{
if (_faultFormatter == null)
{
_faultFormatter = new DataContractSerializerFaultFormatter(_faultContractInfos);
}
return _faultFormatter;
}
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_faultFormatter = value;
_isFaultFormatterSetExplicit = true;
}
}
}
internal bool IsFaultFormatterSetExplicit
{
get
{
return _isFaultFormatterSetExplicit;
}
}
internal IClientMessageFormatter InternalFormatter
{
get { return _formatter; }
set { _formatter = value; }
}
public bool IsInitiating
{
get { return _isInitiating; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_isInitiating = value;
}
}
}
public bool IsOneWay
{
get { return _isOneWay; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_isOneWay = value;
}
}
}
public bool IsTerminating
{
get { return _isTerminating; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_isTerminating = value;
}
}
}
public string Name
{
get { return _name; }
}
public ICollection<IParameterInspector> ClientParameterInspectors
{
get { return this.ParameterInspectors; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new SynchronizedCollection<IParameterInspector> ParameterInspectors
{
get { return this.parameterInspectors; }
}
public ClientRuntime Parent
{
get { return _parent; }
}
public string ReplyAction
{
get { return _replyAction; }
}
public bool SerializeRequest
{
get { return _serializeRequest; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_serializeRequest = value;
}
}
}
public bool DeserializeReply
{
get { return _deserializeReply; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_deserializeReply = value;
}
}
}
public MethodInfo TaskMethod
{
get { return _taskMethod; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_taskMethod = value;
}
}
}
public Type TaskTResult
{
get { return _taskTResult; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_taskTResult = value;
}
}
}
internal bool IsSessionOpenNotificationEnabled
{
get { return _isSessionOpenNotificationEnabled; }
set
{
lock (_parent.ThisLock)
{
_parent.InvalidateRuntime();
_isSessionOpenNotificationEnabled = value;
}
}
}
}
}
| |
using System;
/// <summary>
/// Convert.ToUInt16(String)
/// </summary>
public class ConvertToUInt1616
{
public static int Main()
{
ConvertToUInt1616 convertToUInt1616 = new ConvertToUInt1616();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt1616");
if (convertToUInt1616.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt16 from string 1");
try
{
string strVal = UInt16.MaxValue.ToString();
ushort ushortVal = Convert.ToUInt16(strVal);
if (ushortVal != UInt16.MaxValue)
{
TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt16 from string 2");
try
{
string strVal = UInt16.MinValue.ToString();
ushort ushortVal = Convert.ToUInt16(strVal);
if (ushortVal != UInt16.MinValue)
{
TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt16 from string 3");
try
{
string strVal = "-" + UInt16.MinValue.ToString();
ushort ushortVal = Convert.ToUInt16(strVal);
if (ushortVal != UInt16.MinValue)
{
TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt16 from string 4");
try
{
int intVal = this.GetInt32(0, (int)UInt16.MaxValue);
string strVal = "+" + intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal);
if (ushortVal != (UInt16)intVal)
{
TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Convert to UInt16 from string 5");
try
{
string strVal = null;
ushort ushortVal = Convert.ToUInt16(strVal);
if (ushortVal != 0)
{
TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: the string represents a number less than MinValue");
try
{
int intVal = this.GetInt32(1, Int32.MaxValue);
string strVal = "-" + intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal);
TestLibrary.TestFramework.LogError("N001", "the string represents a number less than MinValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a number greater than MaxValue");
try
{
int intVal = this.GetInt32((int)UInt16.MaxValue + 1, Int32.MaxValue);
string strVal = intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal);
TestLibrary.TestFramework.LogError("N003", "the string represents a number greater than MaxValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string does not consist of an optional sign followed by a sequence of digits ");
try
{
string strVal = "helloworld";
ushort ushortVal = Convert.ToUInt16(strVal);
TestLibrary.TestFramework.LogError("N005", "the string does not consist of an optional sign followed by a sequence of digits but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string is empty string");
try
{
string strVal = string.Empty;
ushort ushortVal = Convert.ToUInt16(strVal);
TestLibrary.TestFramework.LogError("N007", "the string is empty string but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using System.Windows.Controls;
using DevExpress.Internal;
using DevExpress.Mvvm.UI.Native;
using NUnit.Framework;
using System;
using System.IO.Packaging;
using System.Linq;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Collections.Generic;
namespace DevExpress.Mvvm.UI.Tests {
[TestFixture]
public class NotificationTests {
[TearDown]
public void TearDown() {
if(CustomNotifier.positioner != null) {
Assert.AreEqual(0, CustomNotifier.positioner.Items.Count(i => i != null));
}
}
[Test]
public void PositionerTest() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 3);
Point p;
Assert.AreEqual(true, pos.HasEmptySlot());
p = pos.Add("item1", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20, p.Y);
p = pos.Add("item2", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10, p.Y);
p = pos.Add("item3", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10 + 50 + 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item2");
p = pos.Add("item4", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10, p.Y);
pos.Remove("item3");
p = pos.Add("item5", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20 + 50 + 10 + 50 + 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item1");
Assert.AreEqual(true, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.BottomRight, 3);
p = pos.Add("item1", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20, p.Y);
p = pos.Add("item2", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10, p.Y);
p = pos.Add("item3", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10 - 50 - 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item2");
p = pos.Add("item4", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10, p.Y);
pos.Remove("item3");
p = pos.Add("item5", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 50 - 20 - 50 - 10 - 50 - 10, p.Y);
Assert.AreEqual(false, pos.HasEmptySlot());
pos.Remove("item1");
Assert.AreEqual(true, pos.HasEmptySlot());
}
[Test]
public void PositionerTest2() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 480);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 460);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 250), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 360), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
}
[Test]
public void PositionerTest3() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(10, 25, 790, 575), NotificationPosition.TopRight, 100);
Point p = pos.Add("item1", 200, 100);
Assert.AreEqual(10 + 790 - 200, p.X);
Assert.AreEqual(25 + 20, p.Y);
pos = new NotificationPositioner<string>();
pos.Update(new Rect(10, 25, 790, 575), NotificationPosition.BottomRight, 100);
p = pos.Add("item1", 200, 100);
Assert.AreEqual(10 + 790 - 200, p.X);
Assert.AreEqual(600 - 20 - 100, p.Y);
}
[Test]
public void PositionerTest4() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 480);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 460);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 300), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(false, pos.HasEmptySlot());
pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 410), NotificationPosition.TopRight, 100);
pos.Add("item1", 200, 100);
pos.Add("item1", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
}
[Test]
public void PositionerHasSlotTest() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 3);
pos.Add("item1", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Remove("item1");
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Add("item2", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Add("item3", 200, 100);
Assert.AreEqual(true, pos.HasEmptySlot());
pos.Add("item4", 200, 100);
Assert.AreEqual(false, pos.HasEmptySlot());
}
static void WaitWithDispatcher(Task<NotificationResult> task) {
while(task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Faulted) {
DispatcherUtil.DoEvents();
}
}
public static class DispatcherUtil {
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents() {
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
System.Windows.Forms.Application.DoEvents();
}
private static object ExitFrame(object frame) {
((DispatcherFrame)frame).Continue = false;
return null;
}
}
[Test]
public void ResultsTest() {
CustomNotification toast;
Task<NotificationResult> task;
var notifier = new CustomNotifier();
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.TimedOut, task.Result);
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
toast.Activate();
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.Activated, task.Result);
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
toast.Dismiss();
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.UserCanceled, task.Result);
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
toast.Hide();
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.ApplicationHidden, task.Result);
var tasks = Enumerable.Range(0, 10).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void UpdatingPositionerTest() {
CustomNotification toast;
Task<NotificationResult> task;
var notifier = new CustomNotifier();
var tasks = Enumerable.Range(0, 5).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
toast = new CustomNotification(null, notifier);
task = notifier.ShowAsync(toast, 1);
notifier.UpdatePositioner(NotificationPosition.TopRight, 2);
WaitWithDispatcher(task);
Assert.AreEqual(NotificationResult.TimedOut, task.Result);
tasks = Enumerable.Range(0, 10).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
notifier.UpdatePositioner(NotificationPosition.TopRight, 2);
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void ShowingTooManyToastsTest() {
var notifier = new CustomNotifier();
notifier.UpdatePositioner(NotificationPosition.TopRight, 100);
var tasks = Enumerable.Range(0, 100).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void SettingApplicationIDToNullTest() {
var service = new NotificationService();
service.ApplicationId = "";
service.ApplicationId = null;
Assert.IsTrue(true);
}
[Test]
public void RemovePostponedNotificationTest() {
var notifier = new CustomNotifier();
notifier.UpdatePositioner(NotificationPosition.TopRight, 1);
var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
toasts[2].Hide();
tasks.ToList().ForEach(WaitWithDispatcher);
Assert.AreEqual(NotificationResult.TimedOut, tasks[0].Result);
Assert.AreEqual(NotificationResult.TimedOut, tasks[1].Result);
Assert.AreEqual(NotificationResult.ApplicationHidden, tasks[2].Result);
}
class TestScreen : IScreen {
public Rect bounds;
public Rect GetWorkingArea(Point point) {
return new Rect(
bounds.X - point.X,
bounds.Y - point.Y,
bounds.Width, bounds.Height);
}
public void Changed() {
if(WorkingAreaChanged != null)
WorkingAreaChanged();
}
public event Action WorkingAreaChanged;
}
[Test]
public void BasicResolutionChangedHandlingTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
var notifier = new CustomNotifier(testScreen);
notifier.UpdatePositioner(NotificationPosition.BottomRight, 2);
var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
var pos = CustomNotifier.positioner;
var ps = pos.Items.Select(i => pos.GetItemPosition(i)).ToList();
Assert.AreEqual(new Point(615, 390), ps[0]);
Assert.AreEqual(new Point(615, 290), ps[1]);
testScreen.bounds = new Rect(0, 0, 800, 600);
testScreen.Changed();
pos = CustomNotifier.positioner;
ps = pos.Items.Select(i => pos.GetItemPosition(i)).ToList();
Assert.AreEqual(new Point(415, 490), ps[0]);
Assert.AreEqual(new Point(415, 390), ps[1]);
tasks.ToList().ForEach(WaitWithDispatcher);
tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void NotificationsArentLostOnPositionerUpdateTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
var notifier1 = new CustomNotifier(testScreen);
var notifier2 = new CustomNotifier(testScreen);
var positioner = CustomNotifier.positioner;
notifier1.UpdatePositioner(NotificationPosition.BottomRight, 5);
var toasts1 = Enumerable.Range(0, 1).Select(_ => new CustomNotification(null, notifier1)).ToList();
var toasts2 = Enumerable.Range(0, 1).Select(_ => new CustomNotification(null, notifier2)).ToList();
var tasks1 = toasts1.Select(toast => notifier1.ShowAsync(toast, 1)).ToList();
var tasks2 = toasts2.Select(toast => notifier2.ShowAsync(toast, 1)).ToList();
tasks1.Union(tasks2).ToList().ForEach(WaitWithDispatcher);
tasks1.Union(tasks2).ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
}
[Test]
public void UpdatePositionerTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 800, 600) };
var notifier = new CustomNotifier(testScreen);
var pos = CustomNotifier.positioner;
var toast = new CustomNotification(null, notifier);
var task = notifier.ShowAsync(toast, 1);
var p1 = CustomNotifier.positioner.GetItemPosition(CustomNotifier.positioner.Items[0]);
Assert.AreEqual(415, p1.X);
Assert.AreEqual(20, p1.Y);
notifier.UpdatePositioner(NotificationPosition.BottomRight, 3);
p1 = CustomNotifier.positioner.GetItemPosition(CustomNotifier.positioner.Items[0]);
Assert.AreEqual(415, p1.X);
Assert.AreEqual(490, p1.Y);
WaitWithDispatcher(task);
}
[Test, Category("TODO")]
public void ResolutionChangingTest() {
var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
var notifier = new CustomNotifier(testScreen);
notifier.UpdatePositioner(NotificationPosition.BottomRight, 2);
var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
Assert.AreEqual(2, CustomNotifier.positioner.Items.Count(i => i != null));
testScreen.bounds = new Rect(0, 0, 800, 600);
testScreen.Changed();
Assert.AreEqual(2, CustomNotifier.positioner.Items.Count(i => i != null));
tasks.ToList().ForEach(WaitWithDispatcher);
}
[Test]
public void PositionUpdateTest() {
var pos = new NotificationPositioner<string>();
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 3);
Point p;
p = pos.Add("item1", 200, 50);
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(20, p.Y);
pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.BottomRight, 3);
p = pos.GetItemPosition("item1");
Assert.AreEqual(800 - 200, p.X);
Assert.AreEqual(600 - 20 - 50, p.Y);
}
[Test]
public void GetBackgroundTest() {
string _ = PackUriHelper.UriSchemePack;
Action<byte, byte, byte, string> assertMatch = (r, g, b, icon) => {
string path = string.Format("pack://application:,,,/{0};component/Icons/{1}", "DevExpress.Mvvm.Tests.Free", icon);
Uri uri = new Uri(path, UriKind.Absolute);
var bmp = new System.Drawing.Bitmap(Application.GetResourceStream(uri).Stream);
Assert.AreEqual(System.Windows.Media.Color.FromRgb(r, g, b), BackgroundCalculator.GetBestMatch(bmp));
};
assertMatch(9, 74, 178, "icon1.ico");
assertMatch(210, 71, 38, "icon2.ico");
assertMatch(81, 51, 171, "icon3.ico");
assertMatch(210, 71, 38, "icon4.ico");
assertMatch(81, 51, 171, "icon5.ico");
assertMatch(0, 130, 153, "icon6.ico");
assertMatch(9, 74, 178, "icon7.ico");
}
[Test]
public void ThrowOnApplicationIDNullTest() {
var service = new NotificationService();
if(!service.AreWin8NotificationsAvailable)
return;
try {
service.CreatePredefinedNotification("", "", "");
Assert.Fail();
} catch(ArgumentNullException e) {
Assert.AreEqual("ApplicationId", e.ParamName);
}
}
[Test]
public void UpdateCustomToastPositionTest() {
var service = new NotificationService();
var toast = service.CreateCustomNotification(null);
Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
service.CustomNotificationPosition = NotificationPosition.BottomRight;
Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);
service = new NotificationService();
service.CustomNotificationPosition = NotificationPosition.BottomRight;
toast = service.CreateCustomNotification(null);
Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);
service.CustomNotificationPosition = NotificationPosition.TopRight;
Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
}
[Test]
public void ResettingTimerOfHiddenNotificationTest() {
var customNotifier = new CustomNotifier(new TestScreen());
var toast = new CustomNotification(null, customNotifier);
customNotifier.ShowAsync(toast);
customNotifier.Hide(toast);
customNotifier.ResetTimer(toast);
customNotifier.StopTimer(toast);
}
class TestTemplateSelector : DataTemplateSelector {
public bool Called = false;
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
Called = true;
return base.SelectTemplate(item, container);
}
}
[Test]
public void CustomNotificationTemplateSelectorTest() {
var customNotifier = new CustomNotifier(new TestScreen { bounds = new Rect(0, 0, 1000, 500) });
var selector = new TestTemplateSelector();
customNotifier.ContentTemplateSelector = selector;
var toast = new CustomNotification(null, customNotifier);
WaitWithDispatcher(customNotifier.ShowAsync(toast, 1));
Assert.IsTrue(selector.Called);
}
[Test]
public void ThrowOnAutoHeight() {
var style = new Style();
style.Setters.Add(new Setter(FrameworkElement.HeightProperty, double.NaN));
var service = new NotificationService();
service.CustomNotificationStyle = style;
var toast = service.CreateCustomNotification(null);
try {
toast.ShowAsync();
Assert.Fail();
} catch(InvalidOperationException) { }
}
[Test]
public void ConvertTimeSpanToMilliseconds() {
var service = new NotificationService();
service.CustomNotificationDuration = TimeSpan.MaxValue;
var toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(int.MaxValue, toast.duration);
service.CustomNotificationDuration = TimeSpan.MinValue;
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(0, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds((double)int.MaxValue + int.MaxValue);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(int.MaxValue, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds(int.MaxValue);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(int.MaxValue, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds(150);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(150, toast.duration);
service.CustomNotificationDuration = TimeSpan.FromMilliseconds(1);
toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
Assert.AreEqual(1, toast.duration);
}
[Test, Description("T892461")]
public void CreateApplicationWindowNotification() {
var service = new NotificationService();
service.CustomNotificationScreen = NotificationScreen.ApplicationWindow;
service.CreateCustomNotification(null);
}
[Test, Description("T994586")]
public void GetDpiTest() {
var dpi = PrimaryScreen.GetDpi(new Point(1, 1));
Assert.AreEqual(1, dpi.X);
Assert.AreEqual(1, dpi.Y);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.CSharp.Interactive;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Scripting;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Traits = Roslyn.Test.Utilities.Traits;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
[Trait(Traits.Feature, Traits.Features.InteractiveHost)]
public sealed class InteractiveHostTests : AbstractInteractiveHostTests
{
#region Utils
private SynchronizedStringWriter _synchronizedOutput;
private SynchronizedStringWriter _synchronizedErrorOutput;
private int[] _outputReadPosition = new int[] { 0, 0 };
internal readonly InteractiveHost Host;
public InteractiveHostTests()
{
Host = new InteractiveHost(typeof(CSharpRepl), GetInteractiveHostPath(), ".", millisecondsTimeout: -1);
RedirectOutput();
Host.ResetAsync(InteractiveHostOptions.Default).Wait();
var remoteService = Host.TryGetService();
Assert.NotNull(remoteService);
remoteService.SetTestObjectFormattingOptions();
// assert and remove logo:
var output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var errorOutput = ReadErrorOutputToEnd();
Assert.Equal("", errorOutput);
Assert.Equal(2, output.Length);
Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]);
// "Type "#help" for more information."
Assert.Equal(FeaturesResources.TypeHelpForMoreInformation, output[1]);
// remove logo:
ClearOutput();
}
public override void Dispose()
{
try
{
Process process = Host.TryGetProcess();
DisposeInteractiveHostProcess(Host);
// the process should be terminated
if (process != null && !process.HasExited)
{
process.WaitForExit();
}
}
finally
{
// Dispose temp files only after the InteractiveHost exits,
// so that assemblies are unloaded.
base.Dispose();
}
}
internal void RedirectOutput()
{
_synchronizedOutput = new SynchronizedStringWriter();
_synchronizedErrorOutput = new SynchronizedStringWriter();
ClearOutput();
Host.Output = _synchronizedOutput;
Host.ErrorOutput = _synchronizedErrorOutput;
}
internal AssemblyLoadResult LoadReference(string reference)
{
return Host.TryGetService().LoadReferenceThrowing(reference, addReference: true);
}
internal bool Execute(string code)
{
var task = Host.ExecuteAsync(code);
task.Wait();
return task.Result.Success;
}
internal bool IsShadowCopy(string path)
{
return Host.TryGetService().IsShadowCopy(path);
}
public string ReadErrorOutputToEnd()
{
return ReadOutputToEnd(isError: true);
}
public void ClearOutput()
{
_outputReadPosition = new int[] { 0, 0 };
_synchronizedOutput.Clear();
_synchronizedErrorOutput.Clear();
}
public void RestartHost(string rspFile = null)
{
ClearOutput();
var initTask = Host.ResetAsync(InteractiveHostOptions.Default.WithInitializationFile(rspFile));
initTask.Wait();
}
public string ReadOutputToEnd(bool isError = false)
{
var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput;
var markPrefix = '\uFFFF';
var mark = markPrefix + Guid.NewGuid().ToString();
// writes mark to the STDOUT/STDERR pipe in the remote process:
Host.TryGetService().RemoteConsoleWrite(Encoding.UTF8.GetBytes(mark), isError);
while (true)
{
var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]);
if (data != null)
{
return data;
}
Thread.Sleep(10);
}
}
internal class CompiledFile
{
public string Path;
public ImmutableArray<byte> Image;
}
internal CompiledFile CompileLibrary(TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references)
{
const string Prefix = "RoslynTestFile_";
fileName = Prefix + fileName;
assemblyName = Prefix + assemblyName;
var file = dir.CreateFile(fileName);
var compilation = CreateCompilation(
new[] { source },
assemblyName: assemblyName,
references: references.Concat(new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }),
options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll);
var image = compilation.EmitToArray();
file.WriteAllBytes(image);
return new CompiledFile { Path = file.Path, Image = image };
}
#endregion
[Fact] // Bugs #5018, #5344
public void OutputRedirection()
{
Execute(@"
System.Console.WriteLine(""hello-\u4567!"");
System.Console.Error.WriteLine(""error-\u7890!"");
1+1
");
var output = ReadOutputToEnd();
var error = ReadErrorOutputToEnd();
Assert.Equal("hello-\u4567!\r\n2\r\n", output);
Assert.Equal("error-\u7890!\r\n", error);
}
[Fact]
public void OutputRedirection2()
{
Execute(@"System.Console.WriteLine(1);");
Execute(@"System.Console.Error.WriteLine(2);");
var output = ReadOutputToEnd();
var error = ReadErrorOutputToEnd();
Assert.Equal("1\r\n", output);
Assert.Equal("2\r\n", error);
RedirectOutput();
Execute(@"System.Console.WriteLine(3);");
Execute(@"System.Console.Error.WriteLine(4);");
output = ReadOutputToEnd();
error = ReadErrorOutputToEnd();
Assert.Equal("3\r\n", output);
Assert.Equal("4\r\n", error);
}
[Fact]
public void StackOverflow()
{
// Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) ignores SetErrorMode and shows crash dialog, which would hang the test:
if (Environment.OSVersion.Version < new Version(6, 1, 0, 0))
{
return;
}
Execute(@"
int foo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
{
return foo(0,1,2,3,4,5,6,7,8,9) + foo(0,1,2,3,4,5,6,7,8,9);
}
foo(0,1,2,3,4,5,6,7,8,9)
");
Assert.Equal("", ReadOutputToEnd());
// Hosting process exited with exit code -1073741571.
Assert.Equal("Process is terminated due to StackOverflowException.\n" + string.Format(FeaturesResources.HostingProcessExitedWithExitCode, -1073741571), ReadErrorOutputToEnd().Trim());
Execute(@"1+1");
Assert.Equal("2\r\n", ReadOutputToEnd().ToString());
}
private const string MethodWithInfiniteLoop = @"
void foo()
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
System.Console.Error.WriteLine(""in the loop"");
i = i + 1;
}
}
}
";
[Fact]
public void AsyncExecute_InfiniteLoop()
{
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
var executeTask = Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()");
Assert.True(mayTerminate.WaitOne());
RestartHost();
executeTask.Wait();
Assert.True(Execute(@"1+1"));
Assert.Equal("2\r\n", ReadOutputToEnd());
}
[Fact(Skip = "529027")]
public void AsyncExecute_HangingForegroundThreads()
{
var mayTerminate = new ManualResetEvent(false);
Host.OutputReceived += (_, __) =>
{
mayTerminate.Set();
};
var executeTask = Host.ExecuteAsync(@"
using System.Threading;
int i1 = 0;
Thread t1 = new Thread(() => { while(true) { i1++; } });
t1.Name = ""TestThread-1"";
t1.IsBackground = false;
t1.Start();
int i2 = 0;
Thread t2 = new Thread(() => { while(true) { i2++; } });
t2.Name = ""TestThread-2"";
t2.IsBackground = true;
t2.Start();
Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite));
t3.Name = ""TestThread-3"";
t3.Start();
while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { }
System.Console.WriteLine(""terminate!"");
while(true) {}
");
Assert.Equal("", ReadErrorOutputToEnd());
Assert.True(mayTerminate.WaitOne());
var service = Host.TryGetService();
Assert.NotNull(service);
var process = Host.TryGetProcess();
Assert.NotNull(process);
service.EmulateClientExit();
// the process should terminate with exit code 0:
process.WaitForExit();
Assert.Equal(0, process.ExitCode);
}
[Fact]
public void AsyncExecuteFile_InfiniteLoop()
{
var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path;
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
var executeTask = Host.ExecuteFileAsync(file);
mayTerminate.WaitOne();
RestartHost();
executeTask.Wait();
Assert.True(Execute(@"1+1"));
Assert.Equal("2\r\n", ReadOutputToEnd());
}
[Fact]
public void AsyncExecuteFile_SourceKind()
{
var file = Temp.CreateFile().WriteAllText("1+1").Path;
var task = Host.ExecuteFileAsync(file);
task.Wait();
Assert.False(task.Result.Success);
var errorOut = ReadErrorOutputToEnd().Trim();
Assert.True(errorOut.StartsWith(file + "(1,4):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002");
}
[Fact]
public void AsyncExecuteFile_NonExistingFile()
{
var task = Host.ExecuteFileAsync("non existing file");
task.Wait();
Assert.False(task.Result.Success);
var errorOut = ReadErrorOutputToEnd().Trim();
Assert.Contains("Specified file not found.", errorOut, StringComparison.Ordinal);
Assert.Contains("Searched in directories:", errorOut, StringComparison.Ordinal);
}
[Fact]
public void AsyncExecuteFile()
{
var file = Temp.CreateFile().WriteAllText(@"
using static System.Console;
public class C
{
public int field = 4;
public int Foo(int i) { return i; }
}
public int Foo(int i) { return i; }
WriteLine(5);
").Path;
var task = Host.ExecuteFileAsync(file);
task.Wait();
Assert.True(task.Result.Success);
Assert.Equal("5", ReadOutputToEnd().Trim());
Execute("Foo(2)");
Assert.Equal("2", ReadOutputToEnd().Trim());
Execute("new C().Foo(3)");
Assert.Equal("3", ReadOutputToEnd().Trim());
Execute("new C().field");
Assert.Equal("4", ReadOutputToEnd().Trim());
}
[Fact]
public void AsyncExecuteFile_InvalidFileContent()
{
var executeTask = Host.ExecuteFileAsync(typeof(Process).Assembly.Location);
executeTask.Wait();
var errorOut = ReadErrorOutputToEnd().Trim();
Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056");
Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002");
}
[Fact]
public void AsyncExecuteFile_ScriptFileWithBuildErrors()
{
var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}");
Host.ExecuteFileAsync(file.Path).Wait();
var errorOut = ReadErrorOutputToEnd().Trim();
Assert.True(errorOut.StartsWith(file.Path + "(1,2):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1024"), "Error output should include error CS1024");
}
/// <summary>
/// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be
/// even invoked since we resolve the assembly via Fusion.
/// </summary>
[Fact(Skip = "987032")]
public void UserDefinedAssemblyResolve_InfiniteLoop()
{
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
Host.TryGetService().HookMaliciousAssemblyResolve();
var executeTask = Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid());
Assert.True(mayTerminate.WaitOne());
executeTask.Wait();
Assert.True(Execute(@"1+1"));
var output = ReadOutputToEnd();
Assert.Equal("2\r\n", output);
}
[Fact]
public void AddReference_PartialName()
{
Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited"));
Assert.True(LoadReference("System").IsSuccessful);
Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited"));
}
[Fact]
public void AddReference_PartialName_LatestVersion()
{
// there might be two versions of System.Data - v2 and v4, we should get the latter:
Assert.True(LoadReference("System.Data").IsSuccessful);
Assert.True(LoadReference("System").IsSuccessful);
Assert.True(LoadReference("System.Xml").IsSuccessful);
var version = (Version)Host.TryGetService().ExecuteAndWrap("new System.Data.DataSet().GetType().Assembly.GetName().Version").Unwrap();
Assert.True(version >= new Version(4, 0, 0, 0), "Actual:" + version.ToString());
}
[Fact]
public void AddReference_FullName()
{
Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited"));
Assert.True(LoadReference(typeof(Process).Assembly.FullName).IsSuccessful);
Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited"));
}
[ConditionalFact(typeof(Framework35Installed))]
public void AddReference_VersionUnification1()
{
var location = typeof(Enumerable).Assembly.Location;
// V3.5 unifies with the current Framework version:
var result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Assert.True(result.IsSuccessful, "First load");
Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase);
Assert.Equal(location, result.OriginalPath);
result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Assert.False(result.IsSuccessful, "Already loaded");
Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase);
Assert.Equal(location, result.OriginalPath);
result = LoadReference("System.Core");
Assert.False(result.IsSuccessful, "Already loaded");
Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase);
Assert.Equal(location, result.OriginalPath);
}
// TODO: merge with previous test
[Fact]
public void AddReference_VersionUnification2()
{
var location = typeof(Enumerable).Assembly.Location;
var result = LoadReference("System.Core");
Assert.True(result.IsSuccessful, "First load");
Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase);
Assert.Equal(location, result.OriginalPath);
result = LoadReference("System.Core.dll");
Assert.False(result.IsSuccessful, "Already loaded");
Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase);
Assert.Equal(location, result.OriginalPath);
}
[Fact]
public void AddReference_Path()
{
Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited"));
Assert.True(LoadReference(typeof(Process).Assembly.Location).IsSuccessful);
Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited"));
}
[Fact(Skip = "530414")]
public void AddReference_ShadowCopy()
{
var dir = Temp.CreateDirectory();
// create C.dll
var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }");
// load C.dll:
Assert.True(LoadReference(c.Path).IsSuccessful);
Assert.True(Execute("new C()"));
Assert.Equal("C { }", ReadOutputToEnd().Trim());
// rewrite C.dll:
File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 });
// we can still run code:
var result = Execute("new C()");
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("C { }", ReadOutputToEnd().Trim());
Assert.True(result);
}
/// <summary>
/// Tests that a dependency is correctly resolved and loaded at runtime.
/// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded.
/// </summary>
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")]
public void AddReference_Dependencies()
{
var dir = Temp.CreateDirectory();
var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }");
var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image));
var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image));
AssemblyLoadResult result;
result = LoadReference(a.Path);
Assert.Equal(a.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.True(result.IsSuccessful);
Assert.True(Execute("A.CallB()"));
// c.dll is loaded as a dependency, so #r should be successful:
result = LoadReference(c.Path);
Assert.Equal(c.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.True(result.IsSuccessful);
// c.dll was already loaded explicitly via #r so we should fail now:
result = LoadReference(c.Path);
Assert.False(result.IsSuccessful);
Assert.Equal(c.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("1", ReadOutputToEnd().Trim());
}
/// <summary>
/// When two files of the same version are in the same directory, prefer .dll over .exe.
/// </summary>
[Fact]
public void AddReference_Dependencies_DllExe()
{
var dir = Temp.CreateDirectory();
var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }");
var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }");
var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }",
MetadataReference.CreateFromImage(dll.Image));
Assert.True(LoadReference(main.Path).IsSuccessful);
Assert.True(Execute("Program.Main()"));
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("1", ReadOutputToEnd().Trim());
}
[Fact]
public void AddReference_Dependencies_Versions()
{
var dir1 = Temp.CreateDirectory();
var dir2 = Temp.CreateDirectory();
var dir3 = Temp.CreateDirectory();
// [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1);
// [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2);
Assert.True(LoadReference(file1.Path).IsSuccessful);
Assert.True(LoadReference(file2.Path).IsSuccessful);
var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }",
MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull()));
Assert.True(LoadReference(main.Path).IsSuccessful);
Assert.True(Execute("Program.Main()"));
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("2", ReadOutputToEnd().Trim());
}
[Fact]
public void AddReference_AlreadyLoadedDependencies()
{
var dir = Temp.CreateDirectory();
var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }");
var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }",
MetadataReference.CreateFromFile(lib1.Path));
Execute("#r \"" + lib1.Path + "\"");
Execute("#r \"" + lib2.Path + "\"");
Execute("new C().M()");
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("1", ReadOutputToEnd().Trim());
}
[Fact(Skip = "530414")]
public void AddReference_LoadUpdatedReference()
{
var dir = Temp.CreateDirectory();
var source1 = "public class C { public int X = 1; }";
var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C");
var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
// use:
Execute(@"
#r """ + file.Path + @"""
C foo() { return new C(); }
new C().X
");
// update:
var source2 = "public class D { public int Y = 2; }";
var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C");
file.WriteAllBytes(c2.EmitToArray());
// add the reference again:
Execute(@"
#r """ + file.Path + @"""
new D().Y
");
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal(
@"1
2", ReadOutputToEnd().Trim());
}
[Fact(Skip = "987032")]
public void AddReference_MultipleReferencesWithSameWeakIdentity()
{
var dir = Temp.CreateDirectory();
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var source1 = "public class C1 { }";
var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
var source2 = "public class C2 { }";
var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray());
Execute(@"
#r """ + file1.Path + @"""
#r """ + file2.Path + @"""
");
Execute("new C1()");
Execute("new C2()");
Assert.Equal(
@"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side.
(1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
(1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", ReadErrorOutputToEnd().Trim());
Assert.Equal("", ReadOutputToEnd().Trim());
}
//// TODO (987032):
//// [Fact]
//// public void AsyncInitializeContextWithDotNETLibraries()
//// {
//// var rspFile = Temp.CreateFile();
//// var rspDisplay = Path.GetFileName(rspFile.Path);
//// var initScript = Temp.CreateFile();
//// rspFile.WriteAllText(@"
/////r:System.Core
////""" + initScript.Path + @"""
////");
//// initScript.WriteAllText(@"
////using static System.Console;
////using System.Linq.Expressions;
////WriteLine(Expression.Constant(123));
////");
//// // override default "is restarting" behavior (the REPL is already initialized):
//// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true);
//// task.Wait();
//// var output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
//// var errorOutput = ReadErrorOutputToEnd();
//// Assert.Equal(4, output.Length);
//// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]);
//// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]);
//// Assert.Equal("Type \"#help\" for more information.", output[2]);
//// Assert.Equal("123", output[3]);
//// Assert.Equal("", errorOutput);
//// Host.InitializeContextAsync(rspFile.Path).Wait();
//// output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
//// errorOutput = ReadErrorOutputToEnd();
//// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines.");
//// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]);
//// Assert.Equal("123", output[1]);
//// Assert.Equal("", errorOutput);
//// }
//// [Fact]
//// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries()
//// {
//// var dir = Temp.CreateDirectory();
//// var rspFile = Temp.CreateFile();
//// var initScript = Temp.CreateFile();
//// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }");
//// rspFile.WriteAllText(@"
/////r:System.Numerics
/////r:" + dll.Path + @"
////""" + initScript.Path + @"""
////");
//// initScript.WriteAllText(@"
////using static System.Console;
////using System.Numerics;
////WriteLine(new Complex(12, 6).Real + C.Main());
////");
//// // override default "is restarting" behavior (the REPL is already initialized):
//// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true);
//// task.Wait();
//// var errorOutput = ReadErrorOutputToEnd();
//// Assert.Equal("", errorOutput);
//// var output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
//// Assert.Equal(4, output.Length);
//// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]);
//// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]);
//// Assert.Equal("Type \"#help\" for more information.", output[2]);
//// Assert.Equal("13", output[3]);
//// }
[Fact]
public void ReferenceDirectives()
{
var task = Host.ExecuteAsync(@"
#r ""System.Numerics""
#r """ + typeof(System.Linq.Expressions.Expression).Assembly.Location + @"""
using static System.Console;
using System.Linq.Expressions;
using System.Numerics;
WriteLine(Expression.Constant(1));
WriteLine(new Complex(2, 6).Real);
");
task.Wait();
var output = ReadOutputToEnd();
Assert.Equal("1\r\n2\r\n", output);
}
[Fact]
public void ExecutesOnStaThread()
{
var task = Host.ExecuteAsync(@"
#r ""System""
#r ""System.Xaml""
#r ""WindowsBase""
#r ""PresentationCore""
#r ""PresentationFramework""
new System.Windows.Window();
System.Console.WriteLine(""OK"");
");
task.Wait();
var error = ReadErrorOutputToEnd();
Assert.Equal("", error);
var output = ReadOutputToEnd();
Assert.Equal("OK\r\n", output);
}
[Fact]
public void MultiModuleAssembly()
{
var dir = Temp.CreateDirectory();
var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll);
dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2);
dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3);
var task = Host.ExecuteAsync(@"
#r """ + dll.Path + @"""
new object[] { new Class1(), new Class2(), new Class3() }
");
task.Wait();
var error = ReadErrorOutputToEnd();
Assert.Equal("", error);
var output = ReadOutputToEnd();
Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output);
}
[Fact]
public void SearchPaths1()
{
var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01);
var srcDir = Temp.CreateDirectory();
var dllDir = Path.GetDirectoryName(dll.Path);
srcDir.CreateFile("foo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");");
Func<string, string> normalizeSeparatorsAndFrameworkFolders = (s) => s.Replace("\\", "\\\\").Replace("Framework64", "Framework");
// print default:
Host.ExecuteAsync(@"ReferencePaths").Wait();
var output = ReadOutputToEnd();
Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultReferenceSearchPaths)) + "\" }\r\n", output);
Host.ExecuteAsync(@"SourcePaths").Wait();
output = ReadOutputToEnd();
Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultSourceSearchPaths)) + "\" }\r\n", output);
// add and test if added:
Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");").Wait();
Host.ExecuteAsync(@"SourcePaths").Wait();
output = ReadOutputToEnd();
Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultSourceSearchPaths.Concat(new[] { srcDir.Path }))) + "\" }\r\n", output);
// execute file (uses modified search paths), the file adds a reference path
Host.ExecuteFileAsync("foo.csx").Wait();
Host.ExecuteAsync(@"ReferencePaths").Wait();
output = ReadOutputToEnd();
Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultReferenceSearchPaths.Concat(new[] { dllDir }))) + "\" }\r\n", output);
Host.AddReferenceAsync(Path.GetFileName(dll.Path)).Wait();
Host.ExecuteAsync(@"typeof(Metadata.ICSProp)").Wait();
var error = ReadErrorOutputToEnd();
Assert.Equal("", error);
output = ReadOutputToEnd();
Assert.Equal("[Metadata.ICSProp]\r\n", output);
}
[Fact]
public void InvalidArguments()
{
Assert.Throws<FileNotFoundException>(() => LoadReference(""));
Assert.Throws<FileNotFoundException>(() => LoadReference("\0"));
Assert.Throws<FileNotFoundException>(() => LoadReference("blah \0"));
Assert.Throws<FileNotFoundException>(() => LoadReference("*.dll"));
Assert.Throws<FileNotFoundException>(() => LoadReference("*.exe"));
Assert.Throws<FileNotFoundException>(() => LoadReference("http://foo.dll"));
Assert.Throws<FileNotFoundException>(() => LoadReference("blah:foo.dll"));
Assert.Throws<FileNotFoundException>(() => LoadReference("C:\\" + new string('x', 10000) + "\\foo.dll"));
Assert.Throws<FileNotFoundException>(() => LoadReference("system,mscorlib"));
Assert.Throws<FileNotFoundException>(() => LoadReference(@"\\sample\sample1.dll"));
Assert.Throws<FileNotFoundException>(() => LoadReference(typeof(string).Assembly.Location + " " + typeof(string).Assembly.Location));
}
#region Submission result printing - null/void/value.
[Fact]
public void SubmissionResult_PrintingNull()
{
Execute(@"
string s;
s
");
var output = ReadOutputToEnd();
Assert.Equal("null\r\n", output);
}
[Fact]
public void SubmissionResult_PrintingVoid()
{
Execute(@"System.Console.WriteLine(2)");
var output = ReadOutputToEnd();
Assert.Equal("2\r\n<void>\r\n", output);
Execute(@"
void foo() { }
foo()
");
output = ReadOutputToEnd();
Assert.Equal("<void>\r\n", output);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Text;
using System.Xml;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace System.ServiceModel.Channels
{
internal class TextMessageEncoderFactory : MessageEncoderFactory
{
private TextMessageEncoder _messageEncoder;
internal static ContentEncoding[] Soap11Content = GetContentEncodingMap(MessageVersion.Soap11WSAddressing10);
internal static ContentEncoding[] Soap12Content = GetContentEncodingMap(MessageVersion.Soap12WSAddressing10);
internal static ContentEncoding[] SoapNoneContent = GetContentEncodingMap(MessageVersion.None);
internal const string Soap11MediaType = "text/xml";
internal const string Soap12MediaType = "application/soap+xml";
private const string XmlMediaType = "application/xml";
public TextMessageEncoderFactory(MessageVersion version, Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas)
{
_messageEncoder = new TextMessageEncoder(version, writeEncoding, maxReadPoolSize, maxWritePoolSize, quotas);
}
public override MessageEncoder Encoder
{
get { return _messageEncoder; }
}
public override MessageVersion MessageVersion
{
get { return _messageEncoder.MessageVersion; }
}
public int MaxWritePoolSize
{
get { return _messageEncoder.MaxWritePoolSize; }
}
public int MaxReadPoolSize
{
get { return _messageEncoder.MaxReadPoolSize; }
}
public static Encoding[] GetSupportedEncodings()
{
Encoding[] supported = TextEncoderDefaults.SupportedEncodings;
Encoding[] enc = new Encoding[supported.Length];
Array.Copy(supported, enc, supported.Length);
return enc;
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _messageEncoder.ReaderQuotas;
}
}
internal static string GetMediaType(MessageVersion version)
{
string mediaType = null;
if (version.Envelope == EnvelopeVersion.Soap12)
{
mediaType = TextMessageEncoderFactory.Soap12MediaType;
}
else if (version.Envelope == EnvelopeVersion.Soap11)
{
mediaType = TextMessageEncoderFactory.Soap11MediaType;
}
else if (version.Envelope == EnvelopeVersion.None)
{
mediaType = TextMessageEncoderFactory.XmlMediaType;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.EnvelopeVersionNotSupported, version.Envelope)));
}
return mediaType;
}
internal static string GetContentType(string mediaType, Encoding encoding)
{
return String.Format(CultureInfo.InvariantCulture, "{0}; charset={1}", mediaType, TextEncoderDefaults.EncodingToCharSet(encoding));
}
private static ContentEncoding[] GetContentEncodingMap(MessageVersion version)
{
Encoding[] readEncodings = TextMessageEncoderFactory.GetSupportedEncodings();
string media = GetMediaType(version);
ContentEncoding[] map = new ContentEncoding[readEncodings.Length];
for (int i = 0; i < readEncodings.Length; i++)
{
ContentEncoding contentEncoding = new ContentEncoding();
contentEncoding.contentType = GetContentType(media, readEncodings[i]);
contentEncoding.encoding = readEncodings[i];
map[i] = contentEncoding;
}
return map;
}
internal static Encoding GetEncodingFromContentType(string contentType, ContentEncoding[] contentMap)
{
if (contentType == null)
{
return null;
}
// Check for known/expected content types
for (int i = 0; i < contentMap.Length; i++)
{
if (contentMap[i].contentType == contentType)
{
return contentMap[i].encoding;
}
}
// then some heuristic matches (since System.Mime.ContentType is a performance hit)
// start by looking for a parameter.
// If none exists, we don't have an encoding
int semiColonIndex = contentType.IndexOf(';');
if (semiColonIndex == -1)
{
return null;
}
// optimize for charset being the first parameter
int charsetValueIndex = -1;
// for Indigo scenarios, we'll have "; charset=", so check for the c
if ((contentType.Length > semiColonIndex + 11) // need room for parameter + charset + '='
&& contentType[semiColonIndex + 2] == 'c'
&& string.Compare("charset=", 0, contentType, semiColonIndex + 2, 8, StringComparison.OrdinalIgnoreCase) == 0)
{
charsetValueIndex = semiColonIndex + 10;
}
else
{
// look for charset= somewhere else in the message
int paramIndex = contentType.IndexOf("charset=", semiColonIndex + 1, StringComparison.OrdinalIgnoreCase);
if (paramIndex != -1)
{
// validate there's only whitespace or semi-colons beforehand
for (int i = paramIndex - 1; i >= semiColonIndex; i--)
{
if (contentType[i] == ';')
{
charsetValueIndex = paramIndex + 8;
break;
}
if (contentType[i] == '\n')
{
if (i == semiColonIndex || contentType[i - 1] != '\r')
{
break;
}
i--;
continue;
}
if (contentType[i] != ' '
&& contentType[i] != '\t')
{
break;
}
}
}
}
string charSet;
Encoding enc;
// we have a possible charset value. If it's easy to parse, do so
if (charsetValueIndex != -1)
{
// get the next semicolon
semiColonIndex = contentType.IndexOf(';', charsetValueIndex);
if (semiColonIndex == -1)
{
charSet = contentType.Substring(charsetValueIndex);
}
else
{
charSet = contentType.Substring(charsetValueIndex, semiColonIndex - charsetValueIndex);
}
// and some minimal quote stripping
if (charSet.Length > 2 && charSet[0] == '"' && charSet[charSet.Length - 1] == '"')
{
charSet = charSet.Substring(1, charSet.Length - 2);
}
if (TryGetEncodingFromCharSet(charSet, out enc))
{
return enc;
}
}
// our quick heuristics failed. fall back to System.Net
try
{
MediaTypeHeaderValue parsedContentType = MediaTypeHeaderValue.Parse(contentType);
charSet = parsedContentType.CharSet;
}
catch (FormatException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.EncoderBadContentType, e));
}
if (TryGetEncodingFromCharSet(charSet, out enc))
return enc;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.EncoderUnrecognizedCharSet, charSet)));
}
internal static bool TryGetEncodingFromCharSet(string charSet, out Encoding encoding)
{
encoding = null;
if (charSet == null || charSet.Length == 0)
return true;
return TextEncoderDefaults.TryGetEncoding(charSet, out encoding);
}
internal class ContentEncoding
{
internal string contentType;
internal Encoding encoding;
}
internal class TextMessageEncoder : MessageEncoder
{
private int _maxReadPoolSize;
private int _maxWritePoolSize;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile SynchronizedPool<UTF8BufferedMessageData> _bufferedReaderPool;
private volatile SynchronizedPool<TextBufferedMessageWriter> _bufferedWriterPool;
private volatile SynchronizedPool<RecycledMessageState> _recycledStatePool;
private object _thisLock;
private string _contentType;
private string _mediaType;
private Encoding _writeEncoding;
private MessageVersion _version;
private bool _optimizeWriteForUTF8;
private const int maxPooledXmlReadersPerMessage = 2;
private XmlDictionaryReaderQuotas _readerQuotas;
private XmlDictionaryReaderQuotas _bufferedReadReaderQuotas;
private ContentEncoding[] _contentEncodingMap;
public TextMessageEncoder(MessageVersion version, Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
if (writeEncoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding");
TextEncoderDefaults.ValidateEncoding(writeEncoding);
_writeEncoding = writeEncoding;
_optimizeWriteForUTF8 = IsUTF8Encoding(writeEncoding);
_thisLock = new object();
_version = version;
_maxReadPoolSize = maxReadPoolSize;
_maxWritePoolSize = maxWritePoolSize;
_readerQuotas = new XmlDictionaryReaderQuotas();
quotas.CopyTo(_readerQuotas);
_bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(_readerQuotas);
_mediaType = TextMessageEncoderFactory.GetMediaType(version);
_contentType = TextMessageEncoderFactory.GetContentType(_mediaType, writeEncoding);
if (version.Envelope == EnvelopeVersion.Soap12)
{
_contentEncodingMap = TextMessageEncoderFactory.Soap12Content;
}
else if (version.Envelope == EnvelopeVersion.Soap11)
{
// public profile does not allow SOAP1.1/WSA1.0. However, the EnvelopeVersion 1.1 is supported. Need to know what the implications are here
// but I think that it's not necessary to have here since we're a sender in N only.
_contentEncodingMap = TextMessageEncoderFactory.Soap11Content;
}
else if (version.Envelope == EnvelopeVersion.None)
{
_contentEncodingMap = TextMessageEncoderFactory.SoapNoneContent;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.EnvelopeVersionNotSupported, version.Envelope)));
}
}
private static bool IsUTF8Encoding(Encoding encoding)
{
return encoding.WebName == "utf-8";
}
public override string ContentType
{
get { return _contentType; }
}
public int MaxWritePoolSize
{
get { return _maxWritePoolSize; }
}
public int MaxReadPoolSize
{
get { return _maxReadPoolSize; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _readerQuotas;
}
}
public override string MediaType
{
get { return _mediaType; }
}
public override MessageVersion MessageVersion
{
get { return _version; }
}
private object ThisLock
{
get { return _thisLock; }
}
internal override bool IsCharSetSupported(string charSet)
{
Encoding tmp;
return TextEncoderDefaults.TryGetEncoding(charSet, out tmp);
}
public override bool IsContentTypeSupported(string contentType)
{
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
if (base.IsContentTypeSupported(contentType))
{
return true;
}
// we support a few extra content types for "none"
if (MessageVersion == MessageVersion.None)
{
const string rss1MediaType = "text/xml";
const string rss2MediaType = "application/rss+xml";
const string atomMediaType = "application/atom+xml";
const string htmlMediaType = "text/html";
if (IsContentTypeSupported(contentType, rss1MediaType, rss1MediaType))
{
return true;
}
if (IsContentTypeSupported(contentType, rss2MediaType, rss2MediaType))
{
return true;
}
if (IsContentTypeSupported(contentType, htmlMediaType, atomMediaType))
{
return true;
}
if (IsContentTypeSupported(contentType, atomMediaType, atomMediaType))
{
return true;
}
// application/xml checked by base method
}
return false;
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (bufferManager == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bufferManager"));
if (TD.TextMessageDecodingStartIsEnabled())
{
TD.TextMessageDecodingStart();
}
Message message;
UTF8BufferedMessageData messageData = TakeBufferedReader();
messageData.Encoding = GetEncodingFromContentType(contentType, _contentEncodingMap);
messageData.Open(buffer, bufferManager);
RecycledMessageState messageState = messageData.TakeMessageState();
if (messageState == null)
messageState = new RecycledMessageState();
message = new BufferedMessage(messageData, messageState);
message.Properties.Encoder = this;
if (TD.MessageReadByEncoderIsEnabled())
{
TD.MessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true),
buffer.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
return message;
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
if (stream == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
if (TD.TextMessageDecodingStartIsEnabled())
{
TD.TextMessageDecodingStart();
}
XmlReader reader = TakeStreamedReader(stream, GetEncodingFromContentType(contentType, _contentEncodingMap));
Message message = Message.CreateMessage(reader, maxSizeOfHeaders, _version);
message.Properties.Encoder = this;
if (TD.StreamedMessageReadByEncoderIsEnabled())
{
TD.StreamedMessageReadByEncoder(EventTraceActivityHelper.TryExtractActivity(message, true));
}
if (MessageLogger.LogMessagesAtTransportLevel)
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
return message;
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
return WriteMessageAsync(message, maxMessageSize, bufferManager, messageOffset).WaitForCompletion();
}
public override void WriteMessage(Message message, Stream stream)
{
WriteMessageAsyncInternal(message, stream).WaitForCompletion();
}
public override Task<ArraySegment<byte>> WriteMessageAsync(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (bufferManager == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("bufferManager"), message);
if (maxMessageSize < 0)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
SR.ValueMustBeNonNegative), message);
if (messageOffset < 0 || messageOffset > maxMessageSize)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
SR.Format(SR.ValueMustBeInRange, 0, maxMessageSize)), message);
ThrowIfMismatchedMessageVersion(message);
EventTraceActivity eventTraceActivity = null;
if (TD.TextMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.TextMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
TextBufferedMessageWriter messageWriter = TakeBufferedWriter();
ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize);
ReturnMessageWriter(messageWriter);
if (TD.MessageWrittenByEncoderIsEnabled())
{
TD.MessageWrittenByEncoder(
eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message),
messageData.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(messageData.Array, messageData.Offset, messageData.Count, XmlDictionaryReaderQuotas.Max);
MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend);
}
return Task.FromResult(messageData);
}
private async Task WriteMessageAsyncInternal(Message message, Stream stream)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
await WriteMessageAsync(message, stream);
}
public override async Task WriteMessageAsync(Message message, Stream stream)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (stream == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message);
ThrowIfMismatchedMessageVersion(message);
EventTraceActivity eventTraceActivity = null;
if (TD.TextMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.TextMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
XmlDictionaryWriter xmlWriter = TakeStreamedWriter(stream);
if (_optimizeWriteForUTF8)
{
await message.WriteMessageAsync(xmlWriter);
}
else
{
xmlWriter.WriteStartDocument();
await message.WriteMessageAsync(xmlWriter);
xmlWriter.WriteEndDocument();
}
// The underlying type of xmlWriter, XmlUTF8TextWriter, has not implemented FlushAsync() yet.
xmlWriter.Flush();
ReturnStreamedWriter(xmlWriter);
if (TD.StreamedMessageWrittenByEncoderIsEnabled())
{
TD.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message));
}
if (MessageLogger.LogMessagesAtTransportLevel)
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
}
public override IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state)
{
return this.WriteMessageAsync(message, stream).ToApm(callback, state);
}
public override void EndWriteMessage(IAsyncResult result)
{
result.ToApmEnd();
}
private XmlDictionaryWriter TakeStreamedWriter(Stream stream)
{
return XmlDictionaryWriter.CreateTextWriter(stream, _writeEncoding, false);
}
private void ReturnStreamedWriter(XmlWriter xmlWriter)
{
Contract.Assert(xmlWriter != null, "xmlWriter MUST NOT be null");
xmlWriter.Flush();
xmlWriter.Dispose();
}
private TextBufferedMessageWriter TakeBufferedWriter()
{
if (_bufferedWriterPool == null)
{
lock (ThisLock)
{
if (_bufferedWriterPool == null)
{
_bufferedWriterPool = new SynchronizedPool<TextBufferedMessageWriter>(_maxWritePoolSize);
}
}
}
TextBufferedMessageWriter messageWriter = _bufferedWriterPool.Take();
if (messageWriter == null)
{
messageWriter = new TextBufferedMessageWriter(this);
if (TD.WritePoolMissIsEnabled())
{
TD.WritePoolMiss(messageWriter.GetType().Name);
}
}
return messageWriter;
}
private void ReturnMessageWriter(TextBufferedMessageWriter messageWriter)
{
_bufferedWriterPool.Return(messageWriter);
}
private XmlReader TakeStreamedReader(Stream stream, Encoding enc)
{
return XmlDictionaryReader.CreateTextReader(stream, _readerQuotas);
}
private XmlDictionaryWriter CreateWriter(Stream stream)
{
return XmlDictionaryWriter.CreateTextWriter(stream, _writeEncoding, false);
}
private UTF8BufferedMessageData TakeBufferedReader()
{
if (_bufferedReaderPool == null)
{
lock (ThisLock)
{
if (_bufferedReaderPool == null)
{
_bufferedReaderPool = new SynchronizedPool<UTF8BufferedMessageData>(_maxReadPoolSize);
}
}
}
UTF8BufferedMessageData messageData = _bufferedReaderPool.Take();
if (messageData == null)
{
messageData = new UTF8BufferedMessageData(this, maxPooledXmlReadersPerMessage);
if (TD.ReadPoolMissIsEnabled())
{
TD.ReadPoolMiss(messageData.GetType().Name);
}
}
return messageData;
}
private void ReturnBufferedData(UTF8BufferedMessageData messageData)
{
_bufferedReaderPool.Return(messageData);
}
private SynchronizedPool<RecycledMessageState> RecycledStatePool
{
get
{
if (_recycledStatePool == null)
{
lock (ThisLock)
{
if (_recycledStatePool == null)
{
_recycledStatePool = new SynchronizedPool<RecycledMessageState>(_maxReadPoolSize);
}
}
}
return _recycledStatePool;
}
}
private static readonly byte[] s_xmlDeclarationStartText = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l' };
private static readonly byte[] s_version10Text = { (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"' };
private static readonly byte[] s_encodingText = { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=' };
internal class UTF8BufferedMessageData : BufferedMessageData
{
private TextMessageEncoder _messageEncoder;
private Encoding _encoding;
private const int additionalNodeSpace = 1024;
public UTF8BufferedMessageData(TextMessageEncoder messageEncoder, int maxReaderPoolSize)
: base(messageEncoder.RecycledStatePool)
{
_messageEncoder = messageEncoder;
}
internal Encoding Encoding
{
set
{
_encoding = value;
}
}
public override MessageEncoder MessageEncoder
{
get { return _messageEncoder; }
}
public override XmlDictionaryReaderQuotas Quotas
{
get { return _messageEncoder._bufferedReadReaderQuotas; }
}
protected override void OnClosed()
{
_messageEncoder.ReturnBufferedData(this);
}
protected override XmlDictionaryReader TakeXmlReader()
{
ArraySegment<byte> buffer = this.Buffer;
return XmlDictionaryReader.CreateTextReader(buffer.Array, buffer.Offset, buffer.Count, this.Quotas);
}
protected override void ReturnXmlReader(XmlDictionaryReader xmlReader)
{
Contract.Assert(xmlReader != null, "xmlReader MUST NOT be null");
xmlReader.Dispose();
}
}
internal class TextBufferedMessageWriter : BufferedMessageWriter
{
private TextMessageEncoder _messageEncoder;
public TextBufferedMessageWriter(TextMessageEncoder messageEncoder)
{
_messageEncoder = messageEncoder;
}
protected override void OnWriteStartMessage(XmlDictionaryWriter writer)
{
if (!_messageEncoder._optimizeWriteForUTF8)
writer.WriteStartDocument();
}
protected override void OnWriteEndMessage(XmlDictionaryWriter writer)
{
if (!_messageEncoder._optimizeWriteForUTF8)
writer.WriteEndDocument();
}
protected override XmlDictionaryWriter TakeXmlWriter(Stream stream)
{
if (_messageEncoder._optimizeWriteForUTF8)
{
return XmlDictionaryWriter.CreateTextWriter(stream, _messageEncoder._writeEncoding, false);
}
else
{
return _messageEncoder.CreateWriter(stream);
}
}
protected override void ReturnXmlWriter(XmlDictionaryWriter writer)
{
Contract.Assert(writer != null, "writer MUST NOT be null");
writer.Flush();
writer.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 Microsoft.Build.Framework;
using System.Collections.Generic;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
namespace Microsoft.Build.UnitTests
{
/// <summary>
/// A class containing an extension to BuildEventArgs
/// </summary>
internal static class BuildEventArgsExtension
{
/// <summary>
/// Extension method to help our tests without adding shipping code.
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="args">The 'this' object</param>
/// <param name="other">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(this BuildEventArgs args, BuildEventArgs other)
{
if (Object.ReferenceEquals(args, other))
{
return true;
}
if (other is null || args is null)
{
return false;
}
if (args.GetType() != other.GetType())
{
return false;
}
if (args.Timestamp.Ticks != other.Timestamp.Ticks)
{
return false;
}
if (args.BuildEventContext != other.BuildEventContext)
{
return false;
}
if (!String.Equals(args.HelpKeyword, other.HelpKeyword, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.IsNullOrEmpty(args.Message))
{
// Just in case we're matching chk against ret or vice versa, make sure the message still registers as the same
string fixedArgsMessage = args.Message.Replace("\r\nThis is an unhandled exception from a task -- PLEASE OPEN A BUG AGAINST THE TASK OWNER.", String.Empty);
string fixedOtherMessage = other.Message.Replace("\r\nThis is an unhandled exception from a task -- PLEASE OPEN A BUG AGAINST THE TASK OWNER.", String.Empty);
if (!String.Equals(fixedArgsMessage, fixedOtherMessage, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
if (!String.Equals(args.SenderName, other.SenderName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (args.ThreadId != other.ThreadId)
{
return false;
}
return true;
}
/// <summary>
/// Extension method to help our tests without adding shipping code.
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="args">The 'this' object</param>
/// <param name="other">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(this BuildFinishedEventArgs args, BuildFinishedEventArgs other)
{
if (args.Succeeded != other.Succeeded)
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compares the value fields in the class to the passed in object and check to see if they are the same.
/// </summary>
/// <param name="obj">Object to compare to this instance</param>
/// <returns>True if the value fields are identical, false if otherwise</returns>
public static bool IsEquivalent(this BuildMessageEventArgs args, BuildMessageEventArgs other)
{
if (args.Importance != other.Importance)
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(this BuildErrorEventArgs args, BuildErrorEventArgs other)
{
if (args.ColumnNumber != other.ColumnNumber)
{
return false;
}
if (args.EndColumnNumber != other.EndColumnNumber)
{
return false;
}
if (args.LineNumber != other.LineNumber)
{
return false;
}
if (args.EndLineNumber != other.EndLineNumber)
{
return false;
}
if (!String.Equals(args.File, other.File, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.Code, other.Code, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.Subcategory, other.Subcategory, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(this BuildWarningEventArgs args, BuildWarningEventArgs other)
{
if (args.ColumnNumber != other.ColumnNumber)
{
return false;
}
if (args.EndColumnNumber != other.EndColumnNumber)
{
return false;
}
if (args.LineNumber != other.LineNumber)
{
return false;
}
if (args.EndLineNumber != other.EndLineNumber)
{
return false;
}
if (!String.Equals(args.File, other.File, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.Code, other.Code, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.Subcategory, other.Subcategory, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(ProjectStartedEventArgs args, ProjectStartedEventArgs other)
{
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TargetNames, other.TargetNames, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(ExternalProjectStartedEventArgs args, ExternalProjectStartedEventArgs other)
{
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TargetNames, other.TargetNames, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(ProjectFinishedEventArgs args, ProjectFinishedEventArgs other)
{
if (args.Succeeded != other.Succeeded)
{
return false;
}
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(ExternalProjectFinishedEventArgs args, ExternalProjectFinishedEventArgs other)
{
if (args.Succeeded != other.Succeeded)
{
return false;
}
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(TargetStartedEventArgs args, TargetStartedEventArgs other)
{
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TargetFile, other.TargetFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TargetName, other.TargetName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.ParentTarget, other.ParentTarget, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(TargetFinishedEventArgs args, TargetFinishedEventArgs other)
{
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TargetFile, other.TargetFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TargetName, other.TargetName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!Object.ReferenceEquals(args.TargetOutputs, other.TargetOutputs))
{
// See if one is null, if so they are not equal
if (args.TargetOutputs == null || other.TargetOutputs == null)
{
return false;
}
List<string> argItemIncludes = new List<string>();
foreach (TaskItem item in args.TargetOutputs)
{
argItemIncludes.Add(item.ToString());
}
List<string> otherItemIncludes = new List<string>();
foreach (TaskItem item in other.TargetOutputs)
{
otherItemIncludes.Add(item.ToString());
}
argItemIncludes.Sort();
otherItemIncludes.Sort();
if (argItemIncludes.Count != otherItemIncludes.Count)
{
return false;
}
// Since the lists are sorted each include must match
for (int i = 0; i < argItemIncludes.Count; i++)
{
if (!argItemIncludes[i].Equals(otherItemIncludes[i], StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(TaskStartedEventArgs args, TaskStartedEventArgs other)
{
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TaskFile, other.TaskFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TaskName, other.TaskName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
/// <summary>
/// Compare this build event context with another object to determine
/// equality. This means the values inside the object are identical.
/// </summary>
/// <param name="obj">Object to compare to this object</param>
/// <returns>True if the object values are identical, false if they are not identical</returns>
public static bool IsEquivalent(TaskFinishedEventArgs args, TaskFinishedEventArgs other)
{
if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TaskFile, other.TaskFile, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!String.Equals(args.TaskName, other.TaskName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (args.Succeeded != other.Succeeded)
{
return false;
}
return ((BuildEventArgs)args).IsEquivalent(other);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System.Numerics;
using Windows.Devices.Haptics;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
// This sample shows how to use Inking and Interaction tactile signals in
// conjunction with each other.
// Namely, this sample plays the InkContinuous waveform when dragging a movable
// rectangle and then plays the Click waveform when the rectangle is in range
// of a snap gridline and, finally, if the movable rectangle snaps to a gridline
// upon release, it plays the Click waveform one more time.
namespace SDKTemplate
{
public sealed partial class Scenario5_InkingAndInteractionFeedback : Page
{
private readonly int gridSize = 100;
readonly double snapDistance = 20;
private Point topLeft;
private Point previewTopLeft = new Point(-1, -1);
private TransformGroup transforms;
private MatrixTransform previousTransform;
private CompositeTransform deltaTransform;
PenDevice penDevice;
SimpleHapticsController hapticsController;
// Set the initial configuration of the canvas and the rectangles
public Scenario5_InkingAndInteractionFeedback()
{
InitializeComponent();
InitializeGridLines();
InitializeManipulationTransforms();
}
// Draw gridlines based on the gridSize
private void InitializeGridLines()
{
SolidColorBrush darkGray = new SolidColorBrush(Colors.DarkGray);
double width = hapticCanvas.Width;
double height = hapticCanvas.Height;
for (int i = 0; i <= width; i += gridSize)
{
Line currLine = new Line() {
Stroke = darkGray,
X1 = i,
X2 = i,
Y1 = 0,
Y2 = height,
};
hapticCanvas.Children.Add(currLine);
}
for (int i = 0; i <= height; i += gridSize)
{
Line currLine = new Line() {
Stroke = darkGray,
X1 = 0,
X2 = width,
Y1 = i,
Y2 = i,
};
hapticCanvas.Children.Add(currLine);
}
}
// Configure the Manipulation transforms that are used to drag the rectangle around
private void InitializeManipulationTransforms()
{
previousTransform = new MatrixTransform() { Matrix = Matrix.Identity };
topLeft = new Point(75, 75);
deltaTransform = new CompositeTransform() { TranslateX = topLeft.X, TranslateY = topLeft.Y };
transforms = new TransformGroup() { Children = { previousTransform, deltaTransform } };
// Set the render transform on the rect
movableRect.RenderTransform = transforms;
}
// The PointerEnter event will get fired as soon as Pointer input is received in the movableRect.
// This event handler implementation will query the device providing input to see if it's a pen and
// then check to see the pen supports tactile feedback and, if so, configure the PenDevice
// to send the InkContinuous tactile signal.
private void MovableRect_Entered(object sender, PointerRoutedEventArgs e)
{
// If the current Pointer device is not a pen, exit
if (e.Pointer.PointerDeviceType != PointerDeviceType.Pen)
{
return;
}
// Attempt to retrieve the PenDevice from the current PointerId
penDevice = PenDevice.GetFromPointerId(e.Pointer.PointerId);
// If a PenDevice cannot be retrieved based on the PointerId, it does not support
// advanced pen features, such as tactile feedback
if (penDevice == null)
{
statusText.Text = "Advanced pen features not supported";
return;
}
// Check to see if the current PenDevice supports tactile feedback by seeing if it
// has a SimpleHapticsController
hapticsController = penDevice.SimpleHapticsController;
if (hapticsController == null)
{
statusText.Text = "This pen does not provide tactile feedback";
return;
}
// Send the InkContinuous waveform to the PenDevice's SimpleHapticsController.
// Once sent, inking continuous tactile feedback will be triggered as soon as the pen tip touches
// the screen and will be stopped once the pen tip is lifted from the screen.
// Also, check to see if the current PenDevice's SimpleHapticsController supports
// setting the intensity value of the tactile feedback. If so, set it to 0.75.
// If not, send the waveform with the default intensity.
foreach (var waveform in hapticsController.SupportedFeedback)
{
if (waveform.Waveform == KnownSimpleHapticsControllerWaveforms.InkContinuous)
{
if (hapticsController.IsIntensitySupported)
{
hapticsController.SendHapticFeedback(waveform, 0.75);
}
else
{
hapticsController.SendHapticFeedback(waveform);
}
}
}
}
// Stop sending the tactile feedback and clear the current penDevice and hapticsController on PointerExit.
// Stopping the feedback is important as it clears the tactile signal from the PenDevice's
// SimpleHapticsController, ensuring that it has a clean state once it next enters range.
private void MovableRect_Exited(object sender, PointerRoutedEventArgs e)
{
penDevice = null;
statusText.Text = "";
if (hapticsController != null)
{
hapticsController.StopFeedback();
hapticsController = null;
}
}
// Change the color of the movableRect once a manipulation is started. This coincides with the pen
// touching down inside the rectangle, so this color change will happen at the same time that the
// InkContinuous waveform begins playing.
private void MovableRect_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
movableRect.Style = MovableRectangleDragged;
}
// Update the position of the movableRect and update the previewRect as needed
private void MovableRect_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
previousTransform.Matrix = transforms.Value;
// Look at the Delta property of the ManipulationDeltaRoutedEventArgs to retrieve the X and Y changes
deltaTransform.TranslateX = e.Delta.Translation.X;
deltaTransform.TranslateY = e.Delta.Translation.Y;
topLeft.X += e.Delta.Translation.X;
topLeft.Y += e.Delta.Translation.Y;
UpdatePreviewRect();
}
// Update the visibilty or position of the previewRect based on the location
// of the movableRect.
// If the previewRect is snapped to a given gridline for the first time,
// play the Click tactile signal.
private void UpdatePreviewRect()
{
if (IsInSnapRange())
{
previewRect.Visibility = Visibility.Visible;
Point newPreviewTopLeft = GetSnappedPoint();
// Check to see if this is the first time that the previewRect is in range of a given gridline
// and send the Click tactile signal if so
bool sendHaptics = true;
if ((previewTopLeft.X == newPreviewTopLeft.X && previewTopLeft.Y == newPreviewTopLeft.Y) ||
(previewTopLeft.X == newPreviewTopLeft.X && newPreviewTopLeft.Y == topLeft.Y) ||
(previewTopLeft.Y == newPreviewTopLeft.Y && newPreviewTopLeft.X == topLeft.X))
{
sendHaptics = false;
}
if (previewTopLeft.X != newPreviewTopLeft.X || previewTopLeft.Y != newPreviewTopLeft.Y)
{
previewTopLeft = newPreviewTopLeft;
previewRect.Translation = new Vector3((float)previewTopLeft.X, (float)previewTopLeft.Y, 0);
if (hapticsController != null && sendHaptics)
{
foreach (var waveform in hapticsController.SupportedFeedback)
{
if (waveform.Waveform == KnownSimpleHapticsControllerWaveforms.Click)
{
hapticsController.SendHapticFeedback(waveform);
}
}
}
}
}
else
{
previewRect.Visibility = Visibility.Collapsed;
previewTopLeft = new Point(-1, -1);
}
}
// When the manipulation is over, reset the color of the movableRect and
// snap it to a gridline if appropriate
private void MovableRect_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
movableRect.Style = MovableRectangle;
if (IsInSnapRange())
{
SnapMovableRectToGridLines();
}
}
// Updates the position of the movableRect to snap to the appropriate gridline(s).
// In addition, play the Click tactile signal to provide additional feedback to the user that it has snapped.
private void SnapMovableRectToGridLines()
{
topLeft = GetSnappedPoint();
previousTransform = new MatrixTransform() { Matrix = Matrix.Identity };
deltaTransform.TranslateX = topLeft.X;
deltaTransform.TranslateY = topLeft.Y;
transforms = new TransformGroup() { Children = { previousTransform, deltaTransform } };
movableRect.RenderTransform = transforms;
if (hapticsController != null)
{
foreach (var waveform in hapticsController.SupportedFeedback)
{
if (waveform.Waveform == KnownSimpleHapticsControllerWaveforms.Click)
{
hapticsController.SendHapticFeedback(waveform);
}
}
}
}
// Retrieve the point corresponding to the top-left corner of where the movableRect would snap to
// if released.
private Point GetSnappedPoint()
{
Point snappedPoint;
if (topLeft.X % gridSize <= snapDistance)
{
snappedPoint.X = topLeft.X + topLeft.X % gridSize * -1;
}
else if (topLeft.X % gridSize >= gridSize - snapDistance)
{
snappedPoint.X = topLeft.X + gridSize - (topLeft.X % gridSize);
}
else
{
snappedPoint.X = topLeft.X;
}
if (topLeft.Y % gridSize <= snapDistance)
{
snappedPoint.Y = topLeft.Y + topLeft.Y % gridSize * -1;
}
else if (topLeft.Y % gridSize >= gridSize - snapDistance)
{
snappedPoint.Y = topLeft.Y + gridSize - (topLeft.Y % gridSize);
}
else
{
snappedPoint.Y = topLeft.Y;
}
return snappedPoint;
}
// Check to see if the movableRect is currently within snapping range of a gridline
private bool IsInSnapRange()
{
return topLeft.X % gridSize <= snapDistance ||
topLeft.X % gridSize >= gridSize - snapDistance ||
topLeft.Y % gridSize <= snapDistance ||
topLeft.Y % gridSize >= gridSize - snapDistance;
}
}
}
| |
//
// Copyright (C) 2009 Jordi Mas i Hernandez, [email protected]
//
// 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.IO;
using Gtk;
using Gdk;
using System.Collections.Generic;
using System.ComponentModel;
using Mono.Unix;
using Mistelix.Widgets;
using Mistelix.DataModel;
using Mistelix.Core;
namespace Mistelix.Widgets
{
class WelcomeView : Gtk.HBox
{
// Used to report when a file has been open from the recent file list
public delegate void ProjectOpenEventHandler (object sender, ProjectOpenEventHandlerEventArgs e);
public class ProjectOpenEventHandlerEventArgs: EventArgs
{
string project;
public ProjectOpenEventHandlerEventArgs (string project)
{
this.project = project;
}
public string Project {
get { return project; }
}
}
// Contains the list of recent projects
class RecentProjectsTreeView : TreeView
{
ListStore tree_store;
WelcomeView view;
BackgroundWorker thumbnailing;
bool empty;
public RecentProjectsTreeView (WelcomeView view)
{
this.view = view;
Model = tree_store = CreateStore ();
RulesHint = true;
AppendColumn (Catalog.GetString ("Project"), new CellRendererText (), "text", COL_NAME);
AppendColumn (Catalog.GetString ("Last Accessed"), new CellRendererText (), "text", COL_DATE);
AppendColumn (Catalog.GetString ("Thumbnail"), new CellRendererPixbuf (), "pixbuf", COL_PIXBUF);
RowActivated += OnRowActivate;
tree_store.SetSortFunc (0, new Gtk.TreeIterCompareFunc (SortByTime));
thumbnailing = new BackgroundWorker ();
thumbnailing.DoWork += new DoWorkEventHandler (DoWork);
PopulateRecentFiles ();
}
ListStore CreateStore ()
{
// Image filename, date, Image, full filename, thumbnail_done
return new ListStore (typeof (string), typeof (string), typeof (Gdk.Pixbuf) , typeof (RecentFile), typeof (bool));
}
void OnRowActivate (object o, RowActivatedArgs args)
{
if (view.ProjectOpen == null)
return;
TreeIter iter;
tree_store.GetIter (out iter, args.Path);
RecentFile recent;
if (tree_store.GetValue (iter, COL_OBJECT) == null)
return;
recent = (RecentFile) tree_store.GetValue (iter, COL_OBJECT);
view.ProjectOpen (this, new ProjectOpenEventHandlerEventArgs (recent.filename));
}
public void PopulateRecentFiles ()
{
tree_store.Clear ();
if (view.recent_files.Items.Count == 0)
{
tree_store.AppendValues (Catalog.GetString ("No recent projects"), "", null, null);
empty = true;
return;
}
empty = false;
foreach (RecentFile recent in view.recent_files.Items)
{
FileInfo fi = new FileInfo (recent.filename);
tree_store.AppendValues (fi.Name, recent.TimeSinceEdited, null, recent, false);
}
tree_store.SetSortColumnId (0, SortType.Descending);
if (thumbnailing.IsBusy == false)
thumbnailing.RunWorkerAsync (tree_store);
}
public void AddRecentFile (RecentFile recent)
{
if (empty == true) {
empty = false;
tree_store.Clear ();
}
FileInfo fi = new FileInfo (recent.filename);
tree_store.AppendValues (fi.Name, recent.TimeSinceEdited, null, recent, false);
tree_store.SetSortColumnId (0, SortType.Descending);
if (thumbnailing.IsBusy == false)
thumbnailing.RunWorkerAsync (tree_store);
}
public void UpdateRecentFile (RecentFile item)
{
tree_store.Foreach (delegate (TreeModel model, TreePath path, TreeIter iter)
{
RecentFile recent = (RecentFile) tree_store.GetValue (iter, COL_OBJECT);
if (recent.filename == item.filename)
{
tree_store.SetValue (iter, COL_OBJECT, item);
tree_store.SetValue (iter, COL_DATE, item.TimeSinceEdited);
tree_store.SetValue (iter, COL_THUMBNAIL, false);
return true;
}
return false;
});
tree_store.SetSortColumnId (0, SortType.Descending);
if (thumbnailing.IsBusy == false)
thumbnailing.RunWorkerAsync (tree_store);
}
public void RemoveRecentFile (RecentFile item)
{
tree_store.Foreach (delegate (TreeModel model, TreePath path, TreeIter iter)
{
RecentFile recent = (RecentFile) tree_store.GetValue (iter, COL_OBJECT);
if (recent.filename == item.filename)
{
tree_store.Remove (ref iter);
return true;
}
return false;
});
}
int SortByTime (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b)
{
RecentFile recent_a, recent_b;
if (model.GetValue (a, COL_OBJECT) == null || model.GetValue (b, COL_OBJECT) == null)
return 0;
recent_a = (RecentFile) model.GetValue (a, COL_OBJECT);
recent_b = (RecentFile) model.GetValue (b, COL_OBJECT);
return DateTime.Compare (recent_a.timestamp, recent_b.timestamp);
}
static void DoWork (object sender, DoWorkEventArgs e)
{
ListStore store = (ListStore) e.Argument;
Logger.Debug ("WelcomeView.DoWork. Start");
store.Foreach (delegate (TreeModel model, TreePath path, TreeIter iter)
{
RecentFile recent;
Gdk.Pixbuf im;
Project project;
if (store.GetValue (iter, COL_OBJECT) == null)
return false;
if (((bool) store.GetValue (iter, COL_THUMBNAIL)) == true)
return false;
recent = (RecentFile) store.GetValue (iter, COL_OBJECT);
try {
project = new Project ();
project.Load (recent.filename);
im = project.GetThumbnail (ThumbnailSizeManager.Current.Width,
ThumbnailSizeManager.Current.Height);
Logger.Debug ("WelcomeView.DoWork. Thumbnailed {0}", recent.filename);
}
catch (Exception ex) {
Logger.Error ("WelcomeView.Dowork. Exception: " + ex.Message);
return false;
}
Application.Invoke (delegate {
if (im != null)
store.SetValue (iter, COL_PIXBUF, im);
store.SetValue (iter, COL_THUMBNAIL, true);
} );
return false;
});
Logger.Debug ("WelcomeView.DoWork. End");
}
}
Gtk.VBox action_vbox;
Gtk.Label welcome_label;
Gtk.Table action_table;
Gtk.Button dvd_button;
Gtk.Button slideshow_button;
Gtk.VBox dvd_vbox;
Gtk.Label recent_label;
RecentProjectsTreeView recent_treeview;
Gtk.Button buttonCancel;
Gtk.Button buttonOk;
RecentFilesStorage recent_files;
const int COL_NAME = 0;
const int COL_DATE = 1;
const int COL_PIXBUF = 2;
const int COL_OBJECT = 3;
const int COL_THUMBNAIL = 4;
const int BUTTON_SIZE = 80;
public ProjectOpenEventHandler ProjectOpen;
public EventHandler ButtonDVD;
public EventHandler ButtonSlideshow;
public WelcomeView (Gtk.VBox box, RecentFilesStorage recent_files)
{
string text;
this.recent_files = recent_files;
this.recent_files.ListUpdated += new ObservableList <RecentFile>.CollectionChangedEventHandler (OnListUpdated);
Homogeneous = true;
Spacing = 6;
BorderWidth = 20;
// action_vbox packs all the elements in the left column
action_vbox = new Gtk.VBox();
action_vbox.Spacing = 30;
// Welcome label
welcome_label = new Gtk.Label ();
text = Catalog.GetString ("<b>Welcome to Mistelix</b>");
text += "\n\n";
text += Catalog.GetString ("Mistelix is a DVD authoring application also\nwith Theora slideshow creation capabilities.");
welcome_label.Markup = text;
action_vbox.Add (welcome_label);
Gtk.Box.BoxChild w2 = ((Gtk.Box.BoxChild)(action_vbox[welcome_label]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Action table
action_table = new Gtk.Table (((uint)(2)), ((uint)(1)), false);
action_table.RowSpacing = ((uint)(50));
action_table.ColumnSpacing = ((uint)(1));
// DVD button
dvd_button = new Gtk.Button ();
dvd_button.CanFocus = true;
dvd_button.UseUnderline = true;
dvd_button.Clicked += new EventHandler (OnButtonDVD);
Gtk.Alignment w3 = new Gtk.Alignment(0.5F, 0.5F, 0F, 0F);
Gtk.HBox w4 = new Gtk.HBox ();
w4.Spacing = 2;
Gtk.Image w5 = new Gtk.Image();
Pixbuf pb = new Pixbuf (null, "button-dvd.svg");
w5.Pixbuf = pb.ScaleSimple (BUTTON_SIZE, BUTTON_SIZE, InterpType.Hyper);
w4.Add (w5);
Gtk.Label w7 = new Gtk.Label ();
text = Catalog.GetString ("Create a DVD project");
text += "\n\n";
text += Catalog.GetString ("Create a DVD with videos and slideshows\nthat can be played in DVD players.");
w7.LabelProp = text;
w7.UseUnderline = true;
w4.Add (w7);
w3.Add (w4);
dvd_button.Add (w3);
action_table.Add (dvd_button);
Gtk.Table.TableChild w11 = ((Gtk.Table.TableChild)(action_table[dvd_button]));
w11.TopAttach = ((uint)(1));
w11.BottomAttach = ((uint)(2));
w11.XOptions = ((Gtk.AttachOptions)(4));
w11.YOptions = ((Gtk.AttachOptions)(4));
// Slideshown button
slideshow_button = new Gtk.Button ();
slideshow_button.CanFocus = true;
slideshow_button.UseUnderline = true;
slideshow_button.Clicked += new EventHandler (OnButtonSlideshow);
Gtk.Alignment w12 = new Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
Gtk.HBox w13 = new Gtk.HBox ();
w13.Spacing = 2;
Gtk.Image w14 = new Gtk.Image ();
pb = new Pixbuf (null, "button-slideshow.svg");
w14.Pixbuf = pb.ScaleSimple (BUTTON_SIZE, BUTTON_SIZE, InterpType.Hyper);
w13.Add(w14);
// Container child GtkHBox.Gtk.Container+ContainerChild
Gtk.Label w16 = new Gtk.Label ();
text = Catalog.GetString ("Create a Slideshow");
text += "\n\n";
text += Catalog.GetString ("Slideshow from a collection of images\nthat can be played in a PC.");
w16.LabelProp = text;
w16.UseUnderline = true;
w13.Add (w16);
w12.Add (w13);
slideshow_button.Add (w12);
action_table.Add(slideshow_button);
Gtk.Table.TableChild w20 = ((Gtk.Table.TableChild)(action_table[slideshow_button]));
w20.XOptions = ((Gtk.AttachOptions)(4));
w20.YOptions = ((Gtk.AttachOptions)(4));
action_vbox.Add(action_table);
Gtk.Box.BoxChild w21 = ((Gtk.Box.BoxChild)(action_vbox[action_table]));
w21.Position = 1;
w21.Expand = false;
w21.Fill = false;
Add (action_vbox);
Gtk.Box.BoxChild w22 = (Gtk.Box.BoxChild) this[action_vbox];
w22.Position = 0;
w22.Expand = false;
w22.Fill = false;
// dvd_vbox packs all the elements in the left column
dvd_vbox = new Gtk.VBox ();
dvd_vbox.Spacing = 30;
// Container child dvd_vbox.Gtk.Box+BoxChild
recent_label = new Gtk.Label ();
recent_label.Markup = Mono.Unix.Catalog.GetString ("<b>Recent Projects</b>");
dvd_vbox.Add(recent_label);
Gtk.Box.BoxChild w23 = ((Gtk.Box.BoxChild)(dvd_vbox[recent_label]));
w23.Position = 0;
w23.Expand = false;
w23.Fill = false;
// Recent projects Treeview
Gtk.ScrolledWindow scrolled_win = new Gtk.ScrolledWindow ();
Gtk.VBox tree_vbox = new Gtk.VBox ();
recent_treeview = new RecentProjectsTreeView (this);
tree_vbox.Add (recent_treeview);
scrolled_win.AddWithViewport (tree_vbox);
dvd_vbox.Add (scrolled_win);
Add (dvd_vbox);
Gtk.Box.BoxChild treeview_child = ((Gtk.Box.BoxChild)(tree_vbox [recent_treeview]));
treeview_child.Position = 1;
treeview_child.Expand = false;
treeview_child.Fill = false;
Gtk.Box.BoxChild scrolled_child = ((Gtk.Box.BoxChild)(dvd_vbox [scrolled_win]));
scrolled_child.Position = 1;
scrolled_child.Expand = true;
scrolled_child.Fill = true;
Gtk.Box.BoxChild dvd_vbox_child = (Gtk.Box.BoxChild) this [dvd_vbox];
dvd_vbox_child.Position = 1;
dvd_vbox_child.Expand = false;
dvd_vbox_child.Fill = true;
box.Add(this);
}
void OnButtonDVD (object sender, EventArgs args)
{
if (ButtonDVD != null)
ButtonDVD (sender, args);
}
void OnButtonSlideshow (object sender, EventArgs args)
{
if (ButtonSlideshow != null)
ButtonSlideshow (sender, args);
}
void OnListUpdated (object sender, ObservableList <RecentFile>.CollectionChangedEventArgs e)
{
Logger.Debug ("WelcomeView.OnListUpdated. type:{0} item:s{1}", e.Type, e.Item);
switch (e.Type) {
case ObservableList<RecentFile>.ChangeType.ElementChanged:
recent_treeview.UpdateRecentFile (e.Item);
break;
case ObservableList<RecentFile>.ChangeType.ElementAdded:
recent_treeview.AddRecentFile (e.Item);
break;
case ObservableList<RecentFile>.ChangeType.ElementRemoved:
recent_treeview.RemoveRecentFile (e.Item);
break;
case ObservableList<RecentFile>.ChangeType.ListCleared:
recent_treeview.PopulateRecentFiles ();
break;
default:
break;
}
}
}
}
| |
// Source: Microsoft KB Article KB317540
/*
SUMMARY
The native code application programming interfaces (APIs) that allow you to interact with the Global Assembly Cache (GAC) are not documented
in the .NET Framework Software Development Kit (SDK) documentation.
MORE INFORMATION
CAUTION: Do not use these APIs in your application to perform assembly binds or to test for the presence of assemblies or other run time,
development, or design-time operations. Only administrative tools and setup programs must use these APIs. If you use the GAC, this directly
exposes your application to assembly binding fragility or may cause your application to work improperly on future versions of the .NET
Framework.
The GAC stores assemblies that are shared across all applications on a computer. The actual storage location and structure of the GAC is
not documented and is subject to change in future versions of the .NET Framework and the Microsoft Windows operating system.
The only supported method to access assemblies in the GAC is through the APIs that are documented in this article.
Most applications do not have to use these APIs because the assembly binding is performed automatically by the common language runtime.
Only custom setup programs or management tools must use these APIs. Microsoft Windows Installer has native support for installing assemblies
to the GAC.
For more information about assemblies and the GAC, see the .NET Framework SDK.
Use the GAC API in the following scenarios:
When you install an assembly to the GAC.
When you remove an assembly from the GAC.
When you export an assembly from the GAC.
When you enumerate assemblies that are available in the GAC.
NOTE: CoInitialize(Ex) must be called before you use any of the functions and interfaces that are described in this specification.
*/
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Globalization;
namespace System.GAC
{
#region Flags
/// <summary>
/// <see cref="IAssemblyName.GetDisplayName"/>
/// </summary>
[Flags]
public enum ASM_DISPLAY_FLAGS
{
VERSION = 0x1,
CULTURE = 0x2,
PUBLIC_KEY_TOKEN = 0x4,
PUBLIC_KEY = 0x8,
CUSTOM = 0x10,
PROCESSORARCHITECTURE = 0x20,
LANGUAGEID = 0x40
}
[Flags]
public enum ASM_CMP_FLAGS
{
NAME = 0x1,
MAJOR_VERSION = 0x2,
MINOR_VERSION = 0x4,
BUILD_NUMBER = 0x8,
REVISION_NUMBER = 0x10,
PUBLIC_KEY_TOKEN = 0x20,
CULTURE = 0x40,
CUSTOM = 0x80,
ALL = NAME | MAJOR_VERSION | MINOR_VERSION |
REVISION_NUMBER | BUILD_NUMBER |
PUBLIC_KEY_TOKEN | CULTURE | CUSTOM,
DEFAULT = 0x100
}
/// <summary>
/// The ASM_NAME enumeration property ID describes the valid names of the name-value pairs in an assembly name.
/// See the .NET Framework SDK for a description of these properties.
/// </summary>
public enum ASM_NAME
{
ASM_NAME_PUBLIC_KEY = 0,
ASM_NAME_PUBLIC_KEY_TOKEN,
ASM_NAME_HASH_VALUE,
ASM_NAME_NAME,
ASM_NAME_MAJOR_VERSION,
ASM_NAME_MINOR_VERSION,
ASM_NAME_BUILD_NUMBER,
ASM_NAME_REVISION_NUMBER,
ASM_NAME_CULTURE,
ASM_NAME_PROCESSOR_ID_ARRAY,
ASM_NAME_OSINFO_ARRAY,
ASM_NAME_HASH_ALGID,
ASM_NAME_ALIAS,
ASM_NAME_CODEBASE_URL,
ASM_NAME_CODEBASE_LASTMOD,
ASM_NAME_NULL_PUBLIC_KEY,
ASM_NAME_NULL_PUBLIC_KEY_TOKEN,
ASM_NAME_CUSTOM,
ASM_NAME_NULL_CUSTOM,
ASM_NAME_MVID,
ASM_NAME_MAX_PARAMS
}
/// <summary>
/// <see cref="IAssemblyCache.UninstallAssembly"/>
/// </summary>
public enum IASSEMBLYCACHE_UNINSTALL_DISPOSITION
{
IASSEMBLYCACHE_UNINSTALL_DISPOSITION_UNINSTALLED = 1,
IASSEMBLYCACHE_UNINSTALL_DISPOSITION_STILL_IN_USE = 2,
IASSEMBLYCACHE_UNINSTALL_DISPOSITION_ALREADY_UNINSTALLED = 3,
IASSEMBLYCACHE_UNINSTALL_DISPOSITION_DELETE_PENDING = 4,
IASSEMBLYCACHE_UNINSTALL_DISPOSITION_HAS_INSTALL_REFERENCES = 5,
IASSEMBLYCACHE_UNINSTALL_DISPOSITION_REFERENCE_NOT_FOUND = 6
}
/// <summary>
/// <see cref="IAssemblyCache.QueryAssemblyInfo"/>
/// </summary>
public enum QUERYASMINFO_FLAG
{
QUERYASMINFO_FLAG_VALIDATE = 1,
QUERYASMINFO_FLAG_GETSIZE = 2
}
/// <summary>
/// <see cref="IAssemblyChance.InstallAssembly"/>
/// </summary>
public enum IASSEMBLYCACHE_INSTALL_FLAG
{
IASSEMBLYCACHE_INSTALL_FLAG_REFRESH = 1,
IASSEMBLYCACHE_INSTALL_FLAG_FORCE_REFRESH = 2
}
/// <summary>
/// The CREATE_ASM_NAME_OBJ_FLAGS enumeration contains the following values:
/// CANOF_PARSE_DISPLAY_NAME - If this flag is specified, the szAssemblyName parameter is a full assembly name and is parsed to
/// the individual properties. If the flag is not specified, szAssemblyName is the "Name" portion of the assembly name.
/// CANOF_SET_DEFAULT_VALUES - If this flag is specified, certain properties, such as processor architecture, are set to
/// their default values.
/// <see cref="AssemblyCache.CreateAssemblyNameObject"/>
/// </summary>
public enum CREATE_ASM_NAME_OBJ_FLAGS
{
CANOF_PARSE_DISPLAY_NAME = 0x1,
CANOF_SET_DEFAULT_VALUES = 0x2
}
/// <summary>
/// The ASM_CACHE_FLAGS enumeration contains the following values:
/// ASM_CACHE_ZAP - Enumerates the cache of precompiled assemblies by using Ngen.exe.
/// ASM_CACHE_GAC - Enumerates the GAC.
/// ASM_CACHE_DOWNLOAD - Enumerates the assemblies that have been downloaded on-demand or that have been shadow-copied.
/// </summary>
[Flags]
public enum ASM_CACHE_FLAGS
{
ASM_CACHE_ZAP = 0x1,
ASM_CACHE_GAC = 0x2,
ASM_CACHE_DOWNLOAD = 0x4
}
#endregion
#region Structs
/// <summary>
/// The FUSION_INSTALL_REFERENCE structure represents a reference that is made when an application has installed an
/// assembly in the GAC.
/// The fields of the structure are defined as follows:
/// cbSize - The size of the structure in bytes.
/// dwFlags - Reserved, must be zero.
/// guidScheme - The entity that adds the reference.
/// szIdentifier - A unique string that identifies the application that installed the assembly.
/// szNonCannonicalData - A string that is only understood by the entity that adds the reference.
/// The GAC only stores this string.
/// Possible values for the guidScheme field can be one of the following:
/// FUSION_REFCOUNT_MSI_GUID - The assembly is referenced by an application that has been installed by using
/// Windows Installer. The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer.
/// This scheme must only be used by Windows Installer itself.
/// FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID - The assembly is referenced by an application that appears in Add/Remove
/// Programs. The szIdentifier field is the token that is used to register the application with Add/Remove programs.
/// FUSION_REFCOUNT_FILEPATH_GUID - The assembly is referenced by an application that is represented by a file in
/// the file system. The szIdentifier field is the path to this file.
/// FUSION_REFCOUNT_OPAQUE_STRING_GUID - The assembly is referenced by an application that is only represented
/// by an opaque string. The szIdentifier is this opaque string. The GAC does not perform existence checking
/// for opaque references when you remove this.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FUSION_INSTALL_REFERENCE
{
public uint cbSize;
public uint dwFlags;
public Guid guidScheme;
public string szIdentifier;
public string szNonCannonicalData;
}
/// <summary>
/// The ASSEMBLY_INFO structure represents information about an assembly in the assembly cache.
/// The fields of the structure are defined as follows:
/// cbAssemblyInfo - Size of the structure in bytes. Permits additions to the structure in future version of the .NET Framework.
/// dwAssemblyFlags - Indicates one or more of the ASSEMBLYINFO_FLAG_* bits.
/// uliAssemblySizeInKB - The size of the files that make up the assembly in kilobytes (KB).
/// pszCurrentAssemblyPathBuf - A pointer to a string buffer that holds the current path of the directory that contains the
/// files that make up the assembly. The path must end with a zero.
/// cchBuf - Size of the buffer that the pszCurrentAssemblyPathBug field points to.
/// dwAssemblyFlags can have one of the following values:
/// ASSEMBLYINFO_FLAG__INSTALLED - Indicates that the assembly is actually installed. Always set in current version of the
/// .NET Framework.
/// ASSEMBLYINFO_FLAG__PAYLOADRESIDENT - Never set in the current version of the .NET Framework.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ASSEMBLY_INFO
{
public uint cbAssemblyInfo;
public uint dwAssemblyFlags;
public ulong uliAssemblySizeInKB;
public string pszCurrentAssemblyPathBuf;
public uint cchBuf;
}
#endregion
public class AssemblyCache
{
#region DLL Entries
/// <summary>
/// The key entry point for reading the assembly cache.
/// </summary>
/// <param name="ppAsmCache">Pointer to return IAssemblyCache</param>
/// <param name="dwReserved">must be 0</param>
[DllImport("fusion.dll", SetLastError = true, PreserveSig = false)]
static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved);
/// <summary>
/// An instance of IAssemblyName is obtained by calling the CreateAssemblyNameObject API.
/// </summary>
/// <param name="ppAssemblyNameObj">Pointer to a memory location that receives the IAssemblyName pointer that is created.</param>
/// <param name="szAssemblyName">A string representation of the assembly name or of a full assembly reference that is
/// determined by dwFlags. The string representation can be null.</param>
/// <param name="dwFlags">Zero or more of the bits that are defined in the CREATE_ASM_NAME_OBJ_FLAGS enumeration.</param>
/// <param name="pvReserved"> Must be null.</param>
[DllImport("fusion.dll", SetLastError = true, CharSet = CharSet.Unicode, PreserveSig = false)]
static extern void CreateAssemblyNameObject(out IAssemblyName ppAssemblyNameObj, string szAssemblyName,
uint dwFlags, IntPtr pvReserved);
/// <summary>
/// To obtain an instance of the CreateAssemblyEnum API, call the CreateAssemblyNameObject API.
/// </summary>
/// <param name="pEnum">Pointer to a memory location that contains the IAssemblyEnum pointer.</param>
/// <param name="pUnkReserved">Must be null.</param>
/// <param name="pName">An assembly name that is used to filter the enumeration. Can be null to enumerate all assemblies in the GAC.</param>
/// <param name="dwFlags">Exactly one bit from the ASM_CACHE_FLAGS enumeration.</param>
/// <param name="pvReserved">Must be NULL.</param>
[DllImport("fusion.dll", SetLastError = true, PreserveSig = false)]
static extern void CreateAssemblyEnum(out IAssemblyEnum pEnum, IntPtr pUnkReserved, IAssemblyName pName,
ASM_CACHE_FLAGS dwFlags, IntPtr pvReserved);
/// <summary>
/// To obtain an instance of the CreateInstallReferenceEnum API, call the CreateInstallReferenceEnum API.
/// </summary>
/// <param name="ppRefEnum">A pointer to a memory location that receives the IInstallReferenceEnum pointer.</param>
/// <param name="pName">The assembly name for which the references are enumerated.</param>
/// <param name="dwFlags"> Must be zero.</param>
/// <param name="pvReserved">Must be null.</param>
[DllImport("fusion.dll", SetLastError = true, PreserveSig = false)]
static extern void CreateInstallReferenceEnum(out IInstallReferenceEnum ppRefEnum, IAssemblyName pName,
uint dwFlags, IntPtr pvReserved);
/// <summary>
/// The GetCachePath API returns the storage location of the GAC.
/// </summary>
/// <param name="dwCacheFlags">Exactly one of the bits defined in the ASM_CACHE_FLAGS enumeration.</param>
/// <param name="pwzCachePath">Pointer to a buffer that is to receive the path of the GAC as a Unicode string.</param>
/// <param name="pcchPath">Length of the pwszCachePath buffer, in Unicode characters.</param>
[DllImport("fusion.dll", SetLastError = true, CharSet = CharSet.Unicode, PreserveSig = false)]
static extern void GetCachePath(ASM_CACHE_FLAGS dwCacheFlags, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwzCachePath,
ref uint pcchPath);
#endregion
#region GUID Definition
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
/// The assembly is referenced by an application that has been installed by using Windows Installer.
/// The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer.
/// This scheme must only be used by Windows Installer itself.
/// </summary>
public static Guid FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID
{
get
{
return new Guid("8cedc215-ac4b-488b-93c0-a50a49cb2fb8");
}
}
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
///
/// </summary>
public static Guid FUSION_REFCOUNT_FILEPATH_GUID
{
get
{
return new Guid("b02f9d65-fb77-4f7a-afa5-b391309f11c9");
}
}
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
///
/// </summary>
public static Guid FUSION_REFCOUNT_OPAQUE_STRING_GUID
{
get
{
return new Guid("2ec93463-b0c3-45e1-8364-327e96aea856");
}
}
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
///
/// </summary>
public static Guid FUSION_REFCOUNT_MSI_GUID
{
get
{
return new Guid("25df0fc1-7f97-4070-add7-4b13bbfd7cb8");
}
}
#endregion
#region Public Functions for DLL - Assembly Cache
/// <summary>
/// Use this method as a start for the GAC API
/// </summary>
/// <returns>IAssemblyCache COM interface</returns>
public static IAssemblyCache CreateAssemblyCache()
{
IAssemblyCache ac;
AssemblyCache.CreateAssemblyCache(out ac, 0);
return ac;
}
#endregion
#region Public Functions for DLL - AssemblyName
public static IAssemblyName CreateAssemblyName(string name)
{
IAssemblyName an;
AssemblyCache.CreateAssemblyNameObject(out an, name, 2, (IntPtr)0);
return an;
}
public static String GetDisplayName(IAssemblyName name, ASM_DISPLAY_FLAGS which)
{
uint bufferSize = 255;
StringBuilder buffer = new StringBuilder((int)bufferSize);
name.GetDisplayName(buffer, ref bufferSize, which);
return buffer.ToString();
}
public static String GetName(IAssemblyName name)
{
uint bufferSize = 255;
StringBuilder buffer = new StringBuilder((int)bufferSize);
name.GetName(ref bufferSize, buffer);
return buffer.ToString();
}
public static Version GetVersion(IAssemblyName name)
{
uint major;
uint minor;
name.GetVersion(out major, out minor);
return new Version((int)major >> 16, (int)major & 0xFFFF, (int)minor >> 16, (int)minor & 0xFFFF);
}
public static byte[] GetPublicKeyToken(IAssemblyName name)
{
byte[] result = new byte[8];
uint bufferSize = 8;
IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize);
name.GetProperty(ASM_NAME.ASM_NAME_PUBLIC_KEY_TOKEN, buffer, ref bufferSize);
for (int i = 0; i < 8; i++)
result[i] = Marshal.ReadByte(buffer, i);
Marshal.FreeHGlobal(buffer);
return result;
}
public static byte[] GetPublicKey(IAssemblyName name)
{
uint bufferSize = 512;
IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize);
name.GetProperty(ASM_NAME.ASM_NAME_PUBLIC_KEY, buffer, ref bufferSize);
byte[] result = new byte[bufferSize];
for (int i = 0; i < bufferSize; i++)
result[i] = Marshal.ReadByte(buffer, i);
Marshal.FreeHGlobal(buffer);
return result;
}
public static CultureInfo GetCulture(IAssemblyName name)
{
uint bufferSize = 255;
IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize);
name.GetProperty(ASM_NAME.ASM_NAME_CULTURE, buffer, ref bufferSize);
string result = Marshal.PtrToStringAuto(buffer);
Marshal.FreeHGlobal(buffer);
return new CultureInfo(result);
}
#endregion
#region Public Functions for DLL - AssemblyEnum
public static IAssemblyEnum CreateGACEnum()
{
IAssemblyEnum ae;
AssemblyCache.CreateAssemblyEnum(out ae, (IntPtr)0, null, ASM_CACHE_FLAGS.ASM_CACHE_GAC, (IntPtr)0);
return ae;
}
/// <summary>
/// Get the next assembly name in the current enumerator or fail
/// </summary>
/// <param name="enumerator"></param>
/// <param name="name"></param>
/// <returns>0 if the enumeration is not at its end</returns>
public static int GetNextAssembly(IAssemblyEnum enumerator, out IAssemblyName name)
{
return enumerator.GetNextAssembly((IntPtr)0, out name, 0);
}
public static String GetGACPath()
{
uint bufferSize = 255;
StringBuilder buffer = new StringBuilder((int)bufferSize);
AssemblyCache.GetCachePath(ASM_CACHE_FLAGS.ASM_CACHE_GAC, buffer, ref bufferSize);
return buffer.ToString();
}
public static String GetZapPath()
{
uint bufferSize = 255;
StringBuilder buffer = new StringBuilder((int)bufferSize);
AssemblyCache.GetCachePath(ASM_CACHE_FLAGS.ASM_CACHE_ZAP, buffer, ref bufferSize);
return buffer.ToString();
}
public static String GetDownloadPath()
{
uint bufferSize = 255;
StringBuilder buffer = new StringBuilder((int)bufferSize);
AssemblyCache.GetCachePath(ASM_CACHE_FLAGS.ASM_CACHE_DOWNLOAD, buffer, ref bufferSize);
return buffer.ToString();
}
#endregion
}
#region COM Interface Definitions
/// <summary>
/// The IAssemblyCache interface is the top-level interface that provides access to the GAC.
/// </summary>
[ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAssemblyCache
{
/// <summary>
/// The IAssemblyCache::UninstallAssembly method removes a reference to an assembly from the GAC.
/// If other applications hold no other references to the assembly, the files that make up the assembly are removed from the GAC.
/// </summary>
/// <param name="dwFlags">No flags defined. Must be zero.</param>
/// <param name="pszAssemblyName">The name of the assembly. A zero-ended Unicode string.</param>
/// <param name="pRefData">A pointer to a FUSION_INSTALL_REFERENCE structure. Although this is not recommended,
/// this parameter can be null. The assembly is installed without an application reference, or all existing application
/// references are gone.</param>
/// <param name="pulDisposition">Pointer to an integer that indicates the action that is performed by the function.</param>
/// <returns>The return values are defined as follows:
/// S_OK - The assembly has been uninstalled.
/// S_FALSE - The operation succeeded, but the assembly was not removed from the GAC.
/// The reason is described in pulDisposition.</returns>
/// <remarks>
/// NOTE: If pulDisposition is not null, pulDisposition contains one of the following values:
/// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_UNINSTALLED - The assembly files have been removed from the GAC.
/// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_STILL_IN_USE - An application is using the assembly.
/// This value is returned on Microsoft Windows 95 and Microsoft Windows 98.
/// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_ALREADY_UNINSTALLED - The assembly does not exist in the GAC.
/// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_DELETE_PENDING - Not used.
/// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_HAS_INSTALL_REFERENCES - The assembly has not been removed from the GAC because
/// another application reference exists.
/// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_REFERENCE_NOT_FOUND - The reference that is specified in pRefData is not found
/// in the GAC.
/// </remarks>
[PreserveSig]
int UninstallAssembly(
uint dwFlags,
[MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName,
[MarshalAs(UnmanagedType.LPArray)] FUSION_INSTALL_REFERENCE[] pRefData,
out uint pulDisposition);
/// <summary>
/// The IAssemblyCache::QueryAssemblyInfo method retrieves information about an assembly from the GAC.
/// </summary>
/// <param name="dwFlags">One of QUERYASMINFO_FLAG_VALIDATE or QUERYASMINFO_FLAG_GETSIZE:
/// *_VALIDATE - Performs validation of the files in the GAC against the assembly manifest, including hash verification
/// and strong name signature verification.
/// *_GETSIZE - Returns the size of all files in the assembly (disk footprint). If this is not specified, the
/// ASSEMBLY_INFO::uliAssemblySizeInKB field is not modified.</param>
/// <param name="pszAssemblyName"></param>
/// <param name="pAsmInfo"></param>
/// <returns></returns>
[PreserveSig]
int QueryAssemblyInfo(
uint dwFlags,
[MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName,
ref ASSEMBLY_INFO pAsmInfo);
/// <summary>
/// Undocumented
/// </summary>
/// <param name="dwFlags"></param>
/// <param name="pvReserved"></param>
/// <param name="ppAsmItem"></param>
/// <param name="pszAssemblyName"></param>
/// <returns></returns>
[PreserveSig]
int CreateAssemblyCacheItem(
uint dwFlags,
IntPtr pvReserved,
out IAssemblyCacheItem ppAsmItem,
[MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName);
/// <summary>
/// Undocumented
/// </summary>
/// <param name="ppAsmScavenger"></param>
/// <returns></returns>
[PreserveSig]
int CreateAssemblyScavenger(
[MarshalAs(UnmanagedType.IUnknown)] out object ppAsmScavenger);
/// <summary>
/// The IAssemblyCache::InstallAssembly method adds a new assembly to the GAC. The assembly must be persisted in the file
/// system and is copied to the GAC.
/// </summary>
/// <param name="dwFlags">At most, one of the bits of the IASSEMBLYCACHE_INSTALL_FLAG_* values can be specified:
/// *_REFRESH - If the assembly is already installed in the GAC and the file version numbers of the assembly being
/// installed are the same or later, the files are replaced.
/// *_FORCE_REFRESH - The files of an existing assembly are overwritten regardless of their version number.</param>
/// <param name="pszManifestFilePath"> A string pointing to the dynamic-linked library (DLL) that contains the assembly manifest.
/// Other assembly files must reside in the same directory as the DLL that contains the assembly manifest.</param>
/// <param name="pRefData">A pointer to a FUSION_INSTALL_REFERENCE that indicates the application on whose behalf the
/// assembly is being installed. Although this is not recommended, this parameter can be null, but this leaves the assembly
/// without any application reference.</param>
/// <returns></returns>
[PreserveSig]
int InstallAssembly(
uint dwFlags,
[MarshalAs(UnmanagedType.LPWStr)] string pszManifestFilePath,
[MarshalAs(UnmanagedType.LPArray)] FUSION_INSTALL_REFERENCE[] pRefData);
}
/// <summary>
/// The IAssemblyName interface represents an assembly name. An assembly name includes a predetermined set of name-value pairs.
/// The assembly name is described in detail in the .NET Framework SDK.
/// </summary>
[ComImport, Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAssemblyName
{
/// <summary>
/// The IAssemblyName::SetProperty method adds a name-value pair to the assembly name, or, if a name-value pair
/// with the same name already exists, modifies or deletes the value of a name-value pair.
/// </summary>
/// <param name="PropertyId">The ID that represents the name part of the name-value pair that is to be
/// added or to be modified. Valid property IDs are defined in the ASM_NAME enumeration.</param>
/// <param name="pvProperty">A pointer to a buffer that contains the value of the property.</param>
/// <param name="cbProperty">The length of the pvProperty buffer in bytes. If cbProperty is zero, the name-value pair
/// is removed from the assembly name.</param>
/// <returns></returns>
[PreserveSig]
int SetProperty(
ASM_NAME PropertyId,
IntPtr pvProperty,
uint cbProperty);
/// <summary>
/// The IAssemblyName::GetProperty method retrieves the value of a name-value pair in the assembly name that specifies the name.
/// </summary>
/// <param name="PropertyId">The ID that represents the name of the name-value pair whose value is to be retrieved.
/// Specified property IDs are defined in the ASM_NAME enumeration.</param>
/// <param name="pvProperty">A pointer to a buffer that is to contain the value of the property.</param>
/// <param name="pcbProperty">The length of the pvProperty buffer, in bytes.</param>
/// <returns></returns>
[PreserveSig]
int GetProperty(
ASM_NAME PropertyId,
IntPtr pvProperty,
ref uint pcbProperty);
/// <summary>
/// The IAssemblyName::Finalize method freezes an assembly name. Additional calls to IAssemblyName::SetProperty are
/// unsuccessful after this method has been called.
/// </summary>
/// <returns></returns>
[PreserveSig]
int Finalize();
/// <summary>
/// The IAssemblyName::GetDisplayName method returns a string representation of the assembly name.
/// </summary>
/// <param name="szDisplayName">A pointer to a buffer that is to contain the display name. The display name is returned in Unicode.</param>
/// <param name="pccDisplayName">The size of the buffer in characters (on input). The length of the returned display name (on return).</param>
/// <param name="dwDisplayFlags">One or more of the bits defined in the ASM_DISPLAY_FLAGS enumeration:
// *_VERSION - Includes the version number as part of the display name.
/// *_CULTURE - Includes the culture.
/// *_PUBLIC_KEY_TOKEN - Includes the public key token.
/// *_PUBLIC_KEY - Includes the public key.
/// *_CUSTOM - Includes the custom part of the assembly name.
/// *_PROCESSORARCHITECTURE - Includes the processor architecture.
/// *_LANGUAGEID - Includes the language ID.</param>
/// <returns></returns>
/// <remarks>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondefaultmarshalingforstrings.asp</remarks>
[PreserveSig]
int GetDisplayName(
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szDisplayName,
ref uint pccDisplayName,
ASM_DISPLAY_FLAGS dwDisplayFlags);
/// <summary>
/// Undocumented
/// </summary>
/// <param name="refIID"></param>
/// <param name="pUnkSink"></param>
/// <param name="pUnkContext"></param>
/// <param name="szCodeBase"></param>
/// <param name="llFlags"></param>
/// <param name="pvReserved"></param>
/// <param name="cbReserved"></param>
/// <param name="ppv"></param>
/// <returns></returns>
[PreserveSig]
int BindToObject(
ref Guid refIID,
[MarshalAs(UnmanagedType.IUnknown)] object pUnkSink,
[MarshalAs(UnmanagedType.IUnknown)] object pUnkContext,
[MarshalAs(UnmanagedType.LPWStr)] string szCodeBase,
long llFlags,
IntPtr pvReserved,
uint cbReserved,
out IntPtr ppv);
/// <summary>
/// The IAssemblyName::GetName method returns the name part of the assembly name.
/// </summary>
/// <param name="lpcwBuffer">Size of the pwszName buffer (on input). Length of the name (on return).</param>
/// <param name="pwzName">Pointer to the buffer that is to contain the name part of the assembly name.</param>
/// <returns></returns>
/// <remarks>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondefaultmarshalingforstrings.asp</remarks>
[PreserveSig]
int GetName(
ref uint lpcwBuffer,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwzName);
/// <summary>
/// The IAssemblyName::GetVersion method returns the version part of the assembly name.
/// </summary>
/// <param name="pdwVersionHi">Pointer to a DWORD that contains the upper 32 bits of the version number.</param>
/// <param name="pdwVersionLow">Pointer to a DWORD that contain the lower 32 bits of the version number.</param>
/// <returns></returns>
[PreserveSig]
int GetVersion(
out uint pdwVersionHi,
out uint pdwVersionLow);
/// <summary>
/// The IAssemblyName::IsEqual method compares the assembly name to another assembly names.
/// </summary>
/// <param name="pName">The assembly name to compare to.</param>
/// <param name="dwCmpFlags">Indicates which part of the assembly name to use in the comparison.
/// Values are one or more of the bits defined in the ASM_CMP_FLAGS enumeration.</param>
/// <returns></returns>
[PreserveSig]
int IsEqual(
IAssemblyName pName,
ASM_CMP_FLAGS dwCmpFlags);
/// <summary>
/// The IAssemblyName::Clone method creates a copy of an assembly name.
/// </summary>
/// <param name="pName"></param>
/// <returns></returns>
[PreserveSig]
int Clone(
out IAssemblyName pName);
}
/// <summary>
/// The IAssemblyEnum interface enumerates the assemblies in the GAC.
/// </summary>
[ComImport, Guid("21b8916c-f28e-11d2-a473-00c04f8ef448"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAssemblyEnum
{
/// <summary>
/// The IAssemblyEnum::GetNextAssembly method enumerates the assemblies in the GAC.
/// </summary>
/// <param name="pvReserved">Must be null.</param>
/// <param name="ppName">Pointer to a memory location that is to receive the interface pointer to the assembly
/// name of the next assembly that is enumerated.</param>
/// <param name="dwFlags">Must be zero.</param>
/// <returns></returns>
[PreserveSig()]
int GetNextAssembly(
IntPtr pvReserved,
out IAssemblyName ppName,
uint dwFlags);
/// <summary>
/// Undocumented. Best guess: reset the enumeration to the first assembly.
/// </summary>
/// <returns></returns>
[PreserveSig()]
int Reset();
/// <summary>
/// Undocumented. Create a copy of the assembly enum that is independently enumerable.
/// </summary>
/// <param name="ppEnum"></param>
/// <returns></returns>
[PreserveSig()]
int Clone(
out IAssemblyEnum ppEnum);
}
/// <summary>
/// The IInstallReferenceItem interface represents a reference that has been set on an assembly in the GAC.
/// Instances of IInstallReferenceIteam are returned by the IInstallReferenceEnum interface.
/// </summary>
[ComImport, Guid("582dac66-e678-449f-aba6-6faaec8a9394"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IInstallReferenceItem
{
/// <summary>
/// The IInstallReferenceItem::GetReference method returns a FUSION_INSTALL_REFERENCE structure.
/// </summary>
/// <param name="ppRefData">A pointer to a FUSION_INSTALL_REFERENCE structure. The memory is allocated by the GetReference
/// method and is freed when IInstallReferenceItem is released. Callers must not hold a reference to this buffer after the
/// IInstallReferenceItem object is released.</param>
/// <param name="dwFlags">Must be zero.</param>
/// <param name="pvReserved">Must be null.</param>
/// <returns></returns>
[PreserveSig]
int GetReference(
[MarshalAs(UnmanagedType.LPArray)] out FUSION_INSTALL_REFERENCE[] ppRefData,
uint dwFlags,
IntPtr pvReserved);
}
/// <summary>
/// The IInstallReferenceEnum interface enumerates all references that are set on an assembly in the GAC.
/// NOTE: References that belong to the assembly are locked for changes while those references are being enumerated.
/// </summary>
[ComImport, Guid("56b1a988-7c0c-4aa2-8639-c3eb5a90226f"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IInstallReferenceEnum
{
/// <summary>
/// IInstallReferenceEnum::GetNextInstallReferenceItem returns the next reference information for an assembly.
/// </summary>
/// <param name="ppRefItem">Pointer to a memory location that receives the IInstallReferenceItem pointer.</param>
/// <param name="dwFlags">Must be zero.</param>
/// <param name="pvReserved">Must be null.</param>
/// <returns></returns>
[PreserveSig()]
int GetNextInstallReferenceItem(
out IInstallReferenceItem ppRefItem,
uint dwFlags,
IntPtr pvReserved);
}
/// <summary>
/// Undocumented. Probably only for internal use.
/// <see cref="IAssemblyCache.CreateAssemblyCacheItem"/>
/// </summary>
[ComImport, Guid("9E3AAEB4-D1CD-11D2-BAB9-00C04F8ECEAE"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAssemblyCacheItem
{
/// <summary>
/// Undocumented.
/// </summary>
/// <param name="dwFlags"></param>
/// <param name="pszStreamName"></param>
/// <param name="dwFormat"></param>
/// <param name="dwFormatFlags"></param>
/// <param name="ppIStream"></param>
/// <param name="puliMaxSize"></param>
void CreateStream(
uint dwFlags,
[MarshalAs(UnmanagedType.LPWStr)] string pszStreamName,
uint dwFormat,
uint dwFormatFlags,
out System.Runtime.InteropServices.ComTypes.IStream ppIStream,
ref long puliMaxSize);
/// <summary>
/// Undocumented.
/// </summary>
/// <param name="dwFlags"></param>
/// <param name="pulDisposition"></param>
void Commit(
uint dwFlags,
out long pulDisposition);
/// <summary>
/// Undocumented.
/// </summary>
void AbortItem();
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
#endif
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
#if ES_BUILD_STANDALONE
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
#endif
/*
EventDescriptor was public in the separate System.Diagnostics.Tracing assembly(pre NS2.0),
now the move to CoreLib marked them as private.
While they are technically private (it's a contract used between the library and the ILC toolchain),
we need them to be rooted and exported from shared library for the system to work.
For now I'm simply marking them as public again.A cleaner solution might be to use.rd.xml to
root them and modify shared library definition to force export them.
*/
#if ES_BUILD_PN
public
#else
internal
#endif
struct EventDescriptor
{
# region private
[FieldOffset(0)]
private int m_traceloggingId;
[FieldOffset(0)]
private ushort m_id;
[FieldOffset(2)]
private byte m_version;
[FieldOffset(3)]
private byte m_channel;
[FieldOffset(4)]
private byte m_level;
[FieldOffset(5)]
private byte m_opcode;
[FieldOffset(6)]
private ushort m_task;
[FieldOffset(8)]
private long m_keywords;
#endregion
public EventDescriptor(
int traceloggingId,
byte level,
byte opcode,
long keywords
)
{
this.m_id = 0;
this.m_version = 0;
this.m_channel = 0;
this.m_traceloggingId = traceloggingId;
this.m_level = level;
this.m_opcode = opcode;
this.m_task = 0;
this.m_keywords = keywords;
}
public EventDescriptor(
int id,
byte version,
byte channel,
byte level,
byte opcode,
int task,
long keywords
)
{
if (id < 0)
{
throw new ArgumentOutOfRangeException(nameof(id), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (id > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(id), SR.Format(SR.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue));
}
m_traceloggingId = 0;
m_id = (ushort)id;
m_version = version;
m_channel = channel;
m_level = level;
m_opcode = opcode;
m_keywords = keywords;
if (task < 0)
{
throw new ArgumentOutOfRangeException(nameof(task), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (task > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(task), SR.Format(SR.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue));
}
m_task = (ushort)task;
}
public int EventId
{
get
{
return m_id;
}
}
public byte Version
{
get
{
return m_version;
}
}
public byte Channel
{
get
{
return m_channel;
}
}
public byte Level
{
get
{
return m_level;
}
}
public byte Opcode
{
get
{
return m_opcode;
}
}
public int Task
{
get
{
return m_task;
}
}
public long Keywords
{
get
{
return m_keywords;
}
}
internal int TraceLoggingId
{
get
{
return m_traceloggingId;
}
}
public override bool Equals(object? obj)
{
if (!(obj is EventDescriptor))
return false;
return Equals((EventDescriptor) obj);
}
public override int GetHashCode()
{
return m_id ^ m_version ^ m_channel ^ m_level ^ m_opcode ^ m_task ^ (int)m_keywords;
}
public bool Equals(EventDescriptor other)
{
if ((m_id != other.m_id) ||
(m_version != other.m_version) ||
(m_channel != other.m_channel) ||
(m_level != other.m_level) ||
(m_opcode != other.m_opcode) ||
(m_task != other.m_task) ||
(m_keywords != other.m_keywords))
{
return false;
}
return true;
}
public static bool operator ==(EventDescriptor event1, EventDescriptor event2)
{
return event1.Equals(event2);
}
public static bool operator !=(EventDescriptor event1, EventDescriptor event2)
{
return !event1.Equals(event2);
}
}
}
| |
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using NuGet.Common;
using NuGetGallery.Operations.Common;
namespace NuGetGallery.Operations
{
[Export(typeof(HelpCommand))]
[Command(typeof(CommandHelp), "help", "HelpCommandDescription", AltName = "?", MaxArgs = 1,
UsageSummaryResourceName = "HelpCommandUsageSummary", UsageDescriptionResourceName = "HelpCommandUsageDescription",
UsageExampleResourceName = "HelpCommandUsageExamples")]
public class HelpCommand : OpsTask
{
private readonly string _commandExe;
private readonly ICommandManager _commandManager;
private readonly string _helpUrl;
private readonly string _productName;
private string CommandName
{
get
{
if (Arguments != null && Arguments.Count > 0)
{
return Arguments[0];
}
return null;
}
}
[Option(typeof(CommandHelp), "HelpCommandAll")]
public bool All { get; set; }
[ImportingConstructor]
public HelpCommand(ICommandManager commandManager)
: this(commandManager, Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Name, CommandLineConstants.ReferencePage)
{
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#",
Justification = "We don't use the Url for anything besides printing, so it's ok to represent it as a string.")]
public HelpCommand(ICommandManager commandManager, string commandExe, string productName, string helpUrl)
{
_commandManager = commandManager;
_commandExe = commandExe;
_productName = productName;
_helpUrl = helpUrl;
}
public override void ExecuteCommand()
{
if (!String.IsNullOrEmpty(CommandName))
{
ViewHelpForCommand(CommandName);
}
else if (All)
{
ViewHelp(all: true);
}
else
{
ViewHelp(all: false);
}
}
public void ViewHelp(bool all)
{
Console.WriteLine("{0} Version: {1}", _productName, GetType().Assembly.GetName().Version);
Console.WriteLine("usage: {0} <command> [args] [options] ", _commandExe);
Console.WriteLine("Type '{0} help <command>' for help on a specific command.", _commandExe);
Console.WriteLine();
Console.WriteLine("Available commands:");
Console.WriteLine();
var commands = from c in _commandManager.GetCommands()
where all || !c.CommandAttribute.IsSpecialPurpose
orderby c.CommandAttribute.CommandName
select c.CommandAttribute;
// Padding for printing
int maxWidth = commands.Max(c => c.CommandName.Length + GetAltText(c.AltName).Length);
foreach (var command in commands)
{
PrintCommand(maxWidth, command);
}
if (_helpUrl != null)
{
Console.WriteLine();
Console.WriteLine("For more information, visit {0}", _helpUrl);
}
}
private static void PrintCommand(int maxWidth, CommandAttribute commandAttribute)
{
// Write out the command name left justified with the max command's width's padding
Console.Write(" {0, -" + maxWidth + "} ", GetCommandText(commandAttribute));
// Starting index of the description
int descriptionPadding = maxWidth + 4;
PrintJustified(descriptionPadding, commandAttribute.Description);
}
private static string GetCommandText(CommandAttribute commandAttribute)
{
return commandAttribute.CommandName + GetAltText(commandAttribute.AltName);
}
public void ViewHelpForCommand(string commandName)
{
ICommand command = _commandManager.GetCommand(commandName);
CommandAttribute attribute = command.CommandAttribute;
Console.WriteLine("usage: {0} {1} {2}", _commandExe, attribute.CommandName, attribute.UsageSummary);
Console.WriteLine();
if (!String.IsNullOrEmpty(attribute.AltName))
{
Console.WriteLine("alias: {0}", attribute.AltName);
Console.WriteLine();
}
Console.WriteLine(attribute.Description);
Console.WriteLine();
if (attribute.UsageDescription != null)
{
const int padding = 5;
PrintJustified(padding, attribute.UsageDescription);
Console.WriteLine();
}
var options = _commandManager.GetCommandOptions(command);
if (options.Count > 0)
{
Console.WriteLine("options:");
Console.WriteLine();
// Get the max option width. +2 for showing + against multivalued properties
int maxOptionWidth = options.Max(o => o.Value.Name.Length) + 2;
// Get the max altname option width
int maxAltOptionWidth = options.Max(o => (o.Key.AltName ?? String.Empty).Length);
foreach (var o in options)
{
Console.Write(" -{0, -" + (maxOptionWidth + 2) + "}", o.Value.Name +
(TypeHelper.IsMultiValuedProperty(o.Value) ? " +" : String.Empty));
Console.Write(" {0, -" + (maxAltOptionWidth + 4) + "}", GetAltText(o.Key.AltName));
PrintJustified((10 + maxAltOptionWidth + maxOptionWidth), o.Key.Description);
}
if (_helpUrl != null)
{
Console.WriteLine();
Console.WriteLine("For more information, visit {0}", _helpUrl);
}
Console.WriteLine();
}
}
private void ViewHelpForAllCommands()
{
var commands = from c in _commandManager.GetCommands()
orderby c.CommandAttribute.CommandName
select c.CommandAttribute;
TextInfo info = CultureInfo.CurrentCulture.TextInfo;
foreach (var command in commands)
{
Console.WriteLine(info.ToTitleCase(command.CommandName) + " Command");
ViewHelpForCommand(command.CommandName);
}
}
private static string GetAltText(string altNameText)
{
if (String.IsNullOrEmpty(altNameText))
{
return String.Empty;
}
return String.Format(CultureInfo.CurrentCulture, " ({0})", altNameText);
}
private static void PrintJustified(int startIndex, string text)
{
PrintJustified(startIndex, text, Console.WindowWidth);
}
private static void PrintJustified(int startIndex, string text, int maxWidth)
{
if (maxWidth > startIndex)
{
maxWidth = maxWidth - startIndex - 1;
}
while (text.Length > 0)
{
// Trim whitespace at the beginning
text = text.TrimStart();
// Calculate the number of chars to print based on the width of the System.Console
int length = Math.Min(text.Length, maxWidth);
// Text we can print without overflowing the System.Console.
string content = text.Substring(0, length);
int leftPadding = startIndex + length - Console.CursorLeft;
// Print it with the correct padding
Console.WriteLine(content.PadLeft(leftPadding));
// Get the next substring to be printed
text = text.Substring(content.Length);
}
}
}
}
| |
namespace dotless.Core.Parser.Tree
{
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
using System.Text;
public class Ruleset : Node
{
public NodeList<Selector> Selectors { get; set; }
public List<Node> Rules { get; set; }
private List<Ruleset> _RulesetsCache;
public List<Ruleset> Rulesets
{
get
{
if (_RulesetsCache != null) return _RulesetsCache;
_RulesetsCache = GetRulesets();
return _RulesetsCache;
}
}
public void InvalidRulesetCache()
{
_RulesetsCache = null;
}
private Dictionary<string, List<Closure>> _lookups;
private Dictionary<string, Rule> _variables;
public Ruleset(NodeList<Selector> selectors, List<Node> rules)
: this()
{
Selectors = selectors;
Rules = rules;
}
protected Ruleset()
{
_lookups = new Dictionary<string, List<Closure>>();
}
public Rule Variable(string name, Node startNode)
{
return Rules
.TakeWhile(r => r != startNode)
.OfType<Rule>()
.Where(r => r.Variable)
.Reverse()
.FirstOrDefault(r => r.Name == name);
}
private List<Ruleset> GetRulesets()
{
return Rules.OfType<Ruleset>().ToList();
}
private static bool _AnyMatch(NodeList<Selector> selectors, Selector other)
{
for (var i = 0; i < selectors.Count; i++)
{
if (selectors[i].Match(other))
{
return true;
}
}
return false;
}
public List<Closure> Find(Env env, Selector selector, Ruleset self)
{
self = self ?? this;
var rules = new List<Closure>();
var key = selector.ToCSS(env);
if (_lookups.ContainsKey(key))
return _lookups[key];
for(var x = 0; x < Rulesets.Count; x++)
{
var rule = Rulesets[x];
if (rule == self) continue;
if(rule.Selectors && _AnyMatch(rule.Selectors, selector))
{
if (selector.Elements.Count > 1)
{
var remainingSelectors = new Selector(new NodeList<Element>(selector.Elements.Skip(1)));
var closures = rule.Find(env, remainingSelectors, self);
for (var i = 0; i < closures.Count; i++)
{
var closure = closures[i];
closure.Context.Insert(0, rule);
}
rules.AddRange(closures);
}
else
{
rules.Add(new Closure { Ruleset = rule, Context = new List<Ruleset> { rule } });
}
}
}
return _lookups[key] = rules;
}
public virtual bool MatchArguements(NodeList<Expression> arguements, Env env)
{
return arguements == null || arguements.Count == 0;
}
public override Node Evaluate(Env env)
{
if (this is Root)
{
env = env ?? new Env();
NodeHelper.ExpandNodes<Import>(env, this.Rules);
}
EvaluateRules(env);
return this;
}
public List<Node> EvaluateRules(Env env)
{
env.Frames.Push(this);
NodeHelper.ExpandNodes<MixinCall>(env, this.Rules);
for (var i = 0; i < Rules.Count; i++)
{
Rules[i] = Rules[i].Evaluate(env);
}
InvalidRulesetCache();
env.Frames.Pop();
return Rules;
}
public string ToCSS()
{
return ToCSS(new Env());
}
public override string ToCSS(Env env)
{
if (!Rules.Any())
return "";
Evaluate(env);
var css = ToCSS(env, new Context());
if (env.Compress)
{
var minified = new StringBuilder(css.Length);
bool inWhitespace = false;
for (var i = 0; i < css.Length; i++)
{
var c = css[i];
if (!char.IsWhiteSpace(c))
{
inWhitespace = false;
minified.Append(c);
continue;
}
if (!inWhitespace)
{
minified.Append(' ');
inWhitespace = true;
}
}
css = minified.ToString();
}
return css;
}
protected virtual string ToCSS(Env env, Context context)
{
var css = new List<string>(); // The CSS output
var rules = new List<string>(); // node.Rule instances
var rulesets = new List<string>(); // node.Ruleset instances
var paths = new Context(); // Current selectors
if (!(this is Root))
{
paths.AppendSelectors(context, Selectors);
}
for(var i = 0; i < Rules.Count; i++)
{
var rule = Rules[i];
if (rule.IgnoreOutput())
continue;
if(rule is Comment && ((Comment)rule).Silent)
continue;
if (rule is Ruleset)
{
var ruleset = (Ruleset) rule;
rulesets.Add(ruleset.ToCSS(env, paths));
}
else if (rule is Rule)
{
var r = (rule as Rule);
if (!r.Variable)
rules.Add(r.ToCSS(env));
}
else
{
if (this is Root)
rulesets.Add(rule.ToCSS(env));
else
rules.Add(rule.ToCSS(env));
}
}
var rulesetsStr = rulesets.JoinStrings("");
// If this is the root node, we don't render
// a selector, or {}.
// Otherwise, only output if this ruleset has rules.
if (this is Root)
css.Add(rules.JoinStrings(env.Compress ? "" : "\n"));
else
{
if (rules.Count > 0)
{
css.Add(paths.ToCSS(env));
css.Add(
(env.Compress ? "{" : " {\n ") +
rules.JoinStrings(env.Compress ? "" : "\n ") +
(env.Compress ? "}" : "\n}\n"));
}
}
css.Add(rulesetsStr);
return css.JoinStrings("");
}
public override string ToString()
{
var format = "{0}{{{1}}}";
return Selectors != null && Selectors.Count > 0
? string.Format(format, Selectors.Select(s => s.ToCSS(new Env())).JoinStrings(""), Rules.Count)
: string.Format(format, "*", Rules.Count);
}
public override Node Copy()
{
return new Ruleset(
Selectors != null ?
(NodeList<Selector>)Selectors.Copy() :
null,
Rules != null ?
Rules.SelectList(r => r.Copy()) :
null
);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// BSB Numbers Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KABDataSet : EduHubDataSet<KAB>
{
/// <inheritdoc />
public override string Name { get { return "KAB"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KABDataSet(EduHubContext Context)
: base(Context)
{
Index_BSB = new Lazy<Dictionary<string, KAB>>(() => this.ToDictionary(i => i.BSB));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KAB" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KAB" /> fields for each CSV column header</returns>
internal override Action<KAB, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KAB, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "BSB":
mapper[i] = (e, v) => e.BSB = v;
break;
case "BANK":
mapper[i] = (e, v) => e.BANK = v;
break;
case "ADDRESS":
mapper[i] = (e, v) => e.ADDRESS = v;
break;
case "SUBURB":
mapper[i] = (e, v) => e.SUBURB = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KAB" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KAB" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KAB" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KAB}"/> of entities</returns>
internal override IEnumerable<KAB> ApplyDeltaEntities(IEnumerable<KAB> Entities, List<KAB> DeltaEntities)
{
HashSet<string> Index_BSB = new HashSet<string>(DeltaEntities.Select(i => i.BSB));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.BSB;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_BSB.Remove(entity.BSB);
if (entity.BSB.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KAB>> Index_BSB;
#endregion
#region Index Methods
/// <summary>
/// Find KAB by BSB field
/// </summary>
/// <param name="BSB">BSB value used to find KAB</param>
/// <returns>Related KAB entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KAB FindByBSB(string BSB)
{
return Index_BSB.Value[BSB];
}
/// <summary>
/// Attempt to find KAB by BSB field
/// </summary>
/// <param name="BSB">BSB value used to find KAB</param>
/// <param name="Value">Related KAB entity</param>
/// <returns>True if the related KAB entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByBSB(string BSB, out KAB Value)
{
return Index_BSB.Value.TryGetValue(BSB, out Value);
}
/// <summary>
/// Attempt to find KAB by BSB field
/// </summary>
/// <param name="BSB">BSB value used to find KAB</param>
/// <returns>Related KAB entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KAB TryFindByBSB(string BSB)
{
KAB value;
if (Index_BSB.Value.TryGetValue(BSB, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KAB table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KAB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KAB](
[BSB] varchar(6) NOT NULL,
[BANK] varchar(10) NULL,
[ADDRESS] varchar(50) NULL,
[SUBURB] varchar(30) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KAB_Index_BSB] PRIMARY KEY CLUSTERED (
[BSB] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KABDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KABDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KAB"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KAB"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KAB> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_BSB = new List<string>();
foreach (var entity in Entities)
{
Index_BSB.Add(entity.BSB);
}
builder.AppendLine("DELETE [dbo].[KAB] WHERE");
// Index_BSB
builder.Append("[BSB] IN (");
for (int index = 0; index < Index_BSB.Count; index++)
{
if (index != 0)
builder.Append(", ");
// BSB
var parameterBSB = $"@p{parameterIndex++}";
builder.Append(parameterBSB);
command.Parameters.Add(parameterBSB, SqlDbType.VarChar, 6).Value = Index_BSB[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KAB data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KAB data set</returns>
public override EduHubDataSetDataReader<KAB> GetDataSetDataReader()
{
return new KABDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KAB data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KAB data set</returns>
public override EduHubDataSetDataReader<KAB> GetDataSetDataReader(List<KAB> Entities)
{
return new KABDataReader(new EduHubDataSetLoadedReader<KAB>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KABDataReader : EduHubDataSetDataReader<KAB>
{
public KABDataReader(IEduHubDataSetReader<KAB> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 7; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // BSB
return Current.BSB;
case 1: // BANK
return Current.BANK;
case 2: // ADDRESS
return Current.ADDRESS;
case 3: // SUBURB
return Current.SUBURB;
case 4: // LW_DATE
return Current.LW_DATE;
case 5: // LW_TIME
return Current.LW_TIME;
case 6: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // BANK
return Current.BANK == null;
case 2: // ADDRESS
return Current.ADDRESS == null;
case 3: // SUBURB
return Current.SUBURB == null;
case 4: // LW_DATE
return Current.LW_DATE == null;
case 5: // LW_TIME
return Current.LW_TIME == null;
case 6: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // BSB
return "BSB";
case 1: // BANK
return "BANK";
case 2: // ADDRESS
return "ADDRESS";
case 3: // SUBURB
return "SUBURB";
case 4: // LW_DATE
return "LW_DATE";
case 5: // LW_TIME
return "LW_TIME";
case 6: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "BSB":
return 0;
case "BANK":
return 1;
case "ADDRESS":
return 2;
case "SUBURB":
return 3;
case "LW_DATE":
return 4;
case "LW_TIME":
return 5;
case "LW_USER":
return 6;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
/*
*
* fuzzynet: Fuzzy Logic Library for Microsoft .NET
* Copyright (C) 2008 Dmitry Kaluzhny ([email protected])
*
* */
using System;
using System.Collections.Generic;
namespace AI.Fuzzy.Library
{
/// <summary>
/// Interface that must be implemented by class to be used as output function in Sugeno Fuzzy System
/// </summary>
public interface ISugenoFunction : INamedValue
{
/// <summary>
/// Calculate result of function
/// </summary>
/// <param name="inputValues">Input values</param>
/// <returns>Result of the calculation</returns>
double Evaluate(Dictionary<FuzzyVariable, double> inputValues);
}
/// <summary>
/// Lenear function for Sugeno Fuzzy System (can be created via SugenoFuzzySystem::CreateSugenoFunction methods
/// </summary>
public class LinearSugenoFunction : NamedValueImpl, ISugenoFunction
{
List<FuzzyVariable> _input = null;
Dictionary<FuzzyVariable, double> _coeffs = new Dictionary<FuzzyVariable,double>();
double _constValue = 0.0;
/// <summary>
/// Get or set constant coefficient
/// </summary>
public double ConstValue
{
get { return _constValue; }
set { _constValue = value; }
}
/// <summary>
/// Get coefficient by fuzzy variable
/// </summary>
/// <param name="var">Fuzzy variable</param>
/// <returns>Coefficient's value</returns>
public double GetCoefficient(FuzzyVariable var)
{
if (var == null)
{
return _constValue;
}
else
{
return _coeffs[var];
}
}
/// <summary>
/// Set coefficient by fuzzy variable
/// </summary>
/// <param name="var">Fuzzy variable</param>
/// <param name="coeff">New value of the coefficient</param>
public void SetCoefficient(FuzzyVariable var, double coeff)
{
if (var == null)
{
_constValue = coeff;
}
else
{
_coeffs[var] = coeff;
}
}
internal LinearSugenoFunction(string name, List<FuzzyVariable> input) : base(name)
{
_input = input;
}
internal LinearSugenoFunction(string name, List<FuzzyVariable> input, Dictionary<FuzzyVariable, double> coeffs, double constValue)
: this (name, input)
{
//
// Check that all coeffecients are related to the variable from input
//
foreach (FuzzyVariable var in coeffs.Keys)
{
if (!_input.Contains(var))
{
throw new ArgumentException(string.Format(
"Input of the fuzzy system does not contain '{0}' variable.",
var.Name));
}
}
//
// Initialize members
//
_coeffs = coeffs;
_constValue = constValue;
}
internal LinearSugenoFunction(string name, List<FuzzyVariable> input, double[] coeffs)
: this(name, input)
{
//
// Check input values
//
if (coeffs.Length != input.Count && coeffs.Length != input.Count + 1)
{
throw new ArgumentException("Wrong lenght of coefficients' array");
}
//
// Fill list of coefficients
//
for (int i = 0; i < input.Count; i++)
{
_coeffs.Add(input[i], coeffs[i]);
}
if (coeffs.Length == input.Count + 1)
{
_constValue = coeffs[coeffs.Length - 1];
}
}
/// <summary>
/// Calculate result of linear function
/// </summary>
/// <param name="inputValues">Input values</param>
/// <returns>Result of the calculation</returns>
public double Evaluate(Dictionary<FuzzyVariable, double> inputValues)
{
//NOTE: input values should be validated here
double result = 0.0;
foreach (FuzzyVariable var in _coeffs.Keys)
{
result += _coeffs[var] * inputValues[var];
}
result += _constValue;
return result;
}
}
/// <summary>
/// Used as an output variable in Sugeno fuzzy inference system.
/// </summary>
public class SugenoVariable : NamedVariableImpl
{
List<ISugenoFunction> _functions = new List<ISugenoFunction>();
/// <summary>
/// Cnstructor
/// </summary>
/// <param name="name">Name of the variable</param>
public SugenoVariable(string name) : base(name)
{
}
/// <summary>
/// List of functions that belongs to the variable
/// </summary>
public List<ISugenoFunction> Functions
{
get
{
return _functions;
}
}
/// <summary>
/// List of functions that belongs to the variable (implementation of INamedVariable)
/// </summary>
public override List<INamedValue> Values
{
get
{
List<INamedValue> values = new List<INamedValue>();
foreach (ISugenoFunction val in _functions)
{
values.Add(val);
}
return values;
}
}
/// <summary>
/// Find function by its name
/// </summary>
/// <param name="name">Name of the function</param>
/// <returns>Found function</returns>
public ISugenoFunction GetFuncByName(string name)
{
foreach (NamedValueImpl func in Values)
{
if (func.Name == name)
{
return (ISugenoFunction)func;
}
}
throw new KeyNotFoundException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16805")]
public partial class HttpClientHandler_SslProtocols_Test
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (var handler = new HttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsSslConfiguration))]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(~SslProtocols.None)]
#pragma warning disable 0618 // obsolete warning
[InlineData(SslProtocols.Ssl2)]
[InlineData(SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
#pragma warning restore 0618
public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsSslConfiguration))]
[InlineData(SslProtocols.Tls, false)]
[InlineData(SslProtocols.Tls, true)]
[InlineData(SslProtocols.Tls11, false)]
[InlineData(SslProtocols.Tls11, true)]
[InlineData(SslProtocols.Tls12, false)]
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
public static readonly object [][] SupportedSSLVersionServers =
{
new object[] {SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer},
new object[] {SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer},
new object[] {SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer},
};
// This test is logically the same as the above test, albeit using remote servers
// instead of local ones. We're keeping it for now (as outerloop) because it helps
// to validate against another SSL implementation that what we mean by a particular
// TLS version matches that other implementation.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
using (HttpClientHandler handler = new HttpClientHandler())
{
if (PlatformDetection.IsCentos7)
{
// Default protocol selection is always TLSv1 on Centos7 libcurl 7.29.0
// Hence, set the specific protocol on HttpClient that is required by test
handler.SslProtocols = sslProtocols;
}
using (var client = new HttpClient(handler))
{
(await client.GetAsync(url)).Dispose();
}
}
}
public static readonly object[][] NotSupportedSSLVersionServers =
{
new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer},
new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer},
};
// It would be easy to remove the dependency on these remote servers if we didn't
// explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw
// when trying to use such an SslStream, we can't stand up a localhost server that
// only speaks those protocols.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[ConditionalTheory(nameof(SSLv3DisabledByDefault))]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsSslConfiguration), nameof(SslDefaultsToTls12))]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
var options = new LoopbackServer.Options { UseSsl = true };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(stream).SslProtocol);
await LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
return null;
}, options));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsSslConfiguration))]
[InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))]
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))]
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException(
SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException)
{
using (var handler = new HttpClientHandler() { SslProtocols = allowedProtocol, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync(exceptedServerException, () => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(8538, TestPlatforms.Windows)]
[Fact]
public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12()
{
using (var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
if (BackendSupportsSslConfiguration)
{
LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true };
options.SslProtocols = SslProtocols.Tls;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync<IOException>(() => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 })
{
options.SslProtocols = prot;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
else
{
await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/"));
}
}
}
private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7;
// TLS 1.2 may not be enabled on Win7
// https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12
}
}
| |
using System;
using System.Linq.Expressions;
using MoreMountains.NiceVibrations;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
public class TierBreakScreen : Screen
{
public const string Id = "TierBreak";
private const int IntermissionSeconds = 30;
private static readonly int[] BroadcastAddTimes = {15, 10};
public Text modeText;
public DifficultyBall difficultyBall;
public Text stageTitleText;
public Text scoreText;
public Text gradeText;
public Text accuracyText;
public Text maxComboText;
public Text standardMetricText;
public Text advancedMetricText;
public GameObject criterionEntryHolder;
public CircleButton nextStageButton;
public CircleButton retryButton;
public GameObject criterionEntryPrefab;
private TierState tierState;
private GameState gameState;
private DateTimeOffset proceedToNextStageTime = DateTimeOffset.MaxValue;
private DateTimeOffset nextBroadcastCountdownTime = DateTimeOffset.MaxValue;
private int broadcastCount;
public override string GetId() => Id;
public override async void OnScreenBecameActive()
{
base.OnScreenBecameActive();
// TODO: Most code here is the same as the one in ResultScreen.cs. Refactor?
gameState = Context.GameState;
Context.GameState = null;
// Load translucent cover
var path = "file://" + gameState.Level.Path + gameState.Level.Meta.background.path;
TranslucentCover.Set(await Context.AssetMemory.LoadAsset<Sprite>(path, AssetTag.GameCover));
// Update performance info
scoreText.text = Mathf.FloorToInt((float) gameState.Score).ToString("D6");
accuracyText.text = "RESULT_X_ACCURACY".Get((Math.Floor(gameState.Accuracy * 100 * 100) / 100).ToString("0.00"));
if (Mathf.Approximately((float) gameState.Accuracy, 1))
{
accuracyText.text = "RESULT_FULL_ACCURACY".Get();
}
maxComboText.text = "RESULT_X_COMBO".Get(gameState.MaxCombo);
if (gameState.GradeCounts[NoteGrade.Bad] == 0 && gameState.GradeCounts[NoteGrade.Miss] == 0)
{
maxComboText.text = "RESULT_FULL_COMBO".Get();
}
var scoreGrade = ScoreGrades.From(gameState.Score);
gradeText.text = scoreGrade.ToString();
gradeText.GetComponent<GradientMeshEffect>().SetGradient(scoreGrade.GetGradient());
if (scoreGrade == ScoreGrade.MAX || scoreGrade == ScoreGrade.SSS)
{
scoreText.GetComponent<GradientMeshEffect>().SetGradient(scoreGrade.GetGradient());
}
else
{
scoreText.GetComponent<GradientMeshEffect>().enabled = false;
}
standardMetricText.text = $"<b>Perfect</b> {gameState.GradeCounts[NoteGrade.Perfect]} " +
$"<b>Great</b> {gameState.GradeCounts[NoteGrade.Great]} " +
$"<b>Good</b> {gameState.GradeCounts[NoteGrade.Good]} " +
$"<b>Bad</b> {gameState.GradeCounts[NoteGrade.Bad]} " +
$"<b>Miss</b> {gameState.GradeCounts[NoteGrade.Miss]}";
advancedMetricText.text = $"<b>Early</b> {gameState.EarlyCount} " +
$"<b>Late</b> {gameState.LateCount} " +
$"<b>{"RESULT_AVG_TIMING_ERR".Get()}</b> {gameState.AverageTimingError:0.000}s " +
$"<b>{"RESULT_STD_TIMING_ERR".Get()}</b> {gameState.StandardTimingError:0.000}s";
if (!Context.Player.Settings.DisplayEarlyLateIndicators) advancedMetricText.text = "";
tierState = Context.TierState;
modeText.text = tierState.Tier.Meta.name;
var stage = tierState.CurrentStage;
difficultyBall.SetModel(stage.Difficulty, stage.DifficultyLevel);
stageTitleText.text = stage.Level.Meta.title;
if (tierState.IsFailed)
{
retryButton.StartPulsing();
}
else
{
nextStageButton.StartPulsing();
}
nextStageButton.State = tierState.IsFailed ? CircleButtonState.GoBack : (tierState.IsCompleted ? CircleButtonState.Finish : CircleButtonState.NextStage);
nextStageButton.interactableMonoBehavior.onPointerClick.SetListener(_ =>
{
Context.Haptic(HapticTypes.SoftImpact, true);
nextStageButton.StopPulsing();
if (tierState.IsFailed)
{
GoBack();
}
else
{
if (tierState.IsCompleted) Finish();
else NextStage();
}
});
retryButton.State = CircleButtonState.Retry;
retryButton.interactableMonoBehavior.onPointerClick.SetListener(_ =>
{
Context.Haptic(HapticTypes.SoftImpact, true);
retryButton.StopPulsing();
Retry();
});
// Update criterion entries
foreach (Transform child in criterionEntryHolder.transform) Destroy(child.gameObject);
foreach (var criterion in Context.TierState.Criteria)
{
var entry = Instantiate(criterionEntryPrefab, criterionEntryHolder.transform)
.GetComponent<CriterionEntry>();
entry.SetModel(criterion.Description, criterion.Judge(Context.TierState));
}
criterionEntryHolder.transform.RebuildLayout();
NavigationBackdrop.Instance.Apply(it =>
{
it.IsBlurred = true;
it.FadeBrightness(1, 0.8f);
});
ProfileWidget.Instance.Enter();
if (tierState.IsFailed)
{
Toast.Next(Toast.Status.Failure, "TOAST_TIER_FAILED".Get());
}
if (!tierState.IsCompleted && !tierState.IsFailed)
{
proceedToNextStageTime = DateTimeOffset.UtcNow.AddSeconds(IntermissionSeconds);
nextBroadcastCountdownTime = DateTimeOffset.UtcNow;
}
else
{
proceedToNextStageTime = DateTimeOffset.MaxValue;
nextBroadcastCountdownTime = DateTimeOffset.MaxValue;
}
}
public override void OnScreenUpdate()
{
base.OnScreenUpdate();
if (DateTimeOffset.UtcNow > proceedToNextStageTime)
{
nextStageButton.MockClick();
nextStageButton.StopPulsing();
NextStage();
}
else if (DateTimeOffset.UtcNow > nextBroadcastCountdownTime)
{
Toast.Next(Toast.Status.Loading, "TOAST_TIER_PROCEEDING_TO_NEXT_STAGE_X".Get((int) Math.Ceiling((proceedToNextStageTime - DateTimeOffset.UtcNow).TotalSeconds)));
if (broadcastCount >= BroadcastAddTimes.Length)
{
nextBroadcastCountdownTime = DateTimeOffset.MaxValue;
return;
}
nextBroadcastCountdownTime = DateTimeOffset.UtcNow.AddSeconds(BroadcastAddTimes[broadcastCount++]);
}
}
private void OnApplicationPause(bool pauseStatus)
{
// Resuming?
if (!pauseStatus && State == ScreenState.Active)
{
if (DateTimeOffset.UtcNow > proceedToNextStageTime)
{
// Fail!
Dialog.PromptAlert("DIALOG_TIER_TIMED_OUT".Get());
retryButton.StartPulsing();
nextStageButton.State = CircleButtonState.GoBack;
nextStageButton.interactableMonoBehavior.onPointerClick.AddListener(_ =>
{
nextStageButton.StopPulsing();
GoBack();
});
retryButton.State = CircleButtonState.Retry;
retryButton.interactableMonoBehavior.onPointerClick.AddListener(_ =>
{
retryButton.StopPulsing();
Retry();
});
proceedToNextStageTime = DateTimeOffset.MaxValue;
}
}
}
public async void Retry()
{
if (State == ScreenState.Inactive) return;
// TODO: Refactor with TierResult?
State = ScreenState.Inactive;
ProfileWidget.Instance.FadeOut();
LoopAudioPlayer.Instance.StopAudio(0.4f);
Context.AudioManager.Get("LevelStart").Play();
Context.SelectedGameMode = GameMode.Tier;
Context.TierState = new TierState(tierState.Tier);
var sceneLoader = new SceneLoader("Game");
sceneLoader.Load();
await UniTask.Delay(TimeSpan.FromSeconds(0.8f));
NavigationBackdrop.Instance.FadeBrightness(0, 0.8f);
await UniTask.Delay(TimeSpan.FromSeconds(0.8f));
if (!sceneLoader.IsLoaded) await UniTask.WaitUntil(() => sceneLoader.IsLoaded);
sceneLoader.Activate();
}
public async void NextStage()
{
if (State == ScreenState.Inactive) return;
State = ScreenState.Inactive;
ProfileWidget.Instance.FadeOut();
LoopAudioPlayer.Instance.StopAudio(0.4f);
Context.AudioManager.Get("LevelStart").Play();
var sceneLoader = new SceneLoader("Game");
sceneLoader.Load();
await UniTask.Delay(TimeSpan.FromSeconds(0.8f));
NavigationBackdrop.Instance.FadeBrightness(0, 0.8f);
await UniTask.Delay(TimeSpan.FromSeconds(0.8f));
if (!sceneLoader.IsLoaded) await UniTask.WaitUntil(() => sceneLoader.IsLoaded);
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.GameCover);
sceneLoader.Activate();
}
public void GoBack()
{
NavigationBackdrop.Instance.FadeBrightness(0, onComplete: () =>
{
TranslucentCover.Clear();
NavigationBackdrop.Instance.FadeBrightness(1);
});
Context.TierState = null;
Context.ScreenManager.ChangeScreen(TierSelectionScreen.Id, ScreenTransition.Out, willDestroy: true);
Context.AudioManager.Get("LevelStart").Play();
}
public void Finish()
{
Context.ScreenManager.ChangeScreen(TierResultScreen.Id, ScreenTransition.Out, willDestroy: true, addTargetScreenToHistory: false);
Context.AudioManager.Get("LevelStart").Play();
}
public override void OnScreenChangeFinished(Screen from, Screen to)
{
base.OnScreenChangeFinished(from, to);
if (from == this && to is TierSelectionScreen)
{
// Go back to tier selection, so clear game cover
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.GameCover);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Orleans;
using Orleans.Concurrency;
using Orleans.Runtime;
using UnitTests.GrainInterfaces;
using Orleans.Runtime.Configuration;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
namespace UnitTests.Grains
{
internal class StressTestGrain : Grain, IStressTestGrain
{
private string label;
private ILogger logger;
public StressTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
if (this.GetPrimaryKeyLong() == -2)
throw new ArgumentException("Primary key cannot be -2 for this test case");
this.label = this.GetPrimaryKeyLong().ToString();
this.logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<string> GetLabel()
{
return Task.FromResult(this.label);
}
public Task SetLabel(string label)
{
this.label = label;
//logger.Info("SetLabel {0} received", label);
return Task.CompletedTask;
}
public Task<IStressTestGrain> GetGrainReference()
{
return Task.FromResult(this.AsReference<IStressTestGrain>());
}
public Task PingOthers(long[] others)
{
List<Task> promises = new List<Task>();
foreach (long key in others)
{
IStressTestGrain g1 = this.GrainFactory.GetGrain<IStressTestGrain>(key);
Task promise = g1.GetLabel();
promises.Add(promise);
}
return Task.WhenAll(promises);
}
public Task<List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>> LookUpMany(
SiloAddress destination, List<Tuple<GrainId, int>> grainAndETagList, int retries = 0)
{
var list = new List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>();
foreach (Tuple<GrainId, int> tuple in grainAndETagList)
{
GrainId id = tuple.Item1;
var reply = new List<Tuple<SiloAddress, ActivationId>>();
for (int i = 0; i < 10; i++)
{
var siloAddress = SiloAddress.New(new IPEndPoint(ConfigUtilities.GetLocalIPAddress(),0), 0);
reply.Add(new Tuple<SiloAddress, ActivationId>(siloAddress, ActivationId.NewId()));
}
list.Add(new Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>(id, 3, reply));
}
return Task.FromResult(list);
}
public Task<byte[]> Echo(byte[] data)
{
return Task.FromResult(data);
}
public Task Ping(byte[] data)
{
return Task.CompletedTask;
}
public async Task PingWithDelay(byte[] data, TimeSpan delay)
{
await Task.Delay(delay);
}
public Task Send(byte[] data)
{
return Task.CompletedTask;
}
public Task DeactivateSelf()
{
DeactivateOnIdle();
return Task.CompletedTask;
}
}
[Reentrant]
internal class ReentrantStressTestGrain : Grain, IReentrantStressTestGrain
{
private string label;
private ILogger logger;
public ReentrantStressTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.label = this.GetPrimaryKeyLong().ToString();
this.logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(this.RuntimeIdentity);
}
public Task<byte[]> Echo(byte[] data)
{
return Task.FromResult(data);
}
public Task Ping(byte[] data)
{
return Task.CompletedTask;
}
public async Task PingWithDelay(byte[] data, TimeSpan delay)
{
await Task.Delay(delay);
}
public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain,
bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
public async Task InterleavingConsistencyTest(int numItems)
{
TimeSpan delay = TimeSpan.FromMilliseconds(1);
List<Task> getFileMetadataPromises = new List<Task>(numItems*2);
Dictionary<int, string> fileMetadatas = new Dictionary<int, string>(numItems*2);
for (int i = 0; i < numItems; i++)
{
int capture = i;
Func<Task> func = (
async () =>
{
await Task.Delay(ThreadSafeRandom.NextTimeSpan(delay));
int fileMetadata = capture;
if ((fileMetadata%2) == 0)
{
fileMetadatas.Add(fileMetadata, fileMetadata.ToString());
}
});
getFileMetadataPromises.Add(func());
}
await Task.WhenAll(getFileMetadataPromises.ToArray());
List<Task> tagPromises = new List<Task>(fileMetadatas.Count);
foreach (KeyValuePair<int, string> keyValuePair in fileMetadatas)
{
int fileId = keyValuePair.Key;
Func<Task> func = (async () =>
{
await Task.Delay(ThreadSafeRandom.NextTimeSpan(delay));
_ = fileMetadatas[fileId];
});
tagPromises.Add(func());
}
await Task.WhenAll(tagPromises);
// sort the fileMetadatas according to fileIds.
List<string> results = new List<string>(fileMetadatas.Count);
for (int i = 0; i < numItems; i++)
{
string metadata;
if (fileMetadatas.TryGetValue(i, out metadata))
{
results.Add(metadata);
}
}
if (numItems != results.Count)
{
//throw new OrleansException(String.Format("numItems != results.Count, {0} != {1}", numItems, results.Count));
}
}
}
[Reentrant]
[StatelessWorker]
public class ReentrantLocalStressTestGrain : Grain, IReentrantLocalStressTestGrain
{
private string label;
private ILogger logger;
public ReentrantLocalStressTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.label = this.GetPrimaryKeyLong().ToString();
this.logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<byte[]> Echo(byte[] data)
{
return Task.FromResult(data);
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(this.RuntimeIdentity);
}
public Task Ping(byte[] data)
{
return Task.CompletedTask;
}
public async Task PingWithDelay(byte[] data, TimeSpan delay)
{
await Task.Delay(delay);
}
public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain,
bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
}
}
| |
// -------------------------------------------------------------------------------------------
// <copyright file="PageMain.aspx.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// -------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.layouts.Ecommerce.Demo
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Security;
using System.Web.UI;
using Analytics.Components;
using Catalogs;
using Classes;
using Diagnostics;
using DomainModel.Configurations;
using DomainModel.Users;
using Examples;
using Globalization;
using Links;
using SecurityModel;
using Sitecore.Data.Items;
using Sitecore.Security.Authentication;
using Sitecore.Web;
/// <summary>
/// The main page code behind.
/// </summary>
public partial class PageMain : Page
{
/// <summary>
/// Gets or sets the name of the user.
/// </summary>
/// <value>The name of the user.</value>
protected string UserName { get; set; }
/// <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="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
AddToShoppingCartFromPostback(this.Request.Form);
}
if (Sitecore.Context.Item != null)
{
this.scID.Attributes["content"] = Sitecore.Context.Item.ID.ToString();
}
if (Sitecore.Context.Item != null &&
Sitecore.Context.Item.Template != null &&
Sitecore.Context.Item.Template.Name.Equals("Home"))
{
this.pageContainer.Attributes.Add("class", "home_page");
}
}
/// <summary>
/// Adds to shopping cart from postback.
/// </summary>
/// <param name="form">The form.</param>
private static void AddToShoppingCartFromPostback(NameValueCollection form)
{
// firefox workaround
var btns = new List<string>();
foreach (var key in form.AllKeys)
{
if (!key.StartsWith("btn"))
{
continue;
}
var id = key.Replace(".x", string.Empty).Replace(".y", string.Empty);
if (!btns.Contains(id))
{
btns.Add(id);
}
}
// firefox workaround siden img knappers postes 3 ganger
foreach (var id in btns)
{
var arr = id.Split('_');
var command = string.Empty;
var code = string.Empty;
if (arr.Length == 3)
{
command = arr[1];
code = arr[2];
}
// qty
var qty = form["quantity"];
if (string.IsNullOrEmpty(qty))
{
qty = "1";
}
if (!string.IsNullOrEmpty(qty) && !string.IsNullOrEmpty(code))
{
switch (command)
{
case "add":
ShoppingCartWebHelper.AddToShoppingCart(code, qty);
break;
case "del":
ShoppingCartWebHelper.DeleteFromShoppingCart(code);
break;
case "delpl":
ShoppingCartWebHelper.DeleteProductLineFromShoppingCart(code);
break;
}
}
}
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// Login info
var membershipUser = Membership.GetUser();
if (membershipUser != null)
{
this.UserName = membershipUser.UserName.Replace(Sitecore.Context.Domain.Name + @"\", string.Empty);
}
var isLoggedIn = Utils.MainUtil.IsLoggedIn();
this.liStatusNotLoggedIn.Visible = !isLoggedIn;
this.liStatusLoggedIn.Visible = isLoggedIn;
this.liMypage.Visible = isLoggedIn;
this.btnLogIn.Visible = !isLoggedIn;
this.btnLogOut.Visible = isLoggedIn;
this.lblLogedInAs.Text = string.Format(Translate.Text(Sitecore.Ecommerce.Examples.Texts.YouAreLoggedInAs), this.UserName);
}
/// <summary>
/// Votes the clicked.
/// </summary>
/// <returns></returns>
internal static bool VoteClicked()
{
return NicamHelper.SafeRequest("VoteButton").Equals("VoteButton");
}
/// <summary>
/// Handles the OnClick event of the btnLogIn control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnLogIn_OnClick(object sender, EventArgs e)
{
AnalyticsUtil.AuthentificationClickedLoginLink();
GeneralSettings generalSettings = Sitecore.Ecommerce.Context.Entity.GetConfiguration<GeneralSettings>();
this.Response.Redirect(Utils.ItemUtil.GetItemUrl(generalSettings.MainLoginLink, true));
}
/// <summary>
/// Handles the OnClick event of the btnLogOut control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnLogOut_OnClick(object sender, EventArgs e)
{
ICustomerManager<CustomerInfo> customerManager = Sitecore.Ecommerce.Context.Entity.Resolve<ICustomerManager<CustomerInfo>>();
AnalyticsUtil.AuthentificationUserLoggedOut(customerManager.CurrentUser.NickName);
AuthenticationManager.Logout();
customerManager.ResetCurrentUser();
var url = string.Empty;
try
{
if (Sitecore.Context.Item.Security.CanRead(Sitecore.Security.Accounts.User.Current))
{
var qs = WebUtil.GetQueryString();
Item catalogItem = null;
using (new SecurityDisabler())
{
catalogItem = Sitecore.Ecommerce.Context.Entity.Resolve<VirtualProductResolver>().ProductCatalogItem;
}
if (catalogItem == null)
{
url = LinkManager.GetItemUrl(Sitecore.Context.Item);
}
else
{
url = Sitecore.Ecommerce.Context.Entity.Resolve<VirtualProductResolver>().GetVirtualProductUrl(catalogItem, Sitecore.Context.Item);
}
qs = qs.TrimStart('?');
qs = (qs != string.Empty) ? "?" + qs : string.Empty;
url = string.Concat(url, qs);
}
else
{
url = "/";
}
}
catch (Exception err)
{
Log.Warn(err.Message, err);
}
this.Response.Redirect(url);
}
}
}
| |
/**
* \file Player.cs
*
* \brief Implements the player class.
*/
using System;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.Core.Input;
using API.Framework;
using API;
namespace SpaceShips
{
public class Player : GameActor
{
UInt32 cnt=0;
Int16 shootTime=0;
int speed = 3;
/**
* Enum class for player status
*/
public enum PlayerStatus
{
Normal, /**< Play status */
Explosion, /**< Hit status */
Invincible, /**< Respawn status */
GameOver, /**< End status */
};
/**
* \brief Player status.
*/
public PlayerStatus playerStatus;
public int ship;
/**
* \fn Player(Game gs, string name)
*
* \brief Default constructor.
*
* Set the status to NoUse and load the default ship image.
*
* \param gs Variable that contains the game framework class.
* \param name Name of the object.
*/
public Player(Game gs, string name) : base(gs, name)
{
this.Status = Actor.ActorStatus.NoUse;
// this.spriteB = new SpriteB(gs.dicTextureInfo["assets/image/player/"+ship+".png"]);
}
/**
* \fn Initialize()
*
* \brief Player initialize.
*
* Put player tu normal status and at the middle right screen. Also put the counter to 0.
*/
public void Initialize(int ship)
{
this.spriteB = new SpriteB(gs.dicTextureInfo["assets/image/player/ship"+ship+".png"]);
this.ship = ship;
this.playerStatus = PlayerStatus.Normal;
this.Status = Actor.ActorStatus.Action;
this.spriteB.Center.X = 0.5f;
this.spriteB.Center.Y = 0.5f;
this.spriteB.Rotation = (-90)/180.0f*FMath.PI;
this.spriteB.Scale = new Vector2(0.35f, 0.35f);
this.collision.X = 6;
this.collision.Y = 6;
spriteB.Position.X=gs.rectScreen.Width*3/4;
spriteB.Position.Y=gs.rectScreen.Height*1/2;
spriteB.Position.Z=0.1f;
cnt=0;
}
/**
* \fn Update()
*
* \brief Override update method.
*
* Handle the input and change the state if it is hit.
* If the game is in debug mode it will print the position of the player.
*/
public override void Update ()
{
#if DEBUG
gs.debugString.WriteLine(string.Format("Position=({0},{1})\n", spriteB.Position.X, spriteB.Position.Y));
#endif
var gamePadData = GamePad.GetData(0);
if(this.playerStatus == PlayerStatus.Normal || this.playerStatus == PlayerStatus.Invincible)
{
if(this.playerStatus == PlayerStatus.Invincible && ++cnt > 120)
{
this.playerStatus= PlayerStatus.Normal;
this.spriteB.SetColor(Vector4.One);
cnt=0;
}
if (gs.playerInput.LeftRightAxis() != 0.0f)
{
spriteB.Position.X += gs.playerInput.LeftRightAxis() * speed;
if (spriteB.Position.X < spriteB.Width/2.0f)
spriteB.Position.X=spriteB.Width/2.0f;
else if (spriteB.Position.X> gs.rectScreen.Width - spriteB.Width/2.0f)
spriteB.Position.X=gs.rectScreen.Width - spriteB.Width/2.0f;
}
if (gs.playerInput.UpDownAxis() != 0.0f)
{
spriteB.Position.Y += gs.playerInput.UpDownAxis() * speed;
if (spriteB.Position.Y < spriteB.Height/2.0f)
spriteB.Position.Y =spriteB.Height/2.0f;
else if (spriteB.Position.Y > gs.rectScreen.Height - spriteB.Height/2.0f)
spriteB.Position.Y=gs.rectScreen.Height - spriteB.Height/2.0f;
}
// Shoot bullets.
if (gs.playerInput.AttackButton() && (this.playerStatus == PlayerStatus.Normal ||
this.playerStatus == PlayerStatus.Invincible))
{
++shootTime;
Actor bulletManager=gs.Root.Search("bulletManager");
if (shootTime < 5)
{
gs.audioManager.playSound("laser");
if (ship == 1)
{
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-5,
this.spriteB.Position.Y-30, 0.4f)));
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-5,
this.spriteB.Position.Y+30, 0.4f)));
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-5,
this.spriteB.Position.Y, 0.4f)));
}
else if (ship == 2)
{
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-20,
this.spriteB.Position.Y-10, 0.4f), -8, -2));
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-20,
this.spriteB.Position.Y+10, 0.4f), -8, 2));
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-20,
this.spriteB.Position.Y, 0.4f)));
}
else
{
float incY = 0;
if (gs.playerInput.UpDownAxis() < 0)
incY = 5*gs.playerInput.UpDownAxis();
else if (gs.playerInput.UpDownAxis() > 0)
incY = 5*gs.playerInput.UpDownAxis();
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-10,
this.spriteB.Position.Y-21, 0.4f), -8, incY));
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-10,
this.spriteB.Position.Y+19, 0.4f), -8, incY));
bulletManager.AddChild( new Bullet(gs, "Bullet",new Vector3(this.spriteB.Position.X-20,
this.spriteB.Position.Y-1, 0.4f)));
}
}
}
else
{
shootTime=0;
}
}
else if(this.playerStatus == PlayerStatus.Explosion)
{
this.Status = Actor.ActorStatus.UpdateOnly;
if( ++cnt > 60)
{
if( gs.NumShips > 0)
{
this.spriteB.Position.X=gs.rectScreen.Width*3/4;
this.spriteB.Position.Y=gs.rectScreen.Height*1/2;
this.Status = Actor.ActorStatus.Action;
this.playerStatus = PlayerStatus.Invincible;
cnt=0;
}
else
{
this.playerStatus = PlayerStatus.GameOver;
this.Status = Actor.ActorStatus.UpdateOnly;
}
}
}
if(this.playerStatus == PlayerStatus.Invincible)
{
// Flash in translucence.
if( gs.appCounter % 2 == 0)
this.spriteB.SetColor(1.0f, 1.0f, 1.0f, 0.75f);
else
this.spriteB.SetColor(1.0f, 1.0f, 1.0f, 0.2f);
}
base.Update();
}
}
}
| |
using Lumos.GUI;
using Lumos.GUI.Input;
using LumosLIB.Kernel.Log;
using LumosLIB.Tools;
using org.dmxc.lumos.Kernel.Resource;
using System;
using System.ComponentModel;
using System.Linq;
using WeifenLuo.WinFormsUI.Docking;
using System.Xml.Linq;
namespace MidiPlugin
{
public class RuleSet : IDisposable
{
public class RuleEventArgs : EventArgs
{
public DeviceRule Rule
{
get;
set;
}
}
private const int StatusMask = -256;
protected const int DataMask = 255;
private const int Data1Mask = -65281;
private const int Data2Mask = 65535;
private static ILumosLog log = LumosLogger.getInstance(typeof(RuleSet));
private string name;
public MidiInput InputDevice;
public MidiOutput OutputDevice;
public bool InputUsed;
public bool OutputUsed;
public BindingList<DeviceRule> Rules;
private RuleSetEditForm editWindow;
public event EventHandler<MidiEventArgs> SendMessage;
public event EventHandler NameChanged;
public event EventHandler<RuleSet.RuleEventArgs> RuleAdded;
public event EventHandler<RuleSet.RuleEventArgs> RuleDeleted;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
if (this.NameChanged != null)
{
this.NameChanged(this, null);
}
}
}
public int RuleCount
{
get
{
return this.Rules.Count;
}
}
public string InputDeviceID
{
get
{
return (this.InputDevice != null) ? this.InputDevice.DeviceID.ToString() : string.Empty;
}
set
{
if (!this.InputUsed)
{
if (this.InputDevice != null)
{
this.InputDevice.MessageReceived -= new EventHandler<MidiEventArgs>(this.HandleMessageReceived);
}
DeviceId devId = DeviceId.Parse(value);
if (devId != null && ContextManager.DeviceInformation.InputDevices.Any((MidiInput i) => i.DeviceID.Equals(devId)))
{
this.InputDevice = ContextManager.DeviceInformation.InputDevices.First((MidiInput i) => i.DeviceID.Equals(devId));
this.InputDevice.MessageReceived += new EventHandler<MidiEventArgs>(this.HandleMessageReceived);
}
else
{
this.InputDevice = null;
}
}
}
}
public string OutputDeviceID
{
get
{
return (this.OutputDevice != null) ? this.OutputDevice.DeviceID.ToString() : string.Empty;
}
set
{
if (!this.OutputUsed)
{
DeviceId devId = DeviceId.Parse(value);
if (devId != null && ContextManager.DeviceInformation.OutputDevices.Any((MidiOutput i) => i.DeviceID.Equals(devId)))
{
this.OutputDevice = ContextManager.DeviceInformation.OutputDevices.First((MidiOutput i) => i.DeviceID.Equals(devId));
}
else
{
this.OutputDevice = null;
}
}
}
}
public string GUID
{
get;
private set;
}
[Browsable(false)]
public MidiInputLayer InputLayer
{
get;
private set;
}
public static RuleSet Load(ManagedTreeItem mti)
{
RuleSet ret = new RuleSet(false);
Pair<string, object> nameAt = mti.Attributes.FirstOrDefault((Pair<string, object> i) => i.Left == "Name");
ret.Name = ((nameAt != null) ? ((string)nameAt.Right) : "");
Pair<string, object> inp = mti.Attributes.FirstOrDefault((Pair<string, object> i) => i.Left == "InputDeviceID");
ret.InputDeviceID = ((inp != null) ? ((string)inp.Right) : null);
Pair<string, object> outp = mti.Attributes.FirstOrDefault((Pair<string, object> i) => i.Left == "OutputDeviceID");
ret.OutputDeviceID = ((outp != null) ? ((string)outp.Right) : null);
if (mti.hasValue<string>("GUID"))
{
ret.GUID = mti.getValue<string>("GUID");
}
else
{
ret.GUID = Guid.NewGuid().ToString();
}
ret.genInputLayer();
foreach (ManagedTreeItem item in mti.GetChildren("Rule"))
{
if (DeviceRule.Load(ret, item) == null)
{
RuleSet.log.Warn("Failed to load DeviceRule in RuleSet {0}, Invalid Cast and/or constructor missing!", ret.Name);
}
}
foreach (DeviceRule item2 in ret.Rules)
{
item2.UpdateBacktrack();
}
return ret;
}
private void genInputLayer()
{
this.InputLayer = new MidiInputLayer(InputLayerManager.getInstance().SessionName, this);
}
public void Save(ManagedTreeItem mti)
{
ContextManager.log.Debug("Saving RuleSet {0}", Name);
mti.setValue<string>("Name", this.Name);
mti.setValue<string>("InputDeviceID", this.InputDeviceID);
mti.setValue<string>("OutputDeviceID", this.OutputDeviceID);
mti.setValue<string>("GUID", this.GUID);
foreach (DeviceRule rule in this.Rules)
{
ManagedTreeItem mtir = new ManagedTreeItem("Rule");
rule.Save(mtir);
mti.AddChild(mtir);
}
}
protected void OnSendMessage(object s, MidiEventArgs m)
{
if (this.OutputDevice != null)
{
this.OutputUsed = true;
int msg = (m.m.channel + m.m.message) + (m.m.data1 << 8) + (m.m.data2 << 16) - 1;
try
{
this.OutputDevice.OutputDevice.Send(msg);
}
catch(Exception)
{
ContextManager.log.Warn("Error sending Midi Message to device {0}, message: {1}.{2}, {3},{4}", OutputDevice.DeviceID, m.m.channel, m.m.message, m.m.data1, m.m.data2);
}
this.OutputUsed = false;
}
if (this.SendMessage != null)
{
this.SendMessage(this, m);
}
}
public RuleSet() : this(true)
{
}
private RuleSet(bool genGuid)
{
this.Rules = new BindingList<DeviceRule>();
this.Name = "New RuleSet";
this.editWindow = new RuleSetEditForm(this);
if (genGuid)
{
this.GUID = Guid.NewGuid().ToString();
this.genInputLayer();
}
}
private void HandleMessageReceived(object s, MidiEventArgs e)
{
foreach (DeviceRule item in this.Rules)
{
item.Process(e.m);
}
}
public DeviceRule createRule(string t)
{
var type = ContextManager.AssemblyHelper.DeviceRuleTypes.FirstOrDefault(j => j.FullName == t);
if (type == null) return null;
var obj = Activator.CreateInstance(type) as DeviceRule;
return obj;
}
public void AddRule(DeviceRule r)
{
this.Rules.Add(r);
r.MidiMessageSend += new EventHandler<MidiEventArgs>(this.OnSendMessage);
this.OnRuleAdded(r);
}
public void DeleteRule(DeviceRule r)
{
this.Rules.Remove(r);
r.MidiMessageSend -= new EventHandler<MidiEventArgs>(this.OnSendMessage);
this.OnRuleDeleted(r);
}
public void OpenEditWindow()
{
WindowManager.getInstance().ShowWindow(this.editWindow, DockState.Float);
}
public void Dispose()
{
this.editWindow.Dispose();
}
protected void OnRuleAdded(DeviceRule r)
{
if (this.RuleAdded != null)
{
this.RuleAdded(this, new RuleSet.RuleEventArgs
{
Rule = r
});
}
}
protected void OnRuleDeleted(DeviceRule r)
{
if (this.RuleDeleted != null)
{
this.RuleDeleted(this, new RuleSet.RuleEventArgs
{
Rule = r
});
}
}
public XElement Serialize()
{
var xElement = new XElement("RuleSet");
xElement.Add(new XAttribute("Name", this.name));
foreach (var rule in this.Rules)
{
xElement.Add(rule.Serialize());
}
return xElement;
throw new NotImplementedException();
}
public static RuleSet LoadFromXml(XElement element)
{
var ruleset = new RuleSet(true);
ruleset.name = element.Attribute("Name").Value;
ruleset.genInputLayer();
foreach (var item in element.Elements("Rule"))
{
ruleset.AddRule(DeviceRule.LoadFromXml(item));
}
return ruleset;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using MvcContrib.FluentHtml.Behaviors;
using MvcContrib.FluentHtml.Html;
namespace MvcContrib.FluentHtml.Elements
{
/// <summary>
/// Base class for HTML elements.
/// </summary>
/// <typeparam name="T">The derived class type.</typeparam>
public abstract class Element<T> : IMemberElement where T : Element<T>, IElement
{
protected const string LABEL_FORMAT = "{0}_Label";
private bool doNotAutoLabel;
protected readonly TagBuilder builder;
protected MemberExpression forMember;
protected IEnumerable<IBehaviorMarker> behaviors;
protected readonly IDictionary<object, object> metadata = new Dictionary<object, object>();
protected Element(string tag, MemberExpression forMember, IEnumerable<IBehaviorMarker> behaviors) : this(tag)
{
this.forMember = forMember;
this.behaviors = behaviors;
}
protected Element(string tag)
{
builder = new TagBuilder(tag);
}
/// <summary>
/// TagBuilder object used to generate HTML for elements.
/// </summary>
TagBuilder IElement.Builder
{
get { return builder; }
}
/// <summary>
/// Set the 'id' attribute.
/// </summary>
/// <param name="value">The value of the 'id' attribute.</param>
public virtual T Id(string value)
{
builder.MergeAttribute(HtmlAttribute.Id, value, true);
return (T)this;
}
/// <summary>
/// Add a value to the 'class' attribute.
/// </summary>
/// <param name="classToAdd">The value of the class to add.</param>
public virtual T Class(string classToAdd)
{
builder.AddCssClass(classToAdd);
return (T)this;
}
/// <summary>
/// Set the 'title' attribute.
/// </summary>
/// <param name="value">The value of the 'title' attribute.</param>
public virtual T Title(string value)
{
builder.MergeAttribute(HtmlAttribute.Title, value, true);
return (T)this;
}
/// <summary>
/// Set the 'style' attribute.
/// </summary>
/// <param name="values">A list of funcs, each epxressing a style name value pair. Replace dashes with
/// underscores in style names. For example 'margin-top:10px;' is expressed as 'margin_top => "10px"'.</param>
public virtual T Styles(params Func<string, string>[] values)
{
var sb = new StringBuilder();
foreach (var func in values)
{
sb.AppendFormat("{0}:{1};", func.Method.GetParameters()[0].Name.Replace('_', '-'), func(null));
}
builder.MergeAttribute(HtmlAttribute.Style, sb.ToString());
return (T)this;
}
/// <summary>
/// Set the 'onclick' attribute.
/// </summary>
/// <param name="value">The value for the attribute.</param>
/// <returns></returns>
public virtual T OnClick(string value)
{
builder.MergeAttribute(HtmlEventAttribute.OnClick, value, true);
return (T)this;
}
/// <summary>
/// Set the value of a specified attribute.
/// </summary>
/// <param name="name">The name of the attribute.</param>
/// <param name="value">The value of the attribute.</param>
public virtual T Attr(string name, object value)
{
((IElement)this).SetAttr(name, value);
return (T)this;
}
/// <summary>
/// Generate a label before the element.
/// </summary>
/// <param name="value">The inner text of the label.</param>
/// <param name="class">The value of the 'class' attribute for the label.</param>
public virtual T Label(string value, string @class)
{
((IElement)this).LabelBeforeText = value;
((IElement)this).LabelClass = @class;
return (T)this;
}
/// <summary>
/// Generate a label before the element.
/// </summary>
/// <param name="value">The inner text of the label.</param>
public virtual T Label(string value)
{
((IElement)this).LabelBeforeText = value;
return (T)this;
}
/// <summary>
/// Generate a label after the element.
/// </summary>
/// <param name="value">The inner text of the label.</param>
/// <param name="class">The value of the 'class' attribute for the label.</param>
public virtual T LabelAfter(string value, string @class)
{
((IElement)this).LabelAfterText = value;
((IElement)this).LabelClass = @class;
return (T)this;
}
/// <summary>
/// Generate a label after the element.
/// </summary>
/// <param name="value">The inner text of the label.</param>
public virtual T LabelAfter(string value)
{
((IElement)this).LabelAfterText = value;
return (T)this;
}
/// <summary>
/// If no label has been explicitly set, set the label using the element name.
/// </summary>
public virtual T AutoLabel()
{
((IElement)this).SetAutoLabel();
return (T)this;
}
/// <summary>
/// If no label before has been explicitly set, set the label before using the element name.
/// </summary>
public virtual T AutoLabelAfter()
{
((IElement)this).SetAutoLabelAfter();
return (T)this;
}
/// <summary>
/// Prevent this item from being auto labeled.
/// </summary>
public virtual T DoNotAutoLabel()
{
doNotAutoLabel = true;
return (T)this;
}
public virtual string ToHtmlString()
{
ApplyBehaviors();
PreRender();
var html = RenderLabel(((IElement)this).LabelBeforeText);
html += builder.ToString(((IElement)this).TagRenderMode);
html += RenderLabel(((IElement)this).LabelAfterText);
return html;
}
public sealed override string ToString()
{
return ToHtmlString();
}
#region Explicit IElement members
void IElement.RemoveAttr(string name)
{
builder.Attributes.Remove(name);
}
void IElement.SetAttr(string name, object value)
{
var valueString = value == null ? null : value.ToString();
builder.MergeAttribute(name, valueString, true);
}
string IElement.GetAttr(string name)
{
string result;
builder.Attributes.TryGetValue(name, out result);
return result;
}
string IElement.LabelBeforeText { get; set; }
string IElement.LabelAfterText { get; set; }
string IElement.LabelClass { get; set; }
TagRenderMode IElement.TagRenderMode
{
get { return TagRenderMode; }
}
IDictionary<object, object> IElement.Metadata
{
get { return metadata; }
}
void IElement.SetAutoLabel()
{
if (ShouldAutoLabel())
{
var settings = GetAutoLabelSettings();
((IElement)this).LabelBeforeText = GetAutoLabelText(settings);
((IElement)this).LabelClass = settings == null ? null : settings.LabelCssClass;
}
}
void IElement.SetAutoLabelAfter()
{
if (ShouldAutoLabel())
{
var settings = GetAutoLabelSettings();
((IElement)this).LabelAfterText = GetAutoLabelText(settings);
((IElement)this).LabelClass = settings == null ? null : settings.LabelCssClass;
}
}
MemberExpression IMemberElement.ForMember
{
get { return forMember; }
}
void IElement.AddClass(string classToAdd)
{
builder.AddCssClass(classToAdd);
}
#endregion
protected virtual TagRenderMode TagRenderMode
{
get { return TagRenderMode.Normal; }
}
protected bool ShouldAutoLabel()
{
return ((IElement)this).LabelBeforeText == null && ((IElement)this).LabelAfterText == null && !doNotAutoLabel;
}
protected AutoLabelSettings GetAutoLabelSettings()
{
//TODO: should we throw if there is more than one?
AutoLabelSettings foundSettings = null;
if (behaviors != null)
{
foundSettings = behaviors.Where(x => x is AutoLabelSettings).FirstOrDefault() as AutoLabelSettings;
}
return foundSettings ?? new AutoLabelSettings(false, null, null);
}
protected string GetAutoLabelText(AutoLabelSettings settings)
{
var result = ((IElement)this).GetAttr(HtmlAttribute.Name);
if (result == null)
{
return result;
}
if (settings.UseFullNameForNestedProperties)
{
result = result.Replace('.', ' ');
}
else
{
var lastDot = result.LastIndexOf(".");
if (lastDot >= 0)
{
result = result.Substring(lastDot + 1);
}
}
result = result.PascalCaseToPhrase();
result = RemoveArrayNotationFromPhrase(result);
result = settings.LabelFormat != null
? string.Format(settings.LabelFormat, result)
: result;
return result;
}
protected string RemoveArrayNotationFromPhrase(string phrase)
{
if (phrase.IndexOf("[") >= 0)
{
var words = new List<string>(phrase.Split(' '));
words = words.ConvertAll<string>(RemoveArrayNotation);
phrase = string.Join(" ", words.ToArray());
}
return phrase;
}
protected string RemoveArrayNotation(string s)
{
var index = s.LastIndexOf('[');
return index >= 0
? s.Remove(index)
: s;
}
protected virtual string RenderLabel(string labelText)
{
if (labelText == null)
{
return null;
}
var labelBuilder = GetLabelBuilder();
labelBuilder.SetInnerText(labelText);
return labelBuilder.ToString();
}
protected TagBuilder GetLabelBuilder()
{
var labelBuilder = new TagBuilder(HtmlTag.Label);
if (builder.Attributes.ContainsKey(HtmlAttribute.Id))
{
var id = builder.Attributes[HtmlAttribute.Id];
labelBuilder.MergeAttribute(HtmlAttribute.For, id);
labelBuilder.MergeAttribute(HtmlAttribute.Id, string.Format(LABEL_FORMAT, id));
}
if (!string.IsNullOrEmpty(((IElement)this).LabelClass))
{
labelBuilder.MergeAttribute(HtmlAttribute.Class, ((IElement)this).LabelClass);
}
return labelBuilder;
}
protected void ApplyBehaviors()
{
if (behaviors == null)
{
return;
}
var unorderedBehaviors = behaviors.Where(x => (x is IOrderedBehavior) == false);
unorderedBehaviors.ApplyTo(this);
var orderedBehaviors = behaviors.Where(x => x is IOrderedBehavior).OrderBy(x => ((IOrderedBehavior)x).Order);
orderedBehaviors.ApplyTo(this);
}
protected virtual void PreRender() { }
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.NHibernateIntegration.Saga
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Logging;
using MassTransit.Saga;
using NHibernate;
using NHibernate.Exceptions;
using Pipeline;
using Util;
public class NHibernateSagaRepository<TSaga> :
ISagaRepository<TSaga>,
IQuerySagaRepository<TSaga>
where TSaga : class, ISaga
{
static readonly ILog _log = Logger.Get<NHibernateSagaRepository<TSaga>>();
readonly ISessionFactory _sessionFactory;
System.Data.IsolationLevel _insertIsolationLevel;
public NHibernateSagaRepository(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
_insertIsolationLevel = System.Data.IsolationLevel.ReadCommitted;
}
public NHibernateSagaRepository(ISessionFactory sessionFactory, System.Data.IsolationLevel isolationLevel)
{
_sessionFactory = sessionFactory;
_insertIsolationLevel = isolationLevel;
}
public async Task<IEnumerable<Guid>> Find(ISagaQuery<TSaga> query)
{
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
using (ISession session = _sessionFactory.OpenSession())
{
IList<Guid> result = session.QueryOver<TSaga>()
.Where(query.FilterExpression)
.Select(x => x.CorrelationId)
.List<Guid>();
scope.Complete();
return result;
}
}
void IProbeSite.Probe(ProbeContext context)
{
ProbeContext scope = context.CreateScope("sagaRepository");
scope.Set(new
{
Persistence = "nhibernate",
Entities = _sessionFactory.GetAllClassMetadata().Select(x => x.Value.EntityName).ToArray()
});
}
async Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
{
if (!context.CorrelationId.HasValue)
throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T));
Guid sagaId = context.CorrelationId.Value;
using (ISession session = _sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
bool inserted = false;
TSaga instance;
if (policy.PreInsertInstance(context, out instance))
inserted = PreInsertSagaInstance<T>(session, instance, inserted);
try
{
if (instance == null)
instance = session.Get<TSaga>(sagaId, LockMode.Upgrade);
if (instance == null)
{
var missingSagaPipe = new MissingPipe<T>(session, next);
await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
}
else
{
if (_log.IsDebugEnabled)
_log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName);
var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance);
await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false);
if (inserted && !sagaConsumeContext.IsCompleted)
session.Update(instance);
}
if (transaction.IsActive)
transaction.Commit();
}
catch (Exception)
{
if (transaction.IsActive)
transaction.Rollback();
throw;
}
}
}
public async Task SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
where T : class
{
using (ISession session = _sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
try
{
IList<TSaga> instances = session.QueryOver<TSaga>()
.Where(context.Query.FilterExpression)
.List<TSaga>();
if (instances.Count == 0)
{
var missingSagaPipe = new MissingPipe<T>(session, next);
await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
}
else
await Task.WhenAll(instances.Select(instance => SendToInstance(context, policy, instance, next, session))).ConfigureAwait(false);
// TODO partial failure should not affect them all
if (transaction.IsActive)
transaction.Commit();
}
catch (SagaException sex)
{
if (_log.IsErrorEnabled)
_log.Error("Saga Exception Occurred", sex);
}
catch (Exception ex)
{
if (_log.IsErrorEnabled)
_log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", ex);
if (transaction.IsActive)
transaction.Rollback();
throw new SagaException(ex.Message, typeof(TSaga), typeof(T), Guid.Empty, ex);
}
}
}
static bool PreInsertSagaInstance<T>(ISession session, TSaga instance, bool inserted)
{
try
{
session.Save(instance);
session.Flush();
inserted = true;
_log.DebugFormat("SAGA:{0}:{1} Insert {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId,
TypeMetadataCache<T>.ShortName);
}
catch (GenericADOException ex)
{
if (_log.IsDebugEnabled)
{
_log.DebugFormat("SAGA:{0}:{1} Dupe {2} - {3}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId,
TypeMetadataCache<T>.ShortName, ex.Message);
}
}
return inserted;
}
async Task SendToInstance<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, TSaga instance,
IPipe<SagaConsumeContext<TSaga, T>> next, ISession session)
where T : class
{
try
{
if (_log.IsDebugEnabled)
_log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName);
var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance);
await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false);
}
catch (SagaException)
{
throw;
}
catch (Exception ex)
{
throw new SagaException(ex.Message, typeof(TSaga), typeof(T), instance.CorrelationId, ex);
}
}
/// <summary>
/// Once the message pipe has processed the saga instance, add it to the saga repository
/// </summary>
/// <typeparam name="TMessage"></typeparam>
class MissingPipe<TMessage> :
IPipe<SagaConsumeContext<TSaga, TMessage>>
where TMessage : class
{
readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _next;
readonly ISession _session;
public MissingPipe(ISession session, IPipe<SagaConsumeContext<TSaga, TMessage>> next)
{
_session = session;
_next = next;
}
void IProbeSite.Probe(ProbeContext context)
{
_next.Probe(context);
}
public async Task Send(SagaConsumeContext<TSaga, TMessage> context)
{
if (_log.IsDebugEnabled)
{
_log.DebugFormat("SAGA:{0}:{1} Added {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId,
TypeMetadataCache<TMessage>.ShortName);
}
SagaConsumeContext<TSaga, TMessage> proxy = new NHibernateSagaConsumeContext<TSaga, TMessage>(_session, context, context.Saga);
await _next.Send(proxy).ConfigureAwait(false);
if (!proxy.IsCompleted)
_session.Save(context.Saga);
}
}
}
}
| |
/*
* ArrayPrototype.cs - Prototype object for "Array" objects.
*
* Copyright (C) 2003 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 Microsoft.JScript
{
using System;
using System.Text;
using Microsoft.JScript.Vsa;
public class ArrayPrototype : ArrayObject
{
// Constructor.
internal ArrayPrototype(ObjectPrototype parent, EngineInstance inst)
: base(parent)
{
// Add the builtin "Array" properties to the prototype.
Put("constructor", inst.GetArrayConstructor());
AddBuiltin(inst, "concat");
AddBuiltin(inst, "join");
AddBuiltin(inst, "pop");
AddBuiltin(inst, "push");
AddBuiltin(inst, "reverse");
AddBuiltin(inst, "shift");
AddBuiltin(inst, "slice");
AddBuiltin(inst, "sort");
AddBuiltin(inst, "splice");
AddBuiltin(inst, "toLocaleString");
AddBuiltin(inst, "toString");
AddBuiltin(inst, "unshift");
}
// Get the "Array" class constructor. Don't use this.
public static ArrayConstructor constructor
{
get
{
return EngineInstance.Default.GetArrayConstructor();
}
}
// Concatenate arrays together.
[JSFunction(JSFunctionAttributeEnum.HasThisObject |
JSFunctionAttributeEnum.HasVarArgs |
JSFunctionAttributeEnum.HasEngine, JSBuiltin.Array_concat)]
public static ArrayObject concat(Object thisob, VsaEngine engine,
params Object[] args)
{
// TODO
return null;
}
// Join the elements together into a string.
[JSFunction(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.Array_join)]
public static String join(Object thisob, Object separator)
{
String sep;
StringBuilder builder;
if(separator is Missing)
{
sep = ",";
}
else
{
sep = Convert.ToString(separator);
}
builder = new StringBuilder();
// TODO
return builder.ToString();
}
// Pop an element from the end of an array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.Array_pop)]
public static Object pop(Object thisob)
{
// TODO
return thisob;
}
// Push elements onto the end of an array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject |
JSFunctionAttributeEnum.HasVarArgs, JSBuiltin.Array_push)]
public static long push(Object thisob, params Object[] args)
{
// TODO
return 0;
}
// Reverse the elements in an array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject,
JSBuiltin.Array_reverse)]
public static Object reverse(Object thisob)
{
// TODO
return thisob;
}
// Shift the elements in an array down one, returning the first.
[JSFunction(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.Array_shift)]
public static Object shift(Object thisob)
{
// TODO
return null;
}
// Slice a sub-array out of an array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject |
JSFunctionAttributeEnum.HasEngine, JSBuiltin.Array_slice)]
public static ArrayObject slice(Object thisob, VsaEngine engine,
double start, Object end)
{
// TODO
return null;
}
// Sort the contents of an array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.Array_sort)]
public static Object sort(Object thisob, Object function)
{
// TODO
return thisob;
}
// Split an array into the middle of another array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject |
JSFunctionAttributeEnum.HasVarArgs |
JSFunctionAttributeEnum.HasEngine, JSBuiltin.Array_splice)]
public static ArrayObject splice(Object thisob, VsaEngine engine,
double start, double deleteCnt,
params Object[] args)
{
// TODO
return null;
}
// Convert the contents of an array into a locale-based string.
[JSFunction(JSFunctionAttributeEnum.HasThisObject,
JSBuiltin.Array_toLocaleString)]
public static String toLocaleString(Object thisob)
{
// TODO
return null;
}
// Convert the contents of an array into an invariant string.
[JSFunction(JSFunctionAttributeEnum.HasThisObject,
JSBuiltin.Array_toString)]
public static String toString(Object thisob)
{
if(thisob is ArrayObject)
{
return join(thisob, ",");
}
else
{
throw new JScriptException(JSError.NeedArrayObject);
}
}
// Unshift elements back into an array.
[JSFunction(JSFunctionAttributeEnum.HasThisObject |
JSFunctionAttributeEnum.HasEngine, JSBuiltin.Array_unshift)]
public static Object unshift(Object thisob, params Object[] args)
{
// TODO
return null;
}
}; // class ArrayPrototype
// "Lenient" version of the above class which exports all of the
// prototype's properties to the user level.
public class LenientArrayPrototype : ArrayPrototype
{
// Accessible properties.
public new Object constructor;
public new Object concat;
public new Object join;
public new Object pop;
public new Object push;
public new Object reverse;
public new Object shift;
public new Object slice;
public new Object sort;
public new Object splice;
public new Object toLocaleString;
public new Object toString;
public new Object unshift;
// Constructor.
internal LenientArrayPrototype(ObjectPrototype parent, EngineInstance inst)
: base(parent, inst)
{
constructor = inst.GetArrayConstructor();
concat = Get("concat");
join = Get("join");
pop = Get("pop");
push = Get("push");
reverse = Get("reverse");
shift = Get("shift");
slice = Get("slice");
sort = Get("sort");
splice = Get("splice");
toLocaleString = Get("toLocaleString");
toString = Get("toString");
unshift = Get("unshift");
}
}; // class LenientArrayPrototype
}; // namespace Microsoft.JScript
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using UnityEditorInternal;
namespace Cinemachine.Editor
{
[CustomEditor(typeof(CinemachineSmoothPath))]
internal sealed class CinemachineSmoothPathEditor : UnityEditor.Editor
{
private CinemachineSmoothPath Target { get { return target as CinemachineSmoothPath; } }
private static string[] m_excludeFields = null;
private ReorderableList mWaypointList;
void OnEnable()
{
mWaypointList = null;
m_excludeFields = new string[]
{
"m_Script",
SerializedPropertyHelper.PropertyName(() => Target.m_Waypoints)
};
}
public override void OnInspectorGUI()
{
if (mWaypointList == null)
SetupWaypointList();
if (mWaypointList.index >= mWaypointList.count)
mWaypointList.index = mWaypointList.count - 1;
// Ordinary properties
serializedObject.Update();
DrawPropertiesExcluding(serializedObject, m_excludeFields);
serializedObject.ApplyModifiedProperties();
// Waypoints
EditorGUI.BeginChangeCheck();
mWaypointList.DoLayoutList();
if (EditorGUI.EndChangeCheck())
serializedObject.ApplyModifiedProperties();
}
void SetupWaypointList()
{
mWaypointList = new ReorderableList(serializedObject,
serializedObject.FindProperty(() => Target.m_Waypoints),
true, true, true, true);
mWaypointList.drawHeaderCallback = (Rect rect) =>
{ EditorGUI.LabelField(rect, "Waypoints"); };
mWaypointList.drawElementCallback
= (Rect rect, int index, bool isActive, bool isFocused) =>
{ DrawWaypointEditor(rect, index); };
mWaypointList.onAddCallback = (ReorderableList l) =>
{ InsertWaypointAtIndex(l.index); };
}
void DrawWaypointEditor(Rect rect, int index)
{
// Needed for accessing string names of fields
CinemachineSmoothPath.Waypoint def = new CinemachineSmoothPath.Waypoint();
SerializedProperty element = mWaypointList.serializedProperty.GetArrayElementAtIndex(index);
float hSpace = 3;
rect.width -= hSpace; rect.y += 1;
Vector2 numberDimension = GUI.skin.label.CalcSize(new GUIContent("999"));
Rect r = new Rect(rect.position, numberDimension);
if (GUI.Button(r, new GUIContent(index.ToString(), "Go to the waypoint in the scene view")))
{
mWaypointList.index = index;
SceneView.lastActiveSceneView.pivot = Target.EvaluatePosition(index);
SceneView.lastActiveSceneView.size = 4;
SceneView.lastActiveSceneView.Repaint();
}
float floatFieldWidth = EditorGUIUtility.singleLineHeight * 3f;
GUIContent rollLabel = new GUIContent("Roll");
Vector2 labelDimension = GUI.skin.label.CalcSize(rollLabel);
float rollWidth = labelDimension.x + floatFieldWidth;
r.x += r.width + hSpace; r.width = rect.width - (r.width + hSpace + rollWidth);
EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.position), GUIContent.none);
r.x += r.width + hSpace; r.width = rollWidth;
float oldWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = labelDimension.x;
EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.roll), rollLabel);
EditorGUIUtility.labelWidth = oldWidth;
}
void InsertWaypointAtIndex(int indexA)
{
Vector3 pos = Vector3.right;
float roll = 0;
// Get new values from the current indexA (if any)
int numWaypoints = Target.m_Waypoints.Length;
if (indexA < 0)
indexA = numWaypoints - 1;
if (indexA >= 0)
{
int indexB = indexA + 1;
if (Target.m_Looped && indexB >= numWaypoints)
indexB = 0;
if (indexB >= numWaypoints)
{
Vector3 delta = Vector3.right;
if (indexA > 0)
delta = Target.m_Waypoints[indexA].position - Target.m_Waypoints[indexA-1].position;
pos = Target.m_Waypoints[indexA].position + delta;
roll = Target.m_Waypoints[indexA].roll;
}
else
{
// Interpolate
pos = Target.transform.InverseTransformPoint(Target.EvaluatePosition(0.5f + indexA));
roll = Mathf.Lerp(Target.m_Waypoints[indexA].roll, Target.m_Waypoints[indexB].roll, 0.5f);
}
}
Undo.RecordObject(Target, "Add waypoint");
var wp = new CinemachineSmoothPath.Waypoint();
wp.position = pos;
wp.roll = roll;
var list = new List<CinemachineSmoothPath.Waypoint>(Target.m_Waypoints);
list.Insert(indexA + 1, wp);
Target.m_Waypoints = list.ToArray();
InternalEditorUtility.RepaintAllViews();
mWaypointList.index = indexA + 1; // select it
}
void OnSceneGUI()
{
if (mWaypointList == null)
SetupWaypointList();
if (Tools.current == Tool.Move)
{
Matrix4x4 mOld = Handles.matrix;
Color colorOld = Handles.color;
Handles.matrix = Target.transform.localToWorldMatrix;
for (int i = 0; i < Target.m_Waypoints.Length; ++i)
{
DrawSelectionHandle(i);
if (mWaypointList.index == i)
DrawPositionControl(i); // Waypoint is selected
}
Handles.color = colorOld;
Handles.matrix = mOld;
}
}
void DrawSelectionHandle(int i)
{
if (Event.current.button != 1)
{
Vector3 pos = Target.m_Waypoints[i].position;
float size = HandleUtility.GetHandleSize(pos) * 0.2f;
Handles.color = Color.white;
if (Handles.Button(pos, Quaternion.identity, size, size, Handles.SphereHandleCap)
&& mWaypointList.index != i)
{
mWaypointList.index = i;
InternalEditorUtility.RepaintAllViews();
}
// Label it
Handles.BeginGUI();
Vector2 labelSize = new Vector2(
EditorGUIUtility.singleLineHeight * 2, EditorGUIUtility.singleLineHeight);
Vector2 labelPos = HandleUtility.WorldToGUIPoint(pos);
labelPos.y -= labelSize.y / 2;
labelPos.x -= labelSize.x / 2;
GUILayout.BeginArea(new Rect(labelPos, labelSize));
GUIStyle style = new GUIStyle();
style.normal.textColor = Color.black;
style.alignment = TextAnchor.MiddleCenter;
GUILayout.Label(new GUIContent(i.ToString(), "Waypoint " + i), style);
GUILayout.EndArea();
Handles.EndGUI();
}
}
void DrawPositionControl(int i)
{
CinemachineSmoothPath.Waypoint wp = Target.m_Waypoints[i];
EditorGUI.BeginChangeCheck();
Handles.color = Target.m_Appearance.pathColor;
Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
? Quaternion.identity : Quaternion.Inverse(Target.transform.rotation);
float size = HandleUtility.GetHandleSize(wp.position) * 0.1f;
Handles.SphereHandleCap(0, wp.position, rotation, size, EventType.Repaint);
Vector3 pos = Handles.PositionHandle(wp.position, rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Move Waypoint");
wp.position = pos;
Target.m_Waypoints[i] = wp;
Target.InvalidateDistanceCache();
}
}
[DrawGizmo(GizmoType.Active | GizmoType.NotInSelectionHierarchy
| GizmoType.InSelectionHierarchy | GizmoType.Pickable, typeof(CinemachineSmoothPath))]
static void DrawGizmos(CinemachineSmoothPath path, GizmoType selectionType)
{
CinemachinePathEditor.DrawPathGizmo(path,
(Selection.activeGameObject == path.gameObject)
? path.m_Appearance.pathColor : path.m_Appearance.inactivePathColor);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using TestLibrary;
public class StringCompareOrdinal1
{
private const int c_MINI_STRINF_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
StringCompareOrdinal1 sco1 = new StringCompareOrdinal1();
TestLibrary.TestFramework.BeginScenario("StringCompareOrdinal1");
if (sco1.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
retVal = PosTest17() && retVal;
retVal = PosTest18() && retVal;
return retVal;
}
#region Positive Testing
public bool PosTest1()
{
string strA;
string strB;
int ActualResult;
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Two Null CompareOrdinal");
try
{
strA = null;
strB = null;
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult != 0)
{
TestLibrary.TestFramework.LogError("001", "Two Null CompareOrdinal Expected Result is equel 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest2: Null and null string CompareOrdinal");
try
{
strA = null;
strB = "";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("003", "Null and null string CompareOrdinal Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest3: Null and space string CompareOrdinal");
try
{
strA = null;
strB = " ";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0 )
{
TestLibrary.TestFramework.LogError("005", "Null and space string CompareOrdinal Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
int ExpectResult = 0;
TestLibrary.TestFramework.BeginScenario("PosTest4: Null string and a space strings CompareOrdinal");
try
{
strA = "";
strB = " ";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= ExpectResult)
{
TestLibrary.TestFramework.LogError("007", "Null string and a space strings CompareOrdinal Expected Result is less 0;Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string strA;
string strB;
string strBasic;
Random rand = new Random(-55);
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest5: Two like strings embedded different tabs CompareOrdinal");
try
{
char CharTab = '\t';
strBasic = TestLibrary.Generator.GetString(-55, false, c_MINI_STRINF_LEN, c_MAX_STRING_LEN);
strA = strBasic + new string(CharTab, rand.Next(1, 10));
strB = strBasic + new string(CharTab, rand.Next(11, 20));
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("009", "Two like strings embedded different tabs CompareOrdinal Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest6: Two like strings embedded the same tab but differet location CompareOrdinal");
try
{
strA = "hello"+"\t"+"world";
strB = "\t"+"helloworl"+ "d";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult <= 0)
{
TestLibrary.TestFramework.LogError("011", "Two like strings embedded the same tab but differet location CompareOrdinal: Expected Result is greater 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest7: String with upper chars and one with lower chars CompareOrdinal");
try
{
strA = "HELLOWORD";
strB = "helloword";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0 )
{
TestLibrary.TestFramework.LogError("013", "String with upper chars and one with lower chars CompareOrdinal Expected Result is equel 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest8: Two strings with ignorecase same char CompareOrdinal");
try
{
strA = "helloword";
strB = "heLLoword";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult <= 0 )
{
TestLibrary.TestFramework.LogError("015", " Two strings with ignorecase same char CompareOrdinal Expected Result is greate 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest9: Two not null strings CompareOrdinal one");
try
{
strA = "hello-word";
strB = "helloword";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("017", "Two not null strings CompareOrdinal one Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest10: Two not null strings CompareOrdinal two");
try
{
strA = "helloword";
strB = "hello\nword";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult <= 0)
{
TestLibrary.TestFramework.LogError("019", " Two not null strings CompareOrdinal two Expected Result is larger 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest11: Two not null strings CompareOrdinal three");
try
{
strA = "helloword";
strB = "helloword\n";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("021", " Two not null strings CompareOrdinal three Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest12: Two like not null strings CompareOrdinal four");
try
{
strA = "helloword";
strB = "helloword";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult != 0)
{
TestLibrary.TestFramework.LogError("023", " Two not null strings CompareOrdinal four Expected Result is equel 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest13: Two not null strings CompareOrdinal five");
try
{
strA = "\uFF21";
strB = "A";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult <= 0 )
{
TestLibrary.TestFramework.LogError("025", " Two not null strings CompareOrdinal five Expected Result is greater 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest14: Two not null strings CompareOrdinal six");
try
{
strA = "\uD801\uDc00";
strB = "\uD801\uDc28";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("027", " Two not null strings CompareOrdinal six Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest15()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest15: Two not null strings CompareOrdinal seven");
try
{
strA = "\x200b";
strB = "\uFEFF";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("029", " Two not null strings CompareOrdinal seven Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest16()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest16: Two not null strings CompareOrdinal eight");
try
{
strA = "A`";
strB = "\u00c0";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("031", " Two not null strings CompareOrdinal nine Expected Result is less 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest17()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest17: Two not null strings CompareOrdinal nine");
try
{
strA = "\\\\my documents\\my files\\";
strB = @"\\my documents\my files\";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult != 0)
{
TestLibrary.TestFramework.LogError("033", " Two not null strings CompareOrdinal nine Expected Result is equel 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("034", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest18()
{
bool retVal = true;
string strA;
string strB;
int ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest18: tab and fout spaces CompareOrdinal");
try
{
strA = "\t";
strB = " ";
ActualResult = string.CompareOrdinal(strA, strB);
if (ActualResult >= 0)
{
TestLibrary.TestFramework.LogError("035", " tab and fout spaces CompareOrdinal Expected Result is greater 0,Actual Result is ( " + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("036", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using log4net.Core;
namespace log4net.Util
{
/// <summary>
/// A fixed size rolling buffer of logging events.
/// </summary>
/// <remarks>
/// <para>
/// An array backed fixed size leaky bucket.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class CyclicBuffer
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="maxSize">The maximum number of logging events in the buffer.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="CyclicBuffer" /> class with
/// the specified maximum number of buffered logging events.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="maxSize"/> argument is not a positive integer.</exception>
public CyclicBuffer(int maxSize)
{
if (maxSize < 1)
{
throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required");
}
m_maxSize = maxSize;
m_events = new LoggingEvent[maxSize];
m_first = 0;
m_last = 0;
m_numElems = 0;
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Appends a <paramref name="loggingEvent"/> to the buffer.
/// </summary>
/// <param name="loggingEvent">The event to append to the buffer.</param>
/// <returns>The event discarded from the buffer, if the buffer is full, otherwise <c>null</c>.</returns>
/// <remarks>
/// <para>
/// Append an event to the buffer. If the buffer still contains free space then
/// <c>null</c> is returned. If the buffer is full then an event will be dropped
/// to make space for the new event, the event dropped is returned.
/// </para>
/// </remarks>
public LoggingEvent Append(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
lock(this)
{
// save the discarded event
LoggingEvent discardedLoggingEvent = m_events[m_last];
// overwrite the last event position
m_events[m_last] = loggingEvent;
if (++m_last == m_maxSize)
{
m_last = 0;
}
if (m_numElems < m_maxSize)
{
m_numElems++;
}
else if (++m_first == m_maxSize)
{
m_first = 0;
}
if (m_numElems < m_maxSize)
{
// Space remaining
return null;
}
else
{
// Buffer is full and discarding an event
return discardedLoggingEvent;
}
}
}
/// <summary>
/// Get and remove the oldest event in the buffer.
/// </summary>
/// <returns>The oldest logging event in the buffer</returns>
/// <remarks>
/// <para>
/// Gets the oldest (first) logging event in the buffer and removes it
/// from the buffer.
/// </para>
/// </remarks>
public LoggingEvent PopOldest()
{
lock(this)
{
LoggingEvent ret = null;
if (m_numElems > 0)
{
m_numElems--;
ret = m_events[m_first];
m_events[m_first] = null;
if (++m_first == m_maxSize)
{
m_first = 0;
}
}
return ret;
}
}
/// <summary>
/// Pops all the logging events from the buffer into an array.
/// </summary>
/// <returns>An array of all the logging events in the buffer.</returns>
/// <remarks>
/// <para>
/// Get all the events in the buffer and clear the buffer.
/// </para>
/// </remarks>
public LoggingEvent[] PopAll()
{
lock(this)
{
LoggingEvent[] ret = new LoggingEvent[m_numElems];
if (m_numElems > 0)
{
if (m_first < m_last)
{
Array.Copy(m_events, m_first, ret, 0, m_numElems);
}
else
{
Array.Copy(m_events, m_first, ret, 0, m_maxSize - m_first);
Array.Copy(m_events, 0, ret, m_maxSize - m_first, m_last);
}
}
Clear();
return ret;
}
}
/// <summary>
/// Clear the buffer
/// </summary>
/// <remarks>
/// <para>
/// Clear the buffer of all events. The events in the buffer are lost.
/// </para>
/// </remarks>
public void Clear()
{
lock(this)
{
// Set all the elements to null
Array.Clear(m_events, 0, m_events.Length);
m_first = 0;
m_last = 0;
m_numElems = 0;
}
}
#if RESIZABLE_CYCLIC_BUFFER
/// <summary>
/// Resizes the cyclic buffer to <paramref name="newSize"/>.
/// </summary>
/// <param name="newSize">The new size of the buffer.</param>
/// <remarks>
/// <para>
/// Resize the cyclic buffer. Events in the buffer are copied into
/// the newly sized buffer. If the buffer is shrunk and there are
/// more events currently in the buffer than the new size of the
/// buffer then the newest events will be dropped from the buffer.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="newSize"/> argument is not a positive integer.</exception>
public void Resize(int newSize)
{
lock(this)
{
if (newSize < 0)
{
throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("newSize", (object)newSize, "Parameter: newSize, Value: [" + newSize + "] out of range. Non zero positive integer required");
}
if (newSize == m_numElems)
{
return; // nothing to do
}
LoggingEvent[] temp = new LoggingEvent[newSize];
int loopLen = (newSize < m_numElems) ? newSize : m_numElems;
for(int i = 0; i < loopLen; i++)
{
temp[i] = m_events[m_first];
m_events[m_first] = null;
if (++m_first == m_numElems)
{
m_first = 0;
}
}
m_events = temp;
m_first = 0;
m_numElems = loopLen;
m_maxSize = newSize;
if (loopLen == newSize)
{
m_last = 0;
}
else
{
m_last = loopLen;
}
}
}
#endif
#endregion Public Instance Methods
#region Public Instance Properties
/// <summary>
/// Gets the <paramref name="i"/>th oldest event currently in the buffer.
/// </summary>
/// <value>The <paramref name="i"/>th oldest event currently in the buffer.</value>
/// <remarks>
/// <para>
/// If <paramref name="i"/> is outside the range 0 to the number of events
/// currently in the buffer, then <c>null</c> is returned.
/// </para>
/// </remarks>
public LoggingEvent this[int i]
{
get
{
lock(this)
{
if (i < 0 || i >= m_numElems)
{
return null;
}
return m_events[(m_first + i) % m_maxSize];
}
}
}
/// <summary>
/// Gets the maximum size of the buffer.
/// </summary>
/// <value>The maximum size of the buffer.</value>
/// <remarks>
/// <para>
/// Gets the maximum size of the buffer
/// </para>
/// </remarks>
public int MaxSize
{
get
{
lock(this)
{
return m_maxSize;
}
}
#if RESIZABLE_CYCLIC_BUFFER
set
{
/// Setting the MaxSize will cause the buffer to resize.
Resize(value);
}
#endif
}
/// <summary>
/// Gets the number of logging events in the buffer.
/// </summary>
/// <value>The number of logging events in the buffer.</value>
/// <remarks>
/// <para>
/// This number is guaranteed to be in the range 0 to <see cref="MaxSize"/>
/// (inclusive).
/// </para>
/// </remarks>
public int Length
{
get
{
lock(this)
{
return m_numElems;
}
}
}
#endregion Public Instance Properties
#region Private Instance Fields
private LoggingEvent[] m_events;
private int m_first;
private int m_last;
private int m_numElems;
private int m_maxSize;
#endregion Private Instance Fields
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System;
using System.Collections.Generic;
using System.Threading;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Common;
using NLog.Internal;
[TestFixture]
public class AsyncHelperTests : NLogTestBase
{
[Test]
public void OneTimeOnlyTest1()
{
var exceptions = new List<Exception>();
AsyncContinuation cont = exceptions.Add;
cont = AsyncHelpers.PreventMultipleCalls(cont);
// OneTimeOnly(OneTimeOnly(x)) == OneTimeOnly(x)
var cont2 = AsyncHelpers.PreventMultipleCalls(cont);
#if NETCF2_0
Assert.AreNotSame(cont, cont2);
#else
Assert.AreSame(cont, cont2);
#endif
var sampleException = new InvalidOperationException("some message");
cont(null);
cont(sampleException);
cont(null);
cont(sampleException);
Assert.AreEqual(1, exceptions.Count);
Assert.IsNull(exceptions[0]);
}
[Test]
public void OneTimeOnlyTest2()
{
var exceptions = new List<Exception>();
AsyncContinuation cont = exceptions.Add;
cont = AsyncHelpers.PreventMultipleCalls(cont);
var sampleException = new InvalidOperationException("some message");
cont(sampleException);
cont(null);
cont(sampleException);
cont(null);
Assert.AreEqual(1, exceptions.Count);
Assert.AreSame(sampleException, exceptions[0]);
}
[Test]
public void OneTimeOnlyExceptionInHandlerTest()
{
var exceptions = new List<Exception>();
var sampleException = new InvalidOperationException("some message");
AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; };
cont = AsyncHelpers.PreventMultipleCalls(cont);
cont(null);
cont(null);
cont(null);
Assert.AreEqual(1, exceptions.Count);
Assert.IsNull(exceptions[0]);
}
[Test]
public void ContinuationTimeoutTest()
{
var exceptions = new List<Exception>();
// set up a timer to strike in 1 second
var cont = AsyncHelpers.WithTimeout(ex => exceptions.Add(ex), TimeSpan.FromSeconds(1));
// sleep 2 seconds to make sure
Thread.Sleep(2000);
// make sure we got timeout exception
Assert.AreEqual(1, exceptions.Count);
Assert.IsInstanceOfType(typeof(TimeoutException), exceptions[0]);
Assert.AreEqual("Timeout.", exceptions[0].Message);
// those will be ignored
cont(null);
cont(new InvalidOperationException("Some exception"));
cont(null);
cont(new InvalidOperationException("Some exception"));
Assert.AreEqual(1, exceptions.Count);
}
[Test]
public void ContinuationTimeoutNotHitTest()
{
var exceptions = new List<Exception>();
// set up a timer to strike in 1 second
var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromSeconds(1));
// call success quickly, hopefully before the timer comes
cont(null);
// sleep 2 seconds to make sure timer event comes
Thread.Sleep(2000);
// make sure we got success, not a timer exception
Assert.AreEqual(1, exceptions.Count);
Assert.IsNull(exceptions[0]);
// those will be ignored
cont(null);
cont(new InvalidOperationException("Some exception"));
cont(null);
cont(new InvalidOperationException("Some exception"));
Assert.AreEqual(1, exceptions.Count);
Assert.IsNull(exceptions[0]);
}
[Test]
public void ContinuationErrorTimeoutNotHitTest()
{
var exceptions = new List<Exception>();
// set up a timer to strike in 3 second
var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromSeconds(1));
var exception = new InvalidOperationException("Foo");
// call success quickly, hopefully before the timer comes
cont(exception);
// sleep 2 seconds to make sure timer event comes
Thread.Sleep(2000);
// make sure we got success, not a timer exception
Assert.AreEqual(1, exceptions.Count);
Assert.IsNotNull(exceptions[0]);
Assert.AreSame(exception, exceptions[0]);
// those will be ignored
cont(null);
cont(new InvalidOperationException("Some exception"));
cont(null);
cont(new InvalidOperationException("Some exception"));
Assert.AreEqual(1, exceptions.Count);
Assert.IsNotNull(exceptions[0]);
}
[Test]
public void RepeatTest1()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int callCount = 0;
AsyncHelpers.Repeat(10, finalContinuation,
cont =>
{
callCount++;
cont(null);
});
Assert.IsTrue(finalContinuationInvoked);
Assert.IsNull(lastException);
Assert.AreEqual(10, callCount);
}
[Test]
public void RepeatTest2()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int callCount = 0;
AsyncHelpers.Repeat(10, finalContinuation,
cont =>
{
callCount++;
cont(sampleException);
cont(sampleException);
});
Assert.IsTrue(finalContinuationInvoked);
Assert.AreSame(sampleException, lastException);
Assert.AreEqual(1, callCount);
}
[Test]
public void RepeatTest3()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int callCount = 0;
AsyncHelpers.Repeat(10, finalContinuation,
cont =>
{
callCount++;
throw sampleException;
});
Assert.IsTrue(finalContinuationInvoked);
Assert.AreSame(sampleException, lastException);
Assert.AreEqual(1, callCount);
}
[Test]
public void ForEachItemSequentiallyTest1()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemSequentially(input, finalContinuation,
(i, cont) =>
{
sum += i;
cont(null);
cont(null);
});
Assert.IsTrue(finalContinuationInvoked);
Assert.IsNull(lastException);
Assert.AreEqual(55, sum);
}
[Test]
public void ForEachItemSequentiallyTest2()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemSequentially(input, finalContinuation,
(i, cont) =>
{
sum += i;
cont(sampleException);
cont(sampleException);
});
Assert.IsTrue(finalContinuationInvoked);
Assert.AreSame(sampleException, lastException);
Assert.AreEqual(1, sum);
}
[Test]
public void ForEachItemSequentiallyTest3()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemSequentially(input, finalContinuation,
(i, cont) =>
{
sum += i;
throw sampleException;
});
Assert.IsTrue(finalContinuationInvoked);
Assert.AreSame(sampleException, lastException);
Assert.AreEqual(1, sum);
}
[Test]
public void ForEachItemInParallelEmptyTest()
{
int[] items = new int[0];
Exception lastException = null;
bool finalContinuationInvoked = false;
AsyncContinuation continuation = ex =>
{
lastException = ex;
finalContinuationInvoked = true;
};
AsyncHelpers.ForEachItemInParallel(items, continuation, (i, cont) => { Assert.Fail("Will not be reached"); });
Assert.IsTrue(finalContinuationInvoked);
Assert.IsNull(lastException);
}
[Test]
public void ForEachItemInParallelTest()
{
var finalContinuationInvoked = new ManualResetEvent(false);
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
lastException = ex;
finalContinuationInvoked.Set();
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemInParallel(input, finalContinuation,
(i, cont) =>
{
lock (input)
{
sum += i;
}
cont(null);
cont(null);
});
finalContinuationInvoked.WaitOne();
Assert.IsNull(lastException);
Assert.AreEqual(55, sum);
}
[Test]
public void ForEachItemInParallelSingleFailureTest()
{
using (new InternalLoggerScope())
{
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogToConsole = true;
var finalContinuationInvoked = new ManualResetEvent(false);
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
lastException = ex;
finalContinuationInvoked.Set();
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemInParallel(input, finalContinuation,
(i, cont) =>
{
Console.WriteLine("Callback on {0}", Thread.CurrentThread.ManagedThreadId);
lock (input)
{
sum += i;
}
if (i == 7)
{
throw new InvalidOperationException("Some failure.");
}
cont(null);
});
finalContinuationInvoked.WaitOne();
Assert.AreEqual(55, sum);
Assert.IsNotNull(lastException);
Assert.IsInstanceOfType(typeof(InvalidOperationException), lastException);
Assert.AreEqual("Some failure.", lastException.Message);
}
}
[Test]
public void ForEachItemInParallelMultipleFailuresTest()
{
var finalContinuationInvoked = new ManualResetEvent(false);
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
lastException = ex;
finalContinuationInvoked.Set();
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemInParallel(input, finalContinuation,
(i, cont) =>
{
lock (input)
{
sum += i;
}
throw new InvalidOperationException("Some failure.");
});
finalContinuationInvoked.WaitOne();
Assert.AreEqual(55, sum);
Assert.IsNotNull(lastException);
Assert.IsInstanceOfType(typeof(NLogRuntimeException), lastException);
Assert.IsTrue(lastException.Message.StartsWith("Got multiple exceptions:\r\n"));
}
[Test]
public void PrecededByTest1()
{
int invokedCount1 = 0;
int invokedCount2 = 0;
int sequence = 7;
int invokedCount1Sequence = 0;
int invokedCount2Sequence = 0;
AsyncContinuation originalContinuation = ex =>
{
invokedCount1++;
invokedCount1Sequence = sequence++;
};
AsynchronousAction doSomethingElse = c =>
{
invokedCount2++;
invokedCount2Sequence = sequence++;
c(null);
c(null);
};
AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse);
cont(null);
// make sure doSomethingElse was invoked first
// then original continuation
Assert.AreEqual(7, invokedCount2Sequence);
Assert.AreEqual(8, invokedCount1Sequence);
Assert.AreEqual(1, invokedCount1);
Assert.AreEqual(1, invokedCount2);
}
[Test]
public void PrecededByTest2()
{
int invokedCount1 = 0;
int invokedCount2 = 0;
int sequence = 7;
int invokedCount1Sequence = 0;
int invokedCount2Sequence = 0;
AsyncContinuation originalContinuation = ex =>
{
invokedCount1++;
invokedCount1Sequence = sequence++;
};
AsynchronousAction doSomethingElse = c =>
{
invokedCount2++;
invokedCount2Sequence = sequence++;
c(null);
c(null);
};
AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse);
var sampleException = new InvalidOperationException("Some message.");
cont(sampleException);
// make sure doSomethingElse was not invoked
Assert.AreEqual(0, invokedCount2Sequence);
Assert.AreEqual(7, invokedCount1Sequence);
Assert.AreEqual(1, invokedCount1);
Assert.AreEqual(0, invokedCount2);
}
}
}
| |
// 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.IO;
using System.Text;
using System.Collections;
using System.Xml.Schema;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
internal class ValidatingReaderNodeData
{
private string _localName;
private string _namespaceUri;
private string _prefix;
private string _nameWPrefix;
private string _rawValue;
private string _originalStringValue; // Original value
private int _depth;
private AttributePSVIInfo _attributePSVIInfo; //Used only for default attributes
private XmlNodeType _nodeType;
private int _lineNo;
private int _linePos;
public ValidatingReaderNodeData()
{
Clear(XmlNodeType.None);
}
public ValidatingReaderNodeData(XmlNodeType nodeType)
{
Clear(nodeType);
}
public string LocalName
{
get
{
return _localName;
}
set
{
_localName = value;
}
}
public string Namespace
{
get
{
return _namespaceUri;
}
set
{
_namespaceUri = value;
}
}
public string Prefix
{
get
{
return _prefix;
}
set
{
_prefix = value;
}
}
public string GetAtomizedNameWPrefix(XmlNameTable nameTable)
{
if (_nameWPrefix == null)
{
if (_prefix.Length == 0)
{
_nameWPrefix = _localName;
}
else
{
_nameWPrefix = nameTable.Add(string.Concat(_prefix, ":", _localName));
}
}
return _nameWPrefix;
}
public int Depth
{
get
{
return _depth;
}
set
{
_depth = value;
}
}
public string RawValue
{
get
{
return _rawValue;
}
set
{
_rawValue = value;
}
}
public string OriginalStringValue
{
get
{
return _originalStringValue;
}
set
{
_originalStringValue = value;
}
}
public XmlNodeType NodeType
{
get
{
return _nodeType;
}
set
{
_nodeType = value;
}
}
public AttributePSVIInfo AttInfo
{
get
{
return _attributePSVIInfo;
}
set
{
_attributePSVIInfo = value;
}
}
public int LineNumber
{
get
{
return _lineNo;
}
}
public int LinePosition
{
get
{
return _linePos;
}
}
internal void Clear(XmlNodeType nodeType)
{
_nodeType = nodeType;
_localName = string.Empty;
_prefix = string.Empty;
_namespaceUri = string.Empty;
_rawValue = string.Empty;
if (_attributePSVIInfo != null)
{
_attributePSVIInfo.Reset();
}
_nameWPrefix = null;
_lineNo = 0;
_linePos = 0;
}
internal void ClearName()
{
_localName = string.Empty;
_prefix = string.Empty;
_namespaceUri = string.Empty;
}
internal void SetLineInfo(int lineNo, int linePos)
{
_lineNo = lineNo;
_linePos = linePos;
}
internal void SetLineInfo(IXmlLineInfo lineInfo)
{
if (lineInfo != null)
{
_lineNo = lineInfo.LineNumber;
_linePos = lineInfo.LinePosition;
}
}
internal void SetItemData(string localName, string prefix, string ns, string value)
{
_localName = localName;
_prefix = prefix;
_namespaceUri = ns;
_rawValue = value;
}
internal void SetItemData(string localName, string prefix, string ns, int depth)
{
_localName = localName;
_prefix = prefix;
_namespaceUri = ns;
_depth = depth;
_rawValue = string.Empty;
}
internal void SetItemData(string value)
{
SetItemData(value, value);
}
internal void SetItemData(string value, string originalStringValue)
{
_rawValue = value;
_originalStringValue = originalStringValue;
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A lock-free, concurrent queue primitive, and its associated debugger view type.
//
// This is a stripped-down version of ConcurrentQueue, for use from within the System.Threading
// surface to eliminate a dependency on System.Collections.Concurrent.
// Please try to keep this in sync with the public ConcurrentQueue implementation.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
internal class LowLevelConcurrentQueue<T> /*: IProducerConsumerCollection<T>*/ : IEnumerable<T>
{
//fields of ConcurrentQueue
private volatile Segment _head;
private volatile Segment _tail;
private const int SEGMENT_SIZE = 32;
//number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot.
internal volatile int m_numSnapshotTakers = 0;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public LowLevelConcurrentQueue()
{
_head = _tail = new Segment(0, this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
get
{
Segment head = _head;
if (!head.IsEmpty)
//fast route 1:
//if current head is not empty, then queue is not empty
return false;
else if (head.Next == null)
//fast route 2:
//if current head is empty and it's the last segment
//then queue is empty
return true;
else
//slow route:
//current head is empty and it is NOT the last segment,
//it means another thread is growing new segment
{
SpinWait spin = new SpinWait();
while (head.IsEmpty)
{
if (head.Next == null)
return true;
spin.SpinOnce();
head = _head;
}
return false;
}
}
}
/// <summary>
/// Store the position of the current head and tail positions.
/// </summary>
/// <param name="head">return the head segment</param>
/// <param name="tail">return the tail segment</param>
/// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param>
/// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param>
private void GetHeadTailPositions(out Segment head, out Segment tail,
out int headLow, out int tailHigh)
{
head = _head;
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
SpinWait spin = new SpinWait();
//we loop until the observed values are stable and sensible.
//This ensures that any update order by other methods can be tolerated.
while (
//if head and tail changed, retry
head != _head || tail != _tail
//if low and high pointers, retry
|| headLow != head.Low || tailHigh != tail.High
//if head jumps ahead of tail because of concurrent grow and dequeue, retry
|| head.m_index > tail.m_index)
{
spin.SpinOnce();
head = _head;
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
get
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
return tailHigh - headLow + 1;
}
//head segment
int count = SEGMENT_SIZE - headLow;
//middle segment(s), if any, are full.
//We don't deal with overflow to be consistent with the behavior of generic types in CLR.
count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1));
//tail segment
count += tailHigh + 1;
return count;
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
Interlocked.Increment(ref m_numSnapshotTakers);
// Takes a snapshot of the queue.
// A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot
// wrap the following with a try/finally block, otherwise the decrement will happen before the yield return
// statements in the GetEnumerator (head, tail, headLow, tailHigh) method.
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
// the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called.
// This is inconsistent with existing generic collections. In order to prevent it, we capture the
// value of m_head in a buffer and call out to a helper method.
//The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an
// unnecessary perfomance hit.
return GetEnumerator(head, tail, headLow, tailHigh);
}
/// <summary>
/// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation.
/// </summary>
private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh)
{
try
{
SpinWait spin = new SpinWait();
if (head == tail)
{
for (int i = headLow; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return head.m_array[i];
}
}
else
{
//iterate on head segment
for (int i = headLow; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return head.m_array[i];
}
//iterate on middle segments
Segment curr = head.Next;
while (curr != tail)
{
for (int i = 0; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!curr.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return curr.m_array[i];
}
curr = curr.Next;
}
//iterate on tail segment
for (int i = 0; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!tail.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return tail.m_array[i];
}
}
}
finally
{
// This Decrement must happen after the enumeration is over.
Interlocked.Decrement(ref m_numSnapshotTakers);
}
}
/// <summary>
/// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="item">The object to add to the end of the <see
/// cref="ConcurrentQueue{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
SpinWait spin = new SpinWait();
while (true)
{
Segment tail = _tail;
if (tail.TryAppend(item))
return;
spin.SpinOnce();
}
}
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned from the beggining of the <see
/// cref="ConcurrentQueue{T}"/>
/// succesfully; otherwise, false.</returns>
public bool TryDequeue(out T result)
{
while (!IsEmpty)
{
Segment head = _head;
if (head.TryRemove(out result))
return true;
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
return false;
}
/// <summary>
/// private class for ConcurrentQueue.
/// a queue is a linked list of small arrays, each node is called a segment.
/// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording
/// the first and last valid elements of the array.
/// </summary>
private class Segment
{
//we define two volatile arrays: m_array and m_state. Note that the accesses to the array items
//do not get volatile treatment. But we don't need to worry about loading adjacent elements or
//store/load on adjacent elements would suffer reordering.
// - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe.
// - Two loads: because one item from two volatile arrays are accessed, the loads of the array references
// are sufficient to prevent reordering of the loads of the elements.
internal volatile T[] m_array;
// For each entry in m_array, the corresponding entry in m_state indicates whether this position contains
// a valid value. m_state is initially all false.
internal volatile VolatileBool[] m_state;
//pointer to the next segment. null if the current segment is the last segment
private volatile Segment _next;
//We use this zero based index to track how many segments have been created for the queue, and
//to compute how many active segments are there currently.
// * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1;
// * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely
// assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4
// billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years.
internal readonly long m_index;
//indices of where the first and last valid values
// - m_low points to the position of the next element to pop from this segment, range [0, infinity)
// m_low >= SEGMENT_SIZE implies the segment is disposable
// - m_high points to the position of the latest pushed element, range [-1, infinity)
// m_high == -1 implies the segment is new and empty
// m_high >= SEGMENT_SIZE-1 means this segment is ready to grow.
// and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment
// - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty
// - initially m_low =0 and m_high=-1;
private volatile int _low;
private volatile int _high;
private volatile LowLevelConcurrentQueue<T> _source;
/// <summary>
/// Create and initialize a segment with the specified index.
/// </summary>
internal Segment(long index, LowLevelConcurrentQueue<T> source)
{
m_array = new T[SEGMENT_SIZE];
m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
_high = -1;
Debug.Assert(index >= 0);
m_index = index;
_source = source;
}
/// <summary>
/// return the next segment
/// </summary>
internal Segment Next
{
get { return _next; }
}
/// <summary>
/// return true if the current segment is empty (doesn't have any element available to dequeue,
/// false otherwise
/// </summary>
internal bool IsEmpty
{
get { return (Low > High); }
}
/// <summary>
/// Add an element to the tail of the current segment
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <param name="value"></param>
internal void UnsafeAdd(T value)
{
Debug.Assert(_high < SEGMENT_SIZE - 1);
_high++;
m_array[_high] = value;
m_state[_high].m_value = true;
}
/// <summary>
/// Create a new segment and append to the current one
/// Does not update the m_tail pointer
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <returns>the reference to the new Segment</returns>
internal Segment UnsafeGrow()
{
Debug.Assert(_high >= SEGMENT_SIZE - 1);
Segment newSegment = new Segment(m_index + 1, _source); //m_index is Int64, we don't need to worry about overflow
_next = newSegment;
return newSegment;
}
/// <summary>
/// Create a new segment and append to the current one
/// Update the m_tail pointer
/// This method is called when there is no contention
/// </summary>
internal void Grow()
{
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
Segment newSegment = new Segment(m_index + 1, _source); //m_index is Int64, we don't need to worry about overflow
_next = newSegment;
Debug.Assert(_source._tail == this);
_source._tail = _next;
}
/// <summary>
/// Try to append an element at the end of this segment.
/// </summary>
/// <param name="value">the element to append</param>
/// <param name="tail">The tail.</param>
/// <returns>true if the element is appended, false if the current segment is full</returns>
/// <remarks>if appending the specified element succeeds, and after which the segment is full,
/// then grow the segment</remarks>
internal bool TryAppend(T value)
{
//quickly check if m_high is already over the boundary, if so, bail out
if (_high >= SEGMENT_SIZE - 1)
{
return false;
}
//Now we will use a CAS to increment m_high, and store the result in newhigh.
//Depending on how many free spots left in this segment and how many threads are doing this Increment
//at this time, the returning "newhigh" can be
// 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value
// 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment
// 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to
// Queue.Enqueue method, telling it to try again in the next segment.
int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
newhigh = Interlocked.Increment(ref _high);
if (newhigh <= SEGMENT_SIZE - 1)
{
m_array[newhigh] = value;
m_state[newhigh].m_value = true;
}
//if this thread takes up the last slot in the segment, then this thread is responsible
//to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
//if thread abort during Grow, other threads will be left busy spinning forever.
if (newhigh == SEGMENT_SIZE - 1)
{
Grow();
}
}
//if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot
return newhigh <= SEGMENT_SIZE - 1;
}
/// <summary>
/// try to remove an element from the head of current segment
/// </summary>
/// <param name="result">The result.</param>
/// <param name="head">The head.</param>
/// <returns>return false only if the current segment is empty</returns>
internal bool TryRemove(out T result)
{
SpinWait spin = new SpinWait();
int lowLocal = Low, highLocal = High;
while (lowLocal <= highLocal)
{
//try to update m_low
if (Interlocked.CompareExchange(ref _low, lowLocal + 1, lowLocal) == lowLocal)
{
//if the specified value is not available (this spot is taken by a push operation,
// but the value is not written into yet), then spin
SpinWait spinLocal = new SpinWait();
while (!m_state[lowLocal].m_value)
{
spinLocal.SpinOnce();
}
result = m_array[lowLocal];
// If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null.
// It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include
// the deleted entry at m_array[lowLocal].
if (_source.m_numSnapshotTakers <= 0)
{
m_array[lowLocal] = default(T); //release the reference to the object.
}
//if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes
//disposable, then this thread is responsible to dispose this segment, and reset m_head
if (lowLocal + 1 >= SEGMENT_SIZE)
{
// Invariant: we only dispose the current m_head, not any other segment
// In usual situation, disposing a segment is simply seting m_head to m_head.m_next
// But there is one special case, where m_head and m_tail points to the same and ONLY
//segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow,
//while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
//dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
//Grow operation, this is the reason of having the following while loop
spinLocal = new SpinWait();
while (_next == null)
{
spinLocal.SpinOnce();
}
Debug.Assert(_source._head == this);
_source._head = _next;
}
return true;
}
else
{
//CAS failed due to contention: spin briefly and retry
spin.SpinOnce();
lowLocal = Low; highLocal = High;
}
}//end of while
result = default(T);
return false;
}
/// <summary>
/// return the position of the head of the current segment
/// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty
/// </summary>
internal int Low
{
get
{
return Math.Min(_low, SEGMENT_SIZE);
}
}
/// <summary>
/// return the logical position of the tail of the current segment
/// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet
/// </summary>
internal int High
{
get
{
//if m_high > SEGMENT_SIZE, it means it's out of range, we should return
//SEGMENT_SIZE-1 as the logical position
return Math.Min(_high, SEGMENT_SIZE - 1);
}
}
}
}//end of class Segment
/// <summary>
/// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile
/// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile
/// </summary>
internal struct VolatileBool
{
public VolatileBool(bool value)
{
m_value = value;
}
public volatile bool m_value;
}
}
| |
/*
* 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 System;
using System.Threading;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Timers;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class AssetServicesConnector : BaseServiceConnector, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
const int MAXSENDRETRIESLEN = 30;
private string m_ServerURI = String.Empty;
private IAssetCache m_Cache = null;
private int m_retryCounter;
private bool m_inRetries;
private List<AssetBase>[] m_sendRetries = new List<AssetBase>[MAXSENDRETRIESLEN];
private System.Timers.Timer m_retryTimer;
private int m_maxAssetRequestConcurrency = 30;
private delegate void AssetRetrievedEx(AssetBase asset);
// Keeps track of concurrent requests for the same asset, so that it's only loaded once.
// Maps: Asset ID -> Handlers which will be called when the asset has been loaded
// private Dictionary<string, AssetRetrievedEx> m_AssetHandlers = new Dictionary<string, AssetRetrievedEx>();
private Dictionary<string, List<AssetRetrievedEx>> m_AssetHandlers = new Dictionary<string, List<AssetRetrievedEx>>();
private Dictionary<string, string> m_UriMap = new Dictionary<string, string>();
private Thread[] m_fetchThreads;
public int MaxAssetRequestConcurrency
{
get { return m_maxAssetRequestConcurrency; }
set { m_maxAssetRequestConcurrency = value; }
}
public AssetServicesConnector()
{
}
public AssetServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public AssetServicesConnector(IConfigSource source)
: base(source, "AssetService")
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig netconfig = source.Configs["Network"];
if (netconfig != null)
m_maxAssetRequestConcurrency = netconfig.GetInt("MaxRequestConcurrency",m_maxAssetRequestConcurrency);
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
throw new Exception("Asset connector init error");
}
string serviceURI = assetConfig.GetString("AssetServerURI",
String.Empty);
m_ServerURI = serviceURI;
if (serviceURI == String.Empty)
{
m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService");
throw new Exception("Asset connector init error");
}
m_retryTimer = new System.Timers.Timer();
m_retryTimer.Elapsed += new ElapsedEventHandler(retryCheck);
m_retryTimer.AutoReset = true;
m_retryTimer.Interval = 60000;
Uri serverUri = new Uri(m_ServerURI);
string groupHost = serverUri.Host;
for (int i = 0 ; i < 256 ; i++)
{
string prefix = i.ToString("x2");
groupHost = assetConfig.GetString("AssetServerHost_"+prefix, groupHost);
m_UriMap[prefix] = groupHost;
//m_log.DebugFormat("[ASSET]: Using {0} for prefix {1}", groupHost, prefix);
}
m_fetchThreads = new Thread[2];
for (int i = 0 ; i < 2 ; i++)
{
m_fetchThreads[i] = WorkManager.StartThread(AssetRequestProcessor,
String.Format("GetTextureWorker{0}", i),
ThreadPriority.Normal,
true,
false);
}
}
private string MapServer(string id)
{
if (m_UriMap.Count == 0)
return m_ServerURI;
UriBuilder serverUri = new UriBuilder(m_ServerURI);
string prefix = id.Substring(0, 2).ToLower();
string host;
// HG URLs will not be valid UUIDS
if (m_UriMap.ContainsKey(prefix))
host = m_UriMap[prefix];
else
host = m_UriMap["00"];
serverUri.Host = host;
// m_log.DebugFormat("[ASSET]: Using {0} for host name for prefix {1}", host, prefix);
string ret = serverUri.Uri.AbsoluteUri;
if (ret.EndsWith("/"))
ret = ret.Substring(0, ret.Length - 1);
return ret;
}
protected void retryCheck(object source, ElapsedEventArgs e)
{
lock(m_sendRetries)
{
if(m_inRetries)
return;
m_inRetries = true;
}
m_retryCounter++;
if(m_retryCounter >= 61 ) // avoid overflow 60 is max in use below
m_retryCounter = 1;
int inUse = 0;
int nextlevel;
int timefactor;
List<AssetBase> retrylist;
// we need to go down
for(int i = MAXSENDRETRIESLEN - 1; i >= 0; i--)
{
lock(m_sendRetries)
retrylist = m_sendRetries[i];
if(retrylist == null)
continue;
inUse++;
nextlevel = i + 1;
//We exponentially fall back on frequency until we reach one attempt per hour
//The net result is that we end up in the queue for roughly 24 hours..
//24 hours worth of assets could be a lot, so the hope is that the region admin
//will have gotten the asset connector back online quickly!
if(i == 0)
timefactor = 1;
else
{
timefactor = 1 << nextlevel;
if (timefactor > 60)
timefactor = 60;
}
if(m_retryCounter < timefactor)
continue; // to update inUse;
if (m_retryCounter % timefactor != 0)
continue;
// a list to retry
lock(m_sendRetries)
m_sendRetries[i] = null;
// we are the only ones with a copy of this retrylist now
foreach(AssetBase ass in retrylist)
retryStore(ass, nextlevel);
}
lock(m_sendRetries)
{
if(inUse == 0 )
m_retryTimer.Stop();
m_inRetries = false;
}
}
protected void SetCache(IAssetCache cache)
{
m_Cache = cache;
}
public AssetBase Get(string id)
{
string uri = MapServer(id) + "/assets/" + id;
AssetBase asset = null;
if (m_Cache != null)
{
if (!m_Cache.Get(id, out asset))
return null;
}
if (asset == null || asset.Data == null || asset.Data.Length == 0)
{
// XXX: Commented out for now since this has either never been properly operational or not for some time
// as m_maxAssetRequestConcurrency was being passed as the timeout, not a concurrency limiting option.
// Wasn't noticed before because timeout wasn't actually used.
// Not attempting concurrency setting for now as this omission was discovered in release candidate
// phase for OpenSimulator 0.8. Need to revisit afterwards.
// asset
// = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>(
// "GET", uri, 0, m_maxAssetRequestConcurrency);
asset = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, m_Auth);
if (m_Cache != null)
{
if (asset != null)
m_Cache.Cache(asset);
else
m_Cache.CacheNegative(id);
}
}
return asset;
}
public AssetBase GetCached(string id)
{
// m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Cache request for {0}", id);
AssetBase asset = null;
if (m_Cache != null)
{
m_Cache.Get(id, out asset);
}
return asset;
}
public AssetMetadata GetMetadata(string id)
{
if (m_Cache != null)
{
AssetBase fullAsset;
if (!m_Cache.Get(id, out fullAsset))
return null;
if (fullAsset != null)
return fullAsset.Metadata;
}
string uri = MapServer(id) + "/assets/" + id + "/metadata";
AssetMetadata asset = SynchronousRestObjectRequester.MakeRequest<int, AssetMetadata>("GET", uri, 0, m_Auth);
return asset;
}
public byte[] GetData(string id)
{
if (m_Cache != null)
{
AssetBase fullAsset;
if (!m_Cache.Get(id, out fullAsset))
return null;
if (fullAsset != null)
return fullAsset.Data;
}
using (RestClient rc = new RestClient(MapServer(id)))
{
rc.AddResourcePath("assets");
rc.AddResourcePath(id);
rc.AddResourcePath("data");
rc.RequestMethod = "GET";
using (Stream s = rc.Request(m_Auth))
{
if (s == null)
return null;
if (s.Length > 0)
{
byte[] ret = new byte[s.Length];
s.Read(ret, 0, (int)s.Length);
return ret;
}
}
return null;
}
}
private class QueuedAssetRequest
{
public string uri;
public string id;
}
private OpenSim.Framework.BlockingQueue<QueuedAssetRequest> m_requestQueue =
new OpenSim.Framework.BlockingQueue<QueuedAssetRequest>();
private void AssetRequestProcessor()
{
QueuedAssetRequest r;
while (true)
{
r = m_requestQueue.Dequeue(4500);
Watchdog.UpdateThread();
if(r== null)
continue;
string uri = r.uri;
string id = r.id;
try
{
AssetBase a = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, 30000, m_Auth);
if (a != null && m_Cache != null)
m_Cache.Cache(a);
List<AssetRetrievedEx> handlers;
lock (m_AssetHandlers)
{
handlers = m_AssetHandlers[id];
m_AssetHandlers.Remove(id);
}
if(handlers != null)
{
Util.FireAndForget(x =>
{
foreach (AssetRetrievedEx h in handlers)
{
try { h.Invoke(a); }
catch { }
}
handlers.Clear();
});
}
}
catch { }
}
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
string uri = MapServer(id) + "/assets/" + id;
AssetBase asset = null;
if (m_Cache != null)
{
if (!m_Cache.Get(id, out asset))
return false;
}
if (asset == null || asset.Data == null || asset.Data.Length == 0)
{
lock (m_AssetHandlers)
{
AssetRetrievedEx handlerEx = new AssetRetrievedEx(delegate(AssetBase _asset) { handler(id, sender, _asset); });
List<AssetRetrievedEx> handlers;
if (m_AssetHandlers.TryGetValue(id, out handlers))
{
// Someone else is already loading this asset. It will notify our handler when done.
handlers.Add(handlerEx);
return true;
}
handlers = new List<AssetRetrievedEx>();
handlers.Add(handlerEx);
m_AssetHandlers.Add(id, handlers);
QueuedAssetRequest request = new QueuedAssetRequest();
request.id = id;
request.uri = uri;
m_requestQueue.Enqueue(request);
}
}
else
{
handler(id, sender, asset);
}
return true;
}
public virtual bool[] AssetsExist(string[] ids)
{
string uri = m_ServerURI + "/get_assets_exist";
bool[] exist = null;
try
{
exist = SynchronousRestObjectRequester.MakeRequest<string[], bool[]>("POST", uri, ids, m_Auth);
}
catch (Exception)
{
// This is most likely to happen because the server doesn't support this function,
// so just silently return "doesn't exist" for all the assets.
}
if (exist == null)
exist = new bool[ids.Length];
return exist;
}
string stringUUIDZero = UUID.Zero.ToString();
public string Store(AssetBase asset)
{
// Have to assign the asset ID here. This isn't likely to
// trigger since current callers don't pass emtpy IDs
// We need the asset ID to route the request to the proper
// cluster member, so we can't have the server assign one.
if (asset.ID == string.Empty || asset.ID == stringUUIDZero)
{
if (asset.FullID == UUID.Zero)
{
asset.FullID = UUID.Random();
}
m_log.WarnFormat("[Assets] Zero ID: {0}",asset.Name);
asset.ID = asset.FullID.ToString();
}
if (asset.FullID == UUID.Zero)
{
UUID uuid = UUID.Zero;
if (UUID.TryParse(asset.ID, out uuid))
{
asset.FullID = uuid;
}
if(asset.FullID == UUID.Zero)
{
m_log.WarnFormat("[Assets] Zero IDs: {0}",asset.Name);
asset.FullID = UUID.Random();
asset.ID = asset.FullID.ToString();
}
}
if (m_Cache != null)
m_Cache.Cache(asset);
if (asset.Temporary || asset.Local)
{
return asset.ID;
}
string uri = MapServer(asset.FullID.ToString()) + "/assets/";
string newID = null;
try
{
newID = SynchronousRestObjectRequester.
MakeRequest<AssetBase, string>("POST", uri, asset, 100000, m_Auth);
}
catch
{
newID = null;
}
if (newID == null || newID == String.Empty || newID == stringUUIDZero)
{
//The asset upload failed, try later
lock(m_sendRetries)
{
if (m_sendRetries[0] == null)
m_sendRetries[0] = new List<AssetBase>();
List<AssetBase> m_queue = m_sendRetries[0];
m_queue.Add(asset);
m_log.WarnFormat("[Assets] Upload failed: {0} type {1} will retry later",
asset.ID.ToString(), asset.Type.ToString());
m_retryTimer.Start();
}
}
else
{
if (newID != asset.ID)
{
// Placing this here, so that this work with old asset servers that don't send any reply back
// SynchronousRestObjectRequester returns somethins that is not an empty string
asset.ID = newID;
if (m_Cache != null)
m_Cache.Cache(asset);
}
}
return asset.ID;
}
public void retryStore(AssetBase asset, int nextRetryLevel)
{
/* this may be bad, so excluding
if (m_Cache != null && !m_Cache.Check(asset.ID))
{
m_log.WarnFormat("[Assets] Upload giveup asset bc no longer in local cache: {0}",
asset.ID.ToString();
return; // if no longer in cache, it was deleted or expired
}
*/
string uri = MapServer(asset.FullID.ToString()) + "/assets/";
string newID = null;
try
{
newID = SynchronousRestObjectRequester.
MakeRequest<AssetBase, string>("POST", uri, asset, 100000, m_Auth);
}
catch
{
newID = null;
}
if (newID == null || newID == String.Empty || newID == stringUUIDZero)
{
if(nextRetryLevel >= MAXSENDRETRIESLEN)
m_log.WarnFormat("[Assets] Upload giveup after several retries id: {0} type {1}",
asset.ID.ToString(), asset.Type.ToString());
else
{
lock(m_sendRetries)
{
if (m_sendRetries[nextRetryLevel] == null)
{
m_sendRetries[nextRetryLevel] = new List<AssetBase>();
}
List<AssetBase> m_queue = m_sendRetries[nextRetryLevel];
m_queue.Add(asset);
m_log.WarnFormat("[Assets] Upload failed: {0} type {1} will retry later",
asset.ID.ToString(), asset.Type.ToString());
}
}
}
else
{
m_log.InfoFormat("[Assets] Upload of {0} succeeded after {1} failed attempts", asset.ID.ToString(), nextRetryLevel.ToString());
if (newID != asset.ID)
{
asset.ID = newID;
if (m_Cache != null)
m_Cache.Cache(asset);
}
}
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
m_Cache.Get(id, out asset);
if (asset == null)
{
AssetMetadata metadata = GetMetadata(id);
if (metadata == null)
return false;
asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString());
asset.Metadata = metadata;
}
asset.Data = data;
string uri = MapServer(id) + "/assets/" + id;
if (SynchronousRestObjectRequester.MakeRequest<AssetBase, bool>("POST", uri, asset, m_Auth))
{
if (m_Cache != null)
m_Cache.Cache(asset);
return true;
}
return false;
}
public bool Delete(string id)
{
string uri = MapServer(id) + "/assets/" + id;
if (SynchronousRestObjectRequester.MakeRequest<int, bool>("DELETE", uri, 0, m_Auth))
{
if (m_Cache != null)
m_Cache.Expire(id);
return true;
}
return false;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 Sensus.DataStores;
using Sensus.DataStores.Local;
using Sensus.DataStores.Remote;
using Sensus.UI.UiProperties;
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Sensus.Context;
using Sensus.UI.Inputs;
using Xamarin.Forms;
namespace Sensus.UI
{
/// <summary>
/// Displays a single protocol.
/// </summary>
public class ProtocolPage : ContentPage
{
private Protocol _protocol;
private EventHandler<bool> _protocolRunningChangedAction;
/// <summary>
/// Initializes a new instance of the <see cref="ProtocolPage"/> class.
/// </summary>
/// <param name="protocol">Protocol to display.</param>
public ProtocolPage(Protocol protocol)
{
_protocol = protocol;
Title = "Protocol";
List<View> views = new List<View>();
views.AddRange(UiProperty.GetPropertyStacks(_protocol));
#region data stores
string localDataStoreSize = _protocol.LocalDataStore?.SizeDescription;
Button editLocalDataStoreButton = new Button
{
Text = "Local Data Store" + (localDataStoreSize == null ? "" : " (" + localDataStoreSize + ")"),
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand,
IsEnabled = !_protocol.Running
};
editLocalDataStoreButton.Clicked += async (o, e) =>
{
if (_protocol.LocalDataStore != null)
{
DataStore copy = _protocol.LocalDataStore.Copy();
if (copy == null)
{
await SensusServiceHelper.Get().FlashNotificationAsync("Failed to edit data store.");
}
else
{
await Navigation.PushAsync(new DataStorePage(_protocol, copy, true, false));
}
}
};
Button createLocalDataStoreButton = new Button
{
Text = "+",
FontSize = 20,
HorizontalOptions = LayoutOptions.End,
IsEnabled = !_protocol.Running
};
createLocalDataStoreButton.Clicked += (o, e) => CreateDataStore(true);
StackLayout localDataStoreStack = new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { editLocalDataStoreButton, createLocalDataStoreButton }
};
views.Add(localDataStoreStack);
Button editRemoteDataStoreButton = new Button
{
Text = "Remote Data Store",
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand,
IsEnabled = !_protocol.Running
};
editRemoteDataStoreButton.Clicked += async (o, e) =>
{
if (_protocol.RemoteDataStore != null)
{
DataStore copy = _protocol.RemoteDataStore.Copy();
if (copy == null)
{
await SensusServiceHelper.Get().FlashNotificationAsync("Failed to edit data store.");
}
else
{
await Navigation.PushAsync(new DataStorePage(_protocol, copy, false, false));
}
}
};
Button createRemoteDataStoreButton = new Button
{
Text = "+",
FontSize = 20,
HorizontalOptions = LayoutOptions.End,
IsEnabled = !_protocol.Running
};
createRemoteDataStoreButton.Clicked += (o, e) => CreateDataStore(false);
StackLayout remoteDataStoreStack = new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { editRemoteDataStoreButton, createRemoteDataStoreButton }
};
views.Add(remoteDataStoreStack);
#endregion
#region points of interest
Button pointsOfInterestButton = new Button
{
Text = "Points of Interest",
FontSize = 20
};
pointsOfInterestButton.Clicked += async (o, e) =>
{
await Navigation.PushAsync(new PointsOfInterestPage(_protocol.PointsOfInterest));
};
views.Add(pointsOfInterestButton);
#endregion
#region view probes
Button viewProbesButton = new Button
{
Text = "Probes",
FontSize = 20
};
viewProbesButton.Clicked += async (o, e) =>
{
await Navigation.PushAsync(new ProbesEditPage(_protocol));
};
views.Add(viewProbesButton);
#endregion
_protocolRunningChangedAction = (o, running) =>
{
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
editLocalDataStoreButton.IsEnabled = createLocalDataStoreButton.IsEnabled = editRemoteDataStoreButton.IsEnabled = createRemoteDataStoreButton.IsEnabled = !running;
});
};
StackLayout stack = new StackLayout
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand
};
foreach (View view in views)
{
stack.Children.Add(view);
}
Button lockButton = new Button
{
Text = _protocol.LockPasswordHash == "" ? "Lock" : "Unlock",
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand
};
lockButton.Clicked += (o, e) =>
{
if (lockButton.Text == "Lock")
{
SensusServiceHelper.Get().PromptForInputAsync(
"Lock Protocol",
new SingleLineTextInput("Password:", Keyboard.Text, true),
null,
true,
null,
null,
null,
null,
false,
input =>
{
if (input == null)
return;
string password = input.Value as string;
if (string.IsNullOrWhiteSpace(password))
{
SensusServiceHelper.Get().FlashNotificationAsync("Please enter a non-empty password.");
}
else
{
_protocol.LockPasswordHash = SensusServiceHelper.Get().GetHash(password);
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() => lockButton.Text = "Unlock");
}
});
}
else if (lockButton.Text == "Unlock")
{
_protocol.LockPasswordHash = "";
lockButton.Text = "Lock";
}
};
stack.Children.Add(lockButton);
Content = new ScrollView
{
Content = stack
};
}
protected override void OnAppearing()
{
base.OnAppearing();
_protocol.ProtocolRunningChanged += _protocolRunningChangedAction;
}
private async void CreateDataStore(bool local)
{
Type dataStoreType = local ? typeof(LocalDataStore) : typeof(RemoteDataStore);
List<DataStore> dataStores = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => !t.IsAbstract && t.IsSubclassOf(dataStoreType))
.Select(t => Activator.CreateInstance(t))
.Cast<DataStore>()
.OrderBy(d => d.DisplayName)
.ToList();
string cancelButtonName = "Cancel";
string selected = await DisplayActionSheet("Select " + (local ? "Local" : "Remote") + " Data Store", cancelButtonName, null, dataStores.Select((d, i) => (i + 1) + ") " + d.DisplayName).ToArray());
if (!string.IsNullOrWhiteSpace(selected) && selected != cancelButtonName)
{
await Navigation.PushAsync(new DataStorePage(_protocol, dataStores[int.Parse(selected.Substring(0, selected.IndexOf(")"))) - 1], local, true));
}
}
protected override void OnDisappearing()
{
base.OnDisappearing();
_protocol.ProtocolRunningChanged -= _protocolRunningChangedAction;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Palaso.Reporting;
namespace Palaso.Reporting
{
public interface IErrorReporter
{
void ReportFatalException(Exception e);
ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy,
string alternateButton1Label,
ErrorResult resultIfAlternateButtonPressed,
string message);
void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy);
void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args);
void ReportNonFatalMessageWithStackTrace(string message, params object[] args);
void ReportFatalMessageWithStackTrace(string message, object[] args);
}
public enum ErrorResult
{
None,
OK,
Cancel,
Abort,
Retry,
Ignore,
Yes,
No
}
public class ErrorReport
{
private static IErrorReporter _errorReporter;
//We removed all references to Winforms from Palaso.dll but our error reporting relied heavily on it.
//Not wanting to break existing applications we have now added this class initializer which will
//look for a reference to PalasoUIWindowsForms in the consuming app and if it exists instantiate the
//WinformsErrorReporter from there through Reflection. otherwise we will simply use a console
//error reporter
static ErrorReport()
{
_errorReporter = ExceptionHandler.GetObjectFromPalasoUiWindowsForms<IErrorReporter>() ?? new ConsoleErrorReporter();
}
/// <summary>
/// Use this method if you want to override the default IErrorReporter.
/// This method should normally be called only once at application startup.
/// </summary>
public static void SetErrorReporter(IErrorReporter reporter)
{
_errorReporter = reporter ?? new ConsoleErrorReporter();
}
protected static string s_emailAddress = null;
protected static string s_emailSubject = "Exception Report";
/// <summary>
/// a list of name, string value pairs that will be included in the details of the error report.
/// </summary>
private static StringDictionary s_properties =
new StringDictionary();
private static bool s_isOkToInteractWithUser = true;
private static bool s_justRecordNonFatalMessagesForTesting=false;
private static string s_previousNonFatalMessage;
private static Exception s_previousNonFatalException;
public static void Init(string emailAddress)
{
s_emailAddress = emailAddress;
ErrorReport.AddStandardProperties();
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static string GetExceptionText(Exception error)
{
StringBuilder subject = new StringBuilder();
subject.AppendFormat("Exception: {0}", error.Message);
StringBuilder txt = new StringBuilder();
txt.Append("Msg: ");
txt.Append(error.Message);
try
{
if (error is COMException)
{
txt.Append("\r\nCOM message: ");
txt.Append(new Win32Exception(((COMException) error).ErrorCode).Message);
}
}
catch {}
try
{
txt.Append("\r\nSource: ");
txt.Append(error.Source);
subject.AppendFormat(" in {0}", error.Source);
}
catch {}
try
{
if (error.TargetSite != null)
{
txt.Append("\r\nAssembly: ");
txt.Append(error.TargetSite.DeclaringType.Assembly.FullName);
}
}
catch {}
try
{
txt.Append("\r\nStack: ");
txt.Append(error.StackTrace);
}
catch {}
s_emailSubject = subject.ToString();
txt.Append("\r\n");
return txt.ToString();
}
public static string GetVersionForErrorReporting()
{
Assembly assembly = Assembly.GetEntryAssembly();
if (assembly != null)
{
string version = VersionNumberString;
version += " (apparent build date: ";
try
{
string path = assembly.CodeBase.Replace(@"file:///", "");
version += File.GetLastWriteTimeUtc(path).Date.ToShortDateString() + ")";
}
catch
{
version += "???";
}
#if DEBUG
version += " (Debug version)";
#endif
return version;
}
return "unknown";
}
public static object GetAssemblyAttribute(Type attributeType)
{
Assembly assembly = Assembly.GetEntryAssembly();
if (assembly != null)
{
object[] attributes =
assembly.GetCustomAttributes(attributeType, false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0];
}
}
return null;
}
public static string VersionNumberString
{
get
{
/* object attr = GetAssemblyAttribute(typeof (AssemblyFileVersionAttribute));
if (attr != null)
{
return ((AssemblyFileVersionAttribute) attr).Version;
}
return Application.ProductVersion;
*/
var ver = Assembly.GetEntryAssembly().GetName().Version;
return string.Format("Version {0}.{1}.{2}", ver.Major, ver.Minor, ver.Build);
}
}
public static string UserFriendlyVersionString
{
get
{
var asm = Assembly.GetEntryAssembly();
var ver = asm.GetName().Version;
var file = asm.CodeBase.Replace("file:", string.Empty);
file = file.TrimStart('/');
var fi = new FileInfo(file);
return string.Format(
"Version {0}.{1}.{2} Built on {3}",
ver.Major,
ver.Minor,
ver.Build,
fi.CreationTime.ToString("dd-MMM-yyyy")
);
}
}
// /// ------------------------------------------------------------------------------------
// /// <summary>
// ///make this false during automated testing
// /// </summary>
// /// ------------------------------------------------------------------------------------
// public static bool OkToInteractWithUser
// {
// set { s_isOkToInteractWithUser = value; }
// get { return s_isOkToInteractWithUser; }
// }
/// <summary>
/// this overrides OkToInteractWithUser
/// The test can then retrieve from PreviousNonFatalMessage
/// </summary>
// public static bool JustRecordNonFatalMessagesForTesting
// {
// set { s_justRecordNonFatalMessagesForTesting = value; }
// get { return s_justRecordNonFatalMessagesForTesting; }
// }
/// <summary>
/// for unit test
/// </summary>
// public static string PreviousNonFatalMessage
// {
// get { return s_previousNonFatalMessage; }
// }
/// <summary>
/// use this in unit tests to cleanly check that a message would have been shown.
/// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...}
/// </summary>
public class NonFatalErrorReportExpected :IDisposable
{
private readonly bool previousJustRecordNonFatalMessagesForTesting;
public NonFatalErrorReportExpected()
{
previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting;
s_justRecordNonFatalMessagesForTesting = true;
s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck)
}
public void Dispose()
{
s_justRecordNonFatalMessagesForTesting= previousJustRecordNonFatalMessagesForTesting;
if (s_previousNonFatalException == null && s_previousNonFatalMessage == null)
throw new Exception("Non Fatal Error Report was expected but wasn't generated.");
s_previousNonFatalMessage = null;
}
/// <summary>
/// use this to check the actual contents of the message that was triggered
/// </summary>
public string Message
{
get { return s_previousNonFatalMessage; }
}
}
/// <summary>
/// set this property if you want the dialog to offer to create an e-mail message.
/// </summary>
public static string EmailAddress
{
set { s_emailAddress = value; }
get { return s_emailAddress; }
}
/// <summary>
/// set this property if you want something other than the default e-mail subject
/// </summary>
public static string EmailSubject
{
set { s_emailSubject = value; }
get { return s_emailSubject; }
}
/// <summary>
/// a list of name, string value pairs that will be included in the details of the error report.
/// </summary>
public static StringDictionary Properties
{
get
{
return s_properties;
}
set
{
s_properties = value;
}
}
public static bool IsOkToInteractWithUser
{
get
{
return s_isOkToInteractWithUser;
}
set
{
s_isOkToInteractWithUser = value;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// add a property that he would like included in any bug reports created by this application.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void AddProperty(string label, string contents)
{
//avoid an error if the user changes the value of something,
//which happens in FieldWorks, for example, when you change the language project.
if (s_properties.ContainsKey(label))
{
s_properties.Remove(label);
}
s_properties.Add(label, contents);
}
public static void AddStandardProperties()
{
AddProperty("Version", ErrorReport.GetVersionForErrorReporting());
AddProperty("CommandLine", Environment.CommandLine);
AddProperty("CurrentDirectory", Environment.CurrentDirectory);
AddProperty("MachineName", Environment.MachineName);
AddProperty("OSVersion", GetOperatingSystemLabel());
AddProperty("DotNetVersion", Environment.Version.ToString());
AddProperty("WorkingSet", Environment.WorkingSet.ToString());
AddProperty("UserDomainName", Environment.UserDomainName);
AddProperty("UserName", Environment.UserName);
AddProperty("Culture", CultureInfo.CurrentCulture.ToString());
}
class Version
{
private readonly PlatformID _platform;
private readonly int _major;
private readonly int _minor;
public string Label { get; private set; }
public Version(PlatformID platform, int minor, int major, string label)
{
_platform = platform;
_major = major;
_minor = minor;
Label = label;
}
public bool Match(OperatingSystem os)
{
return os.Version.Minor == _minor &&
os.Version.Major == _major &&
os.Platform == _platform;
}
}
public static string GetOperatingSystemLabel()
{
if(Environment.OSVersion.Platform == PlatformID.Unix)
{
var startInfo = new ProcessStartInfo("lsb_release", "-si -sr -sc");
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
var proc = new Process { StartInfo = startInfo };
try
{
proc.Start();
proc.WaitForExit(500);
if(proc.ExitCode == 0)
{
var si = proc.StandardOutput.ReadLine();
var sr = proc.StandardOutput.ReadLine();
var sc = proc.StandardOutput.ReadLine();
return String.Format("{0} {1} {2}", si, sr, sc);
}
}
catch(Exception)
{ /*lsb_release should work on all supported versions but fall back to the OSVersion.VersionString */ }
}
else
{
var list = new List<Version>();
list.Add(new Version(System.PlatformID.Win32NT,0,5, "Windows 2000"));
list.Add(new Version(System.PlatformID.Win32NT, 1, 5, "Windows XP"));
list.Add(new Version(System.PlatformID.Win32NT, 0, 6, "Vista"));
list.Add(new Version(System.PlatformID.Win32NT, 1, 6, "Windows 7"));
list.Add(new Version(System.PlatformID.Win32NT, 2, 6, "Windows 8"));
foreach (var version in list)
{
if(version.Match(System.Environment.OSVersion))
return version.Label + " " + Environment.OSVersion.ServicePack;
}
}
return System.Environment.OSVersion.VersionString;
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static string GetHiearchicalExceptionInfo(Exception error, ref Exception innerMostException)
{
string x = ErrorReport.GetExceptionText(error);
if (error.InnerException != null)
{
innerMostException = error.InnerException;
x += "**Inner Exception:\r\n";
x += GetHiearchicalExceptionInfo(error.InnerException, ref innerMostException);
}
return x;
}
public static void ReportFatalException(Exception error)
{
UsageReporter.ReportException(true, null, error, null);
_errorReporter.ReportFatalException(error);
}
/// <summary>
/// Put up a message box, unless OkToInteractWithUser is false, in which case throw an Appliciation Exception.
/// This will not report the problem to the developer. Use one of the "report" methods for that.
/// </summary>
public static void NotifyUserOfProblem(string message, params object[] args)
{
NotifyUserOfProblem(new ShowAlwaysPolicy(), message, args);
}
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string messageFmt, params object[] args)
{
return NotifyUserOfProblem(policy, null, default(ErrorResult), messageFmt, args);
}
public static void NotifyUserOfProblem(Exception error, string messageFmt, params object[] args)
{
NotifyUserOfProblem(new ShowAlwaysPolicy(), error, messageFmt, args);
}
public static void NotifyUserOfProblem(IRepeatNoticePolicy policy, Exception error, string messageFmt, params object[] args)
{
var result = NotifyUserOfProblem(policy, "Details", ErrorResult.Yes, messageFmt, args);
if (result == ErrorResult.Yes)
{
ErrorReport.ReportNonFatalExceptionWithMessage(error, string.Format(messageFmt, args));
}
UsageReporter.ReportException(false, null, error, String.Format(messageFmt, args));
}
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy,
string alternateButton1Label,
ErrorResult resultIfAlternateButtonPressed,
string messageFmt,
params object[] args)
{
var message = string.Format(messageFmt, args);
if (s_justRecordNonFatalMessagesForTesting)
{
s_previousNonFatalMessage = message;
return ErrorResult.OK;
}
return _errorReporter.NotifyUserOfProblem(policy, alternateButton1Label, resultIfAlternateButtonPressed, message);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// </summary>
public static void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args)
{
_errorReporter.ReportNonFatalExceptionWithMessage(error, message, args);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// Use this one only when you don't have an exception (else you're not reporting the exception's message)
/// </summary>
public static void ReportNonFatalMessageWithStackTrace(string message, params object[] args)
{
_errorReporter.ReportNonFatalMessageWithStackTrace(message, args);
}
/// <summary>
/// Bring up a "green box" that let's them send in a report, then exit.
/// </summary>
public static void ReportFatalMessageWithStackTrace(string message, params object[] args)
{
_errorReporter.ReportFatalMessageWithStackTrace(message, args);
}
/// <summary>
/// Bring up a "yellow box" that lets them send in a report, then return to the program.
/// </summary>
public static void ReportNonFatalException(Exception exception)
{
ReportNonFatalException(exception, new ShowAlwaysPolicy());
}
/// <summary>
/// Allow user to report an exception even though the program doesn't need to exit
/// </summary>
public static void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy)
{
if (s_justRecordNonFatalMessagesForTesting)
{
ErrorReport.s_previousNonFatalException = exception;
return;
}
_errorReporter.ReportNonFatalException(exception, policy);
UsageReporter.ReportException(false, null, exception, null);
}
/// <summary>
/// this is for interacting with test code which doesn't want to allow an actual UI
/// </summary>
public class ProblemNotificationSentToUserException : ApplicationException
{
public ProblemNotificationSentToUserException(string message) : base(message) {}
}
/// <summary>
/// this is for interacting with test code which doesn't want to allow an actual UI
/// </summary>
public class NonFatalExceptionWouldHaveBeenMessageShownToUserException : ApplicationException
{
public NonFatalExceptionWouldHaveBeenMessageShownToUserException(Exception e) : base(e.Message, e) { }
}
}
public interface IRepeatNoticePolicy
{
bool ShouldShowErrorReportDialog(Exception exception);
bool ShouldShowMessage(string message);
string ReoccurenceMessage
{ get;
}
}
public class ShowAlwaysPolicy :IRepeatNoticePolicy
{
public bool ShouldShowErrorReportDialog(Exception exception)
{
return true;
}
public bool ShouldShowMessage(string message)
{
return true;
}
public string ReoccurenceMessage
{
get { return string.Empty; }
}
}
public class ShowOncePerSessionBasedOnExactMessagePolicy :IRepeatNoticePolicy
{
private static List<string> _alreadyReportedMessages = new List<string>();
public bool ShouldShowErrorReportDialog(Exception exception)
{
return ShouldShowMessage(exception.Message);
}
public bool ShouldShowMessage(string message)
{
if(_alreadyReportedMessages.Contains(message))
return false;
_alreadyReportedMessages.Add(message);
return true;
}
public string ReoccurenceMessage
{
get { return "This message will not be shown again this session."; }
}
public static void Reset()
{
_alreadyReportedMessages.Clear();
}
}
}
| |
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using ReactNative.UIManager;
using System;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace ReactNative.Tests.UIManager
{
using UITestMethodAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AppContainer.UITestMethodAttribute;
[TestClass]
public class BorderedCanvasTests
{
[UITestMethod]
public void BorderedCanvas_ArgumentExceptions()
{
var canvas = new BorderedCanvas();
AssertEx.Throws<ArgumentNullException>(
() => canvas.Children.CopyTo(null, 0),
ex => Assert.AreEqual("array", ex.ParamName));
AssertEx.Throws<ArgumentOutOfRangeException>(
() => canvas.Children.RemoveAt(-1),
ex => Assert.AreEqual("index", ex.ParamName));
AssertEx.Throws<ArgumentOutOfRangeException>(
() => canvas.Children.Insert(-1, null),
ex => Assert.AreEqual("index", ex.ParamName));
AssertEx.Throws<ArgumentOutOfRangeException>(
() => canvas.Children.CopyTo(new UIElement[0], -1),
ex => Assert.AreEqual("arrayIndex", ex.ParamName));
canvas.Children.Add(new Canvas());
AssertEx.Throws<ArgumentException>(
() => canvas.Children.CopyTo(new UIElement[0], 0),
ex => Assert.AreEqual("array", ex.ParamName));
}
[UITestMethod]
public void BorderedCanvas_CreateBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
Assert.AreEqual(1, ((Canvas)canvas).Children.Count);
canvas = new BorderedCanvas();
canvas.BorderThickness = new Thickness(10);
Assert.AreEqual(1, ((Canvas)canvas).Children.Count);
}
[UITestMethod]
public void BorderedCanvas_TransferBackgroundAndBorderBrush()
{
var canvas = new BorderedCanvas();
var backgroundBrush = new SolidColorBrush(Colors.Blue);
var borderBrush = new SolidColorBrush(Colors.Red);
canvas.Background = backgroundBrush;
canvas.BorderBrush = borderBrush;
Assert.AreEqual(0, ((Canvas)canvas).Children.Count);
canvas.BorderThickness = new Thickness(10);
Assert.AreEqual(1, ((Canvas)canvas).Children.Count);
var border = ((Canvas)canvas).Children[0] as Border;
Assert.IsNotNull(border);
Assert.AreEqual(backgroundBrush, border.Background);
Assert.AreEqual(borderBrush, border.BorderBrush);
Assert.AreEqual(null, ((Canvas)canvas).Background);
}
[UITestMethod]
public void BorderedCanvas_AddAfterBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
Assert.AreEqual(0, canvas.Children.Count);
var child = new Canvas();
canvas.Children.Add(child);
Assert.AreEqual(2, ((Canvas)canvas).Children.Count);
Assert.AreSame(child, canvas.Children[0]);
Assert.AreSame(child, ((Canvas)canvas).Children[1]);
}
[UITestMethod]
public void BorderedCanvas_AddBeforeBorder()
{
var canvas = new BorderedCanvas();
var child = new Canvas();
canvas.Children.Add(child);
Assert.AreEqual(1, ((Canvas)canvas).Children.Count);
Assert.AreSame(child, canvas.Children[0]);
Assert.AreSame(child, ((Canvas)canvas).Children[0]);
canvas.CornerRadius = new CornerRadius(10);
Assert.AreEqual(2, ((Canvas)canvas).Children.Count);
Assert.AreSame(child, canvas.Children[0]);
Assert.AreSame(child, ((Canvas)canvas).Children[1]);
}
[UITestMethod]
public void BorderedCanvas_IsNotReadOnly()
{
var canvas = new BorderedCanvas();
Assert.IsFalse(canvas.Children.IsReadOnly);
}
[UITestMethod]
public void BorderedCanvas_DoesNotContainBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var border = (Border)((Canvas)canvas).Children[0];
Assert.IsFalse(canvas.Children.Contains(border));
}
[UITestMethod]
public void BorderedCanvas_IndexOfBorderLessThanZero()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var border = (Border)((Canvas)canvas).Children[0];
Assert.IsTrue(canvas.Children.IndexOf(border) < 0);
}
[UITestMethod]
public void BorderedCanvas_DoesNotContainNonChild()
{
var canvas = new BorderedCanvas();
Assert.IsFalse(canvas.Children.Contains(new Canvas()));
}
[UITestMethod]
public void BorderedCanvas_IndexOfNonChildLessThanZero()
{
var canvas = new BorderedCanvas();
Assert.IsTrue(canvas.Children.IndexOf(new Canvas()) < 0);
}
[UITestMethod]
public void BorderedCanvas_ContainsChild()
{
var canvas = new BorderedCanvas();
var child = new Canvas();
canvas.Children.Add(child);
Assert.IsTrue(canvas.Children.Contains(child));
}
[UITestMethod]
public void BorderedCanvas_IndexOfChildBeforeBorder()
{
var canvas = new BorderedCanvas();
var child = new Canvas();
canvas.Children.Add(child);
Assert.AreEqual(0, canvas.Children.IndexOf(child));
canvas.CornerRadius = new CornerRadius(10);
Assert.AreEqual(0, canvas.Children.IndexOf(child));
}
[UITestMethod]
public void BorderedCanvas_IndexOfChildAfterBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var child = new Canvas();
canvas.Children.Add(child);
Assert.AreEqual(0, canvas.Children.IndexOf(child));
}
[UITestMethod]
public void BorderedCanvas_CopyToWithoutBorder()
{
var canvas = new BorderedCanvas();
var c1 = new Canvas();
var c2 = new Canvas();
var c3 = new Canvas();
canvas.Children.Add(c1);
canvas.Children.Add(c2);
canvas.Children.Add(c3);
var arr = new UIElement[4];
canvas.Children.CopyTo(arr, 1);
Assert.AreSame(c1, arr[1]);
Assert.AreSame(c2, arr[2]);
Assert.AreSame(c3, arr[3]);
}
[UITestMethod]
public void BorderedCanvas_CopyToWithBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var child = new Canvas();
canvas.Children.Add(child);
var arr = new UIElement[1];
canvas.Children.CopyTo(arr, 0);
Assert.AreSame(child, arr[0]);
}
[UITestMethod]
public void BorderedCanvas_InsertWithoutBorder()
{
var canvas = new BorderedCanvas();
var c1 = new Canvas();
var c2 = new Canvas();
canvas.Children.Insert(0, c1);
canvas.Children.Insert(0, c2);
Assert.AreSame(c1, ((Canvas)canvas).Children[1]);
Assert.AreSame(c2, ((Canvas)canvas).Children[0]);
}
[UITestMethod]
public void BorderedCanvas_InsertWithBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var child = new Canvas();
canvas.Children.Insert(0, child);
Assert.AreSame(child, ((Canvas)canvas).Children[1]);
}
[UITestMethod]
public void BorderedCanvas_RemoveWithoutBorder()
{
var canvas = new BorderedCanvas();
var child = new Canvas();
canvas.Children.Add(child);
Assert.IsTrue(canvas.Children.Remove(child));
}
[UITestMethod]
public void BorderedCanvas_RemoveWithBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var child = new Canvas();
canvas.Children.Add(child);
Assert.IsTrue(canvas.Children.Remove(child));
}
[UITestMethod]
public void BorderedCanvas_DoesNotRemoveBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var border = ((Canvas)canvas).Children[0];
Assert.IsFalse(canvas.Children.Remove(border));
}
[UITestMethod]
public void BorderedCanvas_RemoveNonChild()
{
var canvas = new BorderedCanvas();
Assert.IsFalse(canvas.Children.Remove(new Canvas()));
}
[UITestMethod]
public void BorderedCanvas_RemoveNonChildAfterBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
Assert.IsFalse(canvas.Children.Remove(new Canvas()));
}
[UITestMethod]
public void BorderedCanvas_RemoveAtWithoutBorder()
{
var canvas = new BorderedCanvas();
var child = new Canvas();
canvas.Children.Add(child);
canvas.Children.RemoveAt(0);
Assert.IsFalse(canvas.Children.Contains(child));
}
[UITestMethod]
public void BorderedCanvas_RemoveAtAfterBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var child = new Canvas();
canvas.Children.Add(child);
canvas.Children.RemoveAt(0);
Assert.IsFalse(canvas.Children.Contains(child));
Assert.AreEqual(1, ((Canvas)canvas).Children.Count);
}
[UITestMethod]
public void BorderedCanvas_ClearWithoutBorder()
{
var canvas = new BorderedCanvas();
var child = new Canvas();
canvas.Children.Add(child);
canvas.Children.Clear();
Assert.AreEqual(0, ((Canvas)canvas).Children.Count);
}
[UITestMethod]
public void BorderedCanvas_ClearAfterBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var child = new Canvas();
canvas.Children.Add(child);
canvas.Children.Clear();
Assert.AreEqual(1, ((Canvas)canvas).Children.Count);
}
[UITestMethod]
public void BorderedCanvas_GetEnumerator()
{
var canvas = new BorderedCanvas();
var c1 = new Canvas();
var c2 = new Canvas();
canvas.Children.Add(c1);
canvas.Children.Add(c2);
var e = canvas.Children.GetEnumerator();
Assert.IsTrue(e.MoveNext());
Assert.AreSame(c1, e.Current);
Assert.IsTrue(e.MoveNext());
Assert.AreSame(c2, e.Current);
Assert.IsFalse(e.MoveNext());
}
[UITestMethod]
public void BorderedCanvas_GetEnumeratorAfterBorder()
{
var canvas = new BorderedCanvas();
canvas.CornerRadius = new CornerRadius(10);
var c1 = new Canvas();
var c2 = new Canvas();
canvas.Children.Add(c1);
canvas.Children.Add(c2);
var e = canvas.Children.GetEnumerator();
Assert.IsTrue(e.MoveNext());
Assert.AreSame(c1, e.Current);
Assert.IsTrue(e.MoveNext());
Assert.AreSame(c2, e.Current);
Assert.IsFalse(e.MoveNext());
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team 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.Text;
using OpenMetaverse;
namespace OpenMetaverse.Packets
{
/// <summary>
/// Thrown when a packet could not be successfully deserialized
/// </summary>
public class MalformedDataException : ApplicationException
{
/// <summary>
/// Default constructor
/// </summary>
public MalformedDataException() { }
/// <summary>
/// Constructor that takes an additional error message
/// </summary>
/// <param name="Message">An error message to attach to this exception</param>
public MalformedDataException(string Message)
: base(Message)
{
this.Source = "Packet decoding";
}
}
/// <summary>
/// The header of a message template packet. Either 5, 6, or 8 bytes in
/// length at the beginning of the packet, and encapsulates any
/// appended ACKs at the end of the packet as well
/// </summary>
public abstract class Header
{
/// <summary>Raw header data, does not include appended ACKs</summary>
public byte[] Data;
/// <summary>Raw value of the flags byte</summary>
public byte Flags
{
get { return Data[0]; }
set { Data[0] = value; }
}
/// <summary>Reliable flag, whether this packet requires an ACK</summary>
public bool Reliable
{
get { return (Data[0] & Helpers.MSG_RELIABLE) != 0; }
set { if (value) { Data[0] |= (byte)Helpers.MSG_RELIABLE; } else { byte mask = (byte)Helpers.MSG_RELIABLE ^ 0xFF; Data[0] &= mask; } }
}
/// <summary>Resent flag, whether this same packet has already been
/// sent</summary>
public bool Resent
{
get { return (Data[0] & Helpers.MSG_RESENT) != 0; }
set { if (value) { Data[0] |= (byte)Helpers.MSG_RESENT; } else { byte mask = (byte)Helpers.MSG_RESENT ^ 0xFF; Data[0] &= mask; } }
}
/// <summary>Zerocoded flag, whether this packet is compressed with
/// zerocoding</summary>
public bool Zerocoded
{
get { return (Data[0] & Helpers.MSG_ZEROCODED) != 0; }
set { if (value) { Data[0] |= (byte)Helpers.MSG_ZEROCODED; } else { byte mask = (byte)Helpers.MSG_ZEROCODED ^ 0xFF; Data[0] &= mask; } }
}
/// <summary>Appended ACKs flag, whether this packet has ACKs appended
/// to the end</summary>
public bool AppendedAcks
{
get { return (Data[0] & Helpers.MSG_APPENDED_ACKS) != 0; }
set { if (value) { Data[0] |= (byte)Helpers.MSG_APPENDED_ACKS; } else { byte mask = (byte)Helpers.MSG_APPENDED_ACKS ^ 0xFF; Data[0] &= mask; } }
}
/// <summary>Packet sequence number</summary>
public uint Sequence
{
get { return (uint)((Data[1] << 24) + (Data[2] << 16) + (Data[3] << 8) + Data[4]); }
set
{
Data[1] = (byte)(value >> 24); Data[2] = (byte)(value >> 16);
Data[3] = (byte)(value >> 8); Data[4] = (byte)(value % 256);
}
}
/// <summary>Numeric ID number of this packet</summary>
public abstract ushort ID { get; set; }
/// <summary>Frequency classification of this packet, Low Medium or
/// High</summary>
public abstract PacketFrequency Frequency { get; }
/// <summary>Convert this header to a byte array, not including any
/// appended ACKs</summary>
public abstract void ToBytes(byte[] bytes, ref int i);
/// <summary>Array containing all the appended ACKs of this packet</summary>
public uint[] AckList;
public abstract void FromBytes(byte[] bytes, ref int pos, ref int packetEnd);
/// <summary>
/// Convert the AckList to a byte array, used for packet serializing
/// </summary>
/// <param name="bytes">Reference to the target byte array</param>
/// <param name="i">Beginning position to start writing to in the byte
/// array, will be updated with the ending position of the ACK list</param>
public void AcksToBytes(byte[] bytes, ref int i)
{
foreach (uint ack in AckList)
{
bytes[i++] = (byte)((ack >> 24) % 256);
bytes[i++] = (byte)((ack >> 16) % 256);
bytes[i++] = (byte)((ack >> 8) % 256);
bytes[i++] = (byte)(ack % 256);
}
if (AckList.Length > 0) { bytes[i++] = (byte)AckList.Length; }
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pos"></param>
/// <param name="packetEnd"></param>
/// <returns></returns>
public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd)
{
if (bytes[6] == 0xFF)
{
if (bytes[7] == 0xFF)
{
return new LowHeader(bytes, ref pos, ref packetEnd);
}
else
{
return new MediumHeader(bytes, ref pos, ref packetEnd);
}
}
else
{
return new HighHeader(bytes, ref pos, ref packetEnd);
}
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="packetEnd"></param>
protected void CreateAckList(byte[] bytes, ref int packetEnd)
{
if (AppendedAcks)
{
try
{
int count = bytes[packetEnd--];
AckList = new uint[count];
for (int i = 0; i < count; i++)
{
AckList[i] = (uint)(
(bytes[(packetEnd - i * 4) - 3] << 24) |
(bytes[(packetEnd - i * 4) - 2] << 16) |
(bytes[(packetEnd - i * 4) - 1] << 8) |
(bytes[(packetEnd - i * 4) ]));
}
packetEnd -= (count * 4);
}
catch (Exception)
{
AckList = new uint[0];
throw new MalformedDataException();
}
}
else
{
AckList = new uint[0];
}
}
}
/// <summary>
///
/// </summary>
public class LowHeader : Header
{
/// <summary></summary>
public override ushort ID
{
get { return (ushort)((Data[8] << 8) + Data[9]); }
set { Data[8] = (byte)(value >> 8); Data[9] = (byte)(value % 256); }
}
/// <summary></summary>
public override PacketFrequency Frequency { get { return PacketFrequency.Low; } }
/// <summary>
///
/// </summary>
public LowHeader()
{
Data = new byte[10];
Data[6] = Data[7] = 0xFF;
AckList = new uint[0];
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pos"></param>
/// <param name="packetEnd"></param>
public LowHeader(byte[] bytes, ref int pos, ref int packetEnd)
{
FromBytes(bytes, ref pos, ref packetEnd);
}
override public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd)
{
if (bytes.Length < 10) { throw new MalformedDataException(); }
Data = new byte[10];
Buffer.BlockCopy(bytes, 0, Data, 0, 10);
if ((bytes[0] & Helpers.MSG_ZEROCODED) != 0 && bytes[8] == 0)
{
if (bytes[9] == 1)
{
Data[9] = bytes[10];
}
else
{
throw new MalformedDataException();
}
}
pos = 10;
CreateAckList(bytes, ref packetEnd);
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="i"></param>
public override void ToBytes(byte[] bytes, ref int i)
{
Buffer.BlockCopy(Data, 0, bytes, i, 10);
i += 10;
}
}
/// <summary>
///
/// </summary>
public class MediumHeader : Header
{
/// <summary></summary>
public override ushort ID
{
get { return (ushort)Data[7]; }
set { Data[7] = (byte)value; }
}
/// <summary></summary>
public override PacketFrequency Frequency { get { return PacketFrequency.Medium; } }
/// <summary>
///
/// </summary>
public MediumHeader()
{
Data = new byte[8];
Data[6] = 0xFF;
AckList = new uint[0];
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pos"></param>
/// <param name="packetEnd"></param>
public MediumHeader(byte[] bytes, ref int pos, ref int packetEnd)
{
FromBytes(bytes, ref pos, ref packetEnd);
}
override public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd)
{
if (bytes.Length < 8) { throw new MalformedDataException(); }
Data = new byte[8];
Buffer.BlockCopy(bytes, 0, Data, 0, 8);
pos = 8;
CreateAckList(bytes, ref packetEnd);
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="i"></param>
public override void ToBytes(byte[] bytes, ref int i)
{
Buffer.BlockCopy(Data, 0, bytes, i, 8);
i += 8;
}
}
/// <summary>
///
/// </summary>
public class HighHeader : Header
{
/// <summary></summary>
public override ushort ID
{
get { return (ushort)Data[6]; }
set { Data[6] = (byte)value; }
}
/// <summary></summary>
public override PacketFrequency Frequency { get { return PacketFrequency.High; } }
/// <summary>
///
/// </summary>
public HighHeader()
{
Data = new byte[7];
AckList = new uint[0];
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pos"></param>
/// <param name="packetEnd"></param>
public HighHeader(byte[] bytes, ref int pos, ref int packetEnd)
{
FromBytes(bytes, ref pos, ref packetEnd);
}
override public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd)
{
if (bytes.Length < 7) { throw new MalformedDataException(); }
Data = new byte[7];
Buffer.BlockCopy(bytes, 0, Data, 0, 7);
pos = 7;
CreateAckList(bytes, ref packetEnd);
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="i"></param>
public override void ToBytes(byte[] bytes, ref int i)
{
Buffer.BlockCopy(Data, 0, bytes, i, 7);
i += 7;
}
}
/// <summary>
/// A block of data in a packet. Packets are composed of one or more blocks,
/// each block containing one or more fields
/// </summary>
public abstract class PacketBlock
{
/// <summary>Current length of the data in this packet</summary>
public abstract int Length { get; }
/// <summary>
/// Create a block from a byte array
/// </summary>
/// <param name="bytes">Byte array containing the serialized block</param>
/// <param name="i">Starting position of the block in the byte array.
/// This will point to the data after the end of the block when the
/// call returns</param>
public abstract void FromBytes(byte[] bytes, ref int i);
/// <summary>
/// Serialize this block into a byte array
/// </summary>
/// <param name="bytes">Byte array to serialize this block into</param>
/// <param name="i">Starting position in the byte array to serialize to.
/// This will point to the position directly after the end of the
/// serialized block when the call returns</param>
public abstract void ToBytes(byte[] bytes, ref int i);
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class IdentifiersShouldNotHaveIncorrectSuffixTests : DiagnosticAnalyzerTestBase
{
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromAttribute()
{
VerifyCSharp(
@"public class MyBadAttribute {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadAttribute",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.AttributeSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromAttribute()
{
VerifyBasic(
@"Public Class MyBadAttribute
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadAttribute",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.AttributeSuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromAttribute()
{
VerifyCSharp(
@"using System;
public class MyAttribute : Attribute {}
public class MyOtherAttribute : MyAttribute {}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromAttribute()
{
VerifyBasic(
@"Imports System
Public Class MyAttribute
Inherits Attribute
End Class
Public Class MyOtherAttribute
Inherits MyAttribute
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromEventArgs()
{
VerifyCSharp(
"public class MyBadEventArgs {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadEventArgs",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.EventArgsSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromEventArgs()
{
VerifyBasic(
@"Public Class MyBadEventArgs
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadEventArgs",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.EventArgsSuffix));
}
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromEventArgs()
{
VerifyCSharp(
@"using System;
public class MyEventArgs : EventArgs {}
public class MyOtherEventArgs : MyEventArgs {}");
}
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromEventArgs()
{
VerifyBasic(
@"Imports System
Public Class MyEventArgs
Inherits EventArgs
End Class
Public Class MyOtherEventArgs
Inherits MyEventArgs
End Class");
}
// There's no need for a test case where the type is derived from EventHandler
// or EventHandler<T>, because they're sealed.
[Fact]
public void CA1711_CSharp_Diagnostic_TypeNameEndsWithEventHandler()
{
VerifyCSharp(
@"public class MyBadEventHandler {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadEventHandler",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.EventHandlerSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeNameEndsWithEventHandler()
{
VerifyBasic(
@"Public Class MyBadEventHandler
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadEventHandler",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.EventHandlerSuffix));
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromException()
{
VerifyCSharp(
@"public class MyBadException {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadException",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExceptionSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromException()
{
VerifyBasic(
@"Public Class MyBadException
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadException",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExceptionSuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromException()
{
VerifyCSharp(
@"using System;
public class MyException : Exception {}
public class MyOtherException : MyException {}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromException()
{
VerifyBasic(
@"Imports System
Public Class MyException
Inherits Exception
End Class
Public Class MyOtherException
Inherits MyException
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromIPermission()
{
VerifyCSharp(
@"public class MyBadPermission {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadPermission",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.PermissionSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromIPermission()
{
VerifyBasic(
@"Public Class MyBadPermission
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadPermission",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.PermissionSuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromIPermission()
{
VerifyCSharp(
@"using System.Security;
public class MyPermission : IPermission
{
public IPermission Copy() { return null; }
public void Demand() {}
public void FromXml(SecurityElement e) {}
public IPermission Intersect(IPermission other) { return null; }
public bool IsSubsetOf(IPermission target) { return false; }
public SecurityElement ToXml() { return null; }
public IPermission Union(IPermission other) { return null; }
}
public class MyOtherPermission : MyPermission {}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromIPermission()
{
VerifyBasic(
@"Imports System.Security
Public Class MyPermission
Implements IPermission
Public Sub Demand() Implements IPermission.Demand
End Sub
Public Sub FromXml(e As SecurityElement) Implements ISecurityEncodable.FromXml
End Sub
Public Function Copy() As IPermission Implements IPermission.Copy
Return Nothing
End Function
Public Function Intersect(target As IPermission) As IPermission Implements IPermission.Intersect
Return Nothing
End Function
Public Function IsSubsetOf(target As IPermission) As Boolean Implements IPermission.IsSubsetOf
Return False
End Function
Public Function ToXml() As SecurityElement Implements ISecurityEncodable.ToXml
Return Nothing
End Function
Public Function Union(target As IPermission) As IPermission Implements IPermission.Union
Return Nothing
End Function
End Class
Public Class MyOtherPermission
Inherits MyPermission
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromStream()
{
VerifyCSharp(
@"public class MyBadStream {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadStream",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.StreamSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromStream()
{
VerifyBasic(
@"Public Class MyBadStream
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadStream",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.StreamSuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromStream()
{
VerifyCSharp(
@"using System.IO;
public class MyStream : Stream
{
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => 0L;
public override long Position
{
get { return 0L; }
set { }
}
public override void Flush() { }
public override int Read(byte[] buffer, int offset, int count)
{
return 0;
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0L;
}
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
}
public class MyOtherStream : MyStream { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromStream()
{
VerifyBasic(
@"Imports System.IO
Public Class MyStream
Inherits Stream
Public Overrides ReadOnly Property CanRead As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property CanSeek As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property CanWrite As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Length As Long
Get
Return 0
End Get
End Property
Public Overrides Property Position As Long
Get
Return 0
End Get
Set(value As Long)
End Set
End Property
Public Overrides Sub Flush()
End Sub
Public Overrides Sub SetLength(value As Long)
End Sub
Public Overrides Sub Write(buffer() As Byte, offset As Integer, count As Integer)
End Sub
Public Overrides Function Read(buffer() As Byte, offset As Integer, count As Integer) As Integer
Return 0
End Function
Public Overrides Function Seek(offset As Long, origin As SeekOrigin) As Long
Return 0
End Function
Public Sub SomeMethodNotPresentInStream()
End Sub
End Class
Public Class MyOtherStream
Inherits MyStream
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeNameEndsWithDelegate()
{
VerifyCSharp(
@"public delegate void MyBadDelegate();",
GetCSharpResultAt(
1, 22,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDelegate",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.DelegateSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeNameEndsWithDelegate()
{
VerifyBasic(
@"Public Delegate Sub MyBadDelegate()",
GetBasicResultAt(
1, 21,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDelegate",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.DelegateSuffix));
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeNameEndsWithEnum()
{
VerifyCSharp(
@"public enum MyBadEnum { X }",
GetCSharpResultAt(
1, 13,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadEnum",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.EnumSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeNameEndsWithEnum()
{
VerifyBasic(
@"Public Enum MyBadEnum
X
End Enum",
GetBasicResultAt(
1, 13,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadEnum",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.EnumSuffix));
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeNameEndsWithImpl()
{
VerifyCSharp(
@"public class MyClassImpl {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyClassImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeNameEndsWithImpl()
{
VerifyBasic(
@"Public Class MyClassImpl
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyClassImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeNamingRulesAreCaseSensitiveEvenInVB()
{
VerifyBasic(
@"Public Class MyClassimpl
End Class");
}
[Fact]
public void CSharp_No_Diagnostic_MisnamedTypeIsInternal()
{
VerifyCSharp(
@"internal class MyClassImpl {}");
}
[Fact]
public void Basic_No_Diagnostic_MisnamedTypeIsInternal()
{
VerifyBasic(
@"Friend Class MyClassImpl
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_MisnamedTypeIsNestedPublic()
{
VerifyCSharp(
@"public class MyClass
{
public class MyNestedClassImpl {}
}",
GetCSharpResultAt(
3, 18,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyNestedClassImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_MisnamedTypeIsNestedPublic()
{
VerifyBasic(
@"Public Class [MyClass]
Public Class MyNestedClassImpl
End Class
End Class",
GetBasicResultAt(
2, 18,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyNestedClassImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_CSharp_Diagnostic_MisnamedTypeIsNestedProtected()
{
VerifyCSharp(
@"public class MyClass
{
protected class MyNestedClassImpl {}
}",
GetCSharpResultAt(
3, 21,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyNestedClassImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_MisnamedTypeIsNestedProtected()
{
VerifyBasic(
@"Public Class [MyClass]
Protected Class MyNestedClassImpl
End Class
End Class",
GetBasicResultAt(
2, 21,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyNestedClassImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_MisnamedTypeIsNestedPrivate()
{
VerifyCSharp(
@"public class MyClass
{
private class MyNestedClassImpl {}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_MisnamedTypeIsNestedPrivate()
{
VerifyBasic(
@"Public Class [MyClass]
Private Class MyNestedClassImpl
End Class
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromDictionary()
{
VerifyCSharp(
@"public class MyBadDictionary {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDictionary",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.DictionarySuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromDictionary()
{
VerifyBasic(
@"Public Class MyBadDictionary
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDictionary",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.DictionarySuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeImplementsIReadOnlyDictionary()
{
VerifyCSharp(
@"using System.Collections;
using System.Collections.Generic;
public class MyReadOnlyDictionary : IReadOnlyDictionary<string, int>
{
public int this[string key] => 0;
public int Count => 0;
public IEnumerable<string> Keys => new string[0];
public IEnumerable<int> Values => new int[0];
public bool ContainsKey(string key) { return false; }
public IEnumerator<KeyValuePair<string, int>> GetEnumerator() { return null; }
IEnumerator IEnumerable.GetEnumerator() { return null; }
public bool TryGetValue(string key, out int value)
{
value = -1;
return false;
}
}");
}
[Fact]
public void CA1711_BasicNoDiagnostic_TypeImplementsIReadOnlyDictionary()
{
VerifyBasic(
@"Imports System.Collections
Imports System.Collections.Generic
Public Class MyReadOnlyDictionary
Implements IReadOnlyDictionary(Of String, Integer)
Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of KeyValuePair(Of String, Integer)).Count
Get
Return 0
End Get
End Property
Default Public ReadOnly Property Item(key As String) As Integer Implements IReadOnlyDictionary(Of String, Integer).Item
Get
Return 0
End Get
End Property
Public ReadOnly Property Keys As IEnumerable(Of String) Implements IReadOnlyDictionary(Of String, Integer).Keys
Get
Return New String() { }
End Get
End Property
Public ReadOnly Property Values As IEnumerable(Of Integer) Implements IReadOnlyDictionary(Of String, Integer).Values
Get
Return New Integer() { }
End Get
End Property
Public Function ContainsKey(key As String) As Boolean Implements IReadOnlyDictionary(Of String, Integer).ContainsKey
Return False
End Function
Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of String, Integer)) Implements IEnumerable(Of KeyValuePair(Of String, Integer)).GetEnumerator
Return Nothing
End Function
Public Function TryGetValue(key As String, ByRef value As Integer) As Boolean Implements IReadOnlyDictionary(Of String, Integer).TryGetValue
value = -1
Return False
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeImplementsNonGenericIDictionary()
{
VerifyCSharp(
@"using System;
using System.Collections;
using System.Runtime.Serialization;
public class MyNonGenericDictionary : IDictionary
{
protected MyNonGenericDictionary(SerializationInfo info, StreamingContext context) { }
public object this[object key]
{
get { return null; }
set { }
}
public int Count => 0;
public bool IsFixedSize => true;
public bool IsReadOnly => true;
public bool IsSynchronized => false;
public ICollection Keys => null;
public object SyncRoot => null;
public ICollection Values => null;
public void Add(object key, object value) { }
public void Clear() { }
public void CopyTo(Array array, int index) { }
public void Remove(object key) { }
public bool Contains(object key)
{
return false;
}
public IDictionaryEnumerator GetEnumerator()
{
return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
return null;
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeImplementsNonGenericIDictionary()
{
VerifyBasic(
@"Imports System
Imports System.Collections
Imports System.Runtime.Serialization
Public Class MyNonGenericDictionary
Implements IDictionary
Protected Sub New(info As SerializationInfo, context As StreamingContext)
End Sub
Public ReadOnly Property Count As Integer Implements ICollection.Count
Get
Return 0
End Get
End Property
Public ReadOnly Property IsFixedSize As Boolean Implements IDictionary.IsFixedSize
Get
Return True
End Get
End Property
Public ReadOnly Property IsReadOnly As Boolean Implements IDictionary.IsReadOnly
Get
Return True
End Get
End Property
Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
Get
Return False
End Get
End Property
Default Public Property Item(key As Object) As Object Implements IDictionary.Item
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
Public ReadOnly Property Keys As ICollection Implements IDictionary.Keys
Get
Return Nothing
End Get
End Property
Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
Get
Return Nothing
End Get
End Property
Public ReadOnly Property Values As ICollection Implements IDictionary.Values
Get
Return Nothing
End Get
End Property
Public Sub Add(key As Object, value As Object) Implements IDictionary.Add
End Sub
Public Sub Clear() Implements IDictionary.Clear
End Sub
Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
End Sub
Public Sub Remove(key As Object) Implements IDictionary.Remove
End Sub
Public Function Contains(key As Object) As Boolean Implements IDictionary.Contains
Return False
End Function
Public Function GetEnumerator() As IDictionaryEnumerator Implements IDictionary.GetEnumerator
Return Nothing
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromGenericDictionary()
{
VerifyCSharp(
@"using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[Serializable]
public class MyGenericDictionary<K, V> : Dictionary<K, V>
{
protected MyGenericDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromGenericDictionary()
{
VerifyBasic(
@"Imports System
Imports System.Collections.Generic
Imports System.Runtime.Serialization
<Serializable>
Public Class MyGenericDictionary(Of K, V)
Inherits Dictionary(Of K, V)
Protected Sub New(info As SerializationInfo, context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromPartiallyInstantiatedGenericDictionary()
{
VerifyCSharp(
@"using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[Serializable]
public class MyStringDictionary<V> : Dictionary<string, V>
{
protected MyStringDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromPartiallyInstantiatedGenericDictionary()
{
VerifyBasic(
@"Imports System
Imports System.Collections.Generic
Imports System.Runtime.Serialization
<Serializable>
Public Class MyStringDictionary(Of V)
Inherits Dictionary(Of String, V)
Protected Sub New(info As SerializationInfo, context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromFullyInstantiatedGenericDictionary()
{
VerifyCSharp(
@"using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[Serializable]
public class MyStringToIntDictionary : Dictionary<string, int>
{
protected MyStringToIntDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromFullyInstantiatedGenericDictionary()
{
VerifyBasic(
@"Imports System
Imports System.Collections.Generic
Imports System.Runtime.Serialization
<Serializable>
Public Class MyStringToIntDictionary
Inherits Dictionary(Of String, Integer)
Protected Sub New(info As SerializationInfo, context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromCollection()
{
VerifyCSharp(
@"public class MyBadCollection {}",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadCollection",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CollectionSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromCollection()
{
VerifyBasic(
@"Public Class MyBadCollection
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadCollection",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CollectionSuffix));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeImplementsNonGenericICollection()
{
VerifyCSharp(
@"using System.Collections;
public class MyNonGenericCollection : ICollection
{
public int Count => 0;
public bool IsSynchronized => true;
public object SyncRoot => null;
public void CopyTo(System.Array array, int index) { }
public IEnumerator GetEnumerator()
{
return null;
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeImplementsNonGenericICollection()
{
VerifyBasic(
@"Imports System.Collections
Public Class MyNonGenericCollection
Implements ICollection
Public ReadOnly Property Count As Integer Implements ICollection.Count
Get
Return 0
End Get
End Property
Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
Get
Return False
End Get
End Property
Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
Get
Return Nothing
End Get
End Property
Public Sub CopyTo(array As System.Array, index As Integer) Implements ICollection.CopyTo
End Sub
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeImplementsNonGenericIEnumerable()
{
VerifyCSharp(
@"using System.Collections;
public class MyEnumerableCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
return null;
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeImplementsNonGenericIEnumerable()
{
VerifyBasic(
@"Imports System.Collections
Public Class MyEnumerableCollection
Implements IEnumerable
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeImplementsInstantiatedGenericICollection()
{
VerifyCSharp(
@"using System.Collections;
using System.Collections.Generic;
public class MyIntCollection : ICollection<int>
{
public int Count => 0;
public bool IsReadOnly => true;
public void Add(int item) { }
public void Clear() { }
public bool Contains(int item)
{
return false;
}
public void CopyTo(int[] array, int arrayIndex) { }
public IEnumerator<int> GetEnumerator()
{
return null;
}
public bool Remove(int item)
{
return false;
}
IEnumerator IEnumerable.GetEnumerator()
{
return null;
}
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeImplementsInstantiatedGenericICollection()
{
VerifyBasic(
@"Imports System.Collections
Imports System.Collections.Generic
Public Class MyIntCollection
Implements ICollection(Of Integer)
Public ReadOnly Property Count As Integer Implements ICollection(Of Integer).Count
Get
Return 0
End Get
End Property
Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of Integer).IsReadOnly
Get
Return True
End Get
End Property
Public Sub Add(item As Integer) Implements ICollection(Of Integer).Add
End Sub
Public Sub Clear() Implements ICollection(Of Integer).Clear
End Sub
Public Sub CopyTo(array() As Integer, arrayIndex As Integer) Implements ICollection(Of Integer).CopyTo
End Sub
Public Function Contains(item As Integer) As Boolean Implements ICollection(Of Integer).Contains
Return False
End Function
Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Return Nothing
End Function
Public Function Remove(item As Integer) As Boolean Implements ICollection(Of Integer).Remove
Return False
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromNonGenericQueue()
{
VerifyCSharp(
@"using System.Collections;
public class MyNonGenericQueue : Queue { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromNonGenericQueue()
{
VerifyBasic(
@"Imports System.Collections
Public Class MyNonGenericQueue
Inherits Queue
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromGenericQueue()
{
VerifyCSharp(
@"using System.Collections.Generic;
public class MyGenericQueue<T> : Queue<T> { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromGenericQueue()
{
VerifyBasic(
@"Imports System.Collections.Generic
Public Class MyGenericQueue(Of T)
Inherits Queue(Of T)
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromInstantiatedGenericQueue()
{
VerifyCSharp(
@"using System.Collections.Generic;
public class MyIntQueue : Queue<int> { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromInstantiatedGenericQueue()
{
VerifyBasic(
@"Imports System.Collections.Generic
Public Class MyIntQueue
Inherits Queue(Of Integer)
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromQueue()
{
VerifyCSharp(
@"public class MyBadQueue { }",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadQueue",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.QueueSuffix)
);
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromQueue()
{
VerifyBasic(
@"Public Class MyBadQueue
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadQueue",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.QueueSuffix)
);
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromNonGenericStack()
{
VerifyCSharp(
@"using System.Collections;
public class MyNonGenericStack : Stack { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromNonGenericStack()
{
VerifyBasic(
@"Imports System.Collections
Public Class MyNonGenericStack
Inherits Stack
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromGenericStack()
{
VerifyCSharp(
@"using System.Collections.Generic;
public class MyGenericStack<T> : Stack<T> { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromGenericStack()
{
VerifyBasic(
@"Imports System.Collections.Generic
Public Class MyGenericStack(Of T)
Inherits Stack(Of T)
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeDerivesFromInstantiatedGenericStack()
{
VerifyCSharp(
@"using System.Collections.Generic;
public class MyIntStack : Stack<int> { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeDerivesFromInstantiatedGenericStack()
{
VerifyBasic(
@"Imports System.Collections.Generic
Public Class MyIntStack
Inherits Stack(Of Integer)
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDoesNotDeriveFromStack()
{
VerifyCSharp(
@"public class MyBadStack { }",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadStack",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.StackSuffix)
);
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDoesNotDeriveFromStack()
{
VerifyBasic(
@"Public Class MyBadStack
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadStack",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.StackSuffix)
);
}
// MSDN says that DataSet and DataTable can be called "Collection",
// but FxCop disagrees.
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDerivesFromDataSet()
{
VerifyCSharp(
@"using System;
using System.Data;
[Serializable]
public class MyBadDataSetCollection : DataSet { }",
GetCSharpResultAt(
5, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDataSetCollection",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CollectionSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDerivesFromDataSet()
{
VerifyBasic(
@"Imports System
Imports System.Data
<Serializable>
Public Class MyBadDataSetCollection
Inherits DataSet
End Class",
GetBasicResultAt(
5, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDataSetCollection",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CollectionSuffix));
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeDerivesFromDataTable()
{
VerifyCSharp(
@"using System;
using System.Data;
[Serializable]
public class MyBadDataTableCollection : DataTable { }",
GetCSharpResultAt(
5, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDataTableCollection",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CollectionSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeDerivesFromDataTable()
{
VerifyBasic(
@"Imports System
Imports System.Data
<Serializable>
Public Class MyBadDataTableCollection
Inherits DataTable
End Class",
GetBasicResultAt(
5, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNoAlternateRule,
"MyBadDataTableCollection",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CollectionSuffix));
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeNameEndsWithEx()
{
VerifyCSharp(
@"public class MyClassEx { }",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyClassEx"));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeNameEndsWithEx()
{
VerifyBasic(
@"Public Class MyClassEx
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyClassEx"));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_TypeNameNameIsEx()
{
VerifyCSharp(
@"public class Ex { }");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_TypeNameNameIsEx()
{
VerifyBasic(
@"Public Class Ex
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_TypeNameEndsWithNew()
{
VerifyCSharp(
@"public class MyClassNew { }",
GetCSharpResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.NewSuffix,
"MyClassNew"));
}
[Fact]
public void CA1711_Basic_Diagnostic_TypeNameEndsWithNew()
{
VerifyBasic(
@"Public Class MyClassNew
End Class",
GetBasicResultAt(
1, 14,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.TypeNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.NewSuffix,
"MyClassNew"));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_MethodNameEndsWithNew()
{
VerifyCSharp(
@"public class MyClass
{
public void MyMethodNew() { }
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_MethodNameEndsWithNew()
{
VerifyBasic(
@"Public Class [MyClass]
Public Sub MyMethodNew()
End Sub
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_MethodNameEndsWithNewAndMethodNameWithoutNewExistsInSameClass()
{
VerifyCSharp(
@"public class MyBaseClass
{
public void MyMethod() { }
public void MyMethodNew() { }
}",
GetCSharpResultAt(
4, 17,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.NewSuffix,
"MyMethodNew"));
}
[Fact]
public void CA1711_Basic_Diagnostic_MethodNameEndsWithNewAndMethodNameWithoutNewExistsInSameClass()
{
VerifyBasic(
@"Public Class MyBaseClass
Public Sub MyMethod()
End Sub
Public Sub MyMethodNew()
End Sub
End Class",
GetBasicResultAt(
5, 16,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.NewSuffix,
"MyMethodNew"));
}
[Fact]
public void CA1711_CSharp_Diagnostic_MethodNameEndsWithNewAndMethodNameWithoutNewExistsInAncestorClass()
{
VerifyCSharp(
@"public class MyBaseClass
{
public void MyMethod() { }
}
public class MyDerivedClass : MyBaseClass
{
}
public class MyClass : MyDerivedClass
{
public void MyMethodNew() { }
}",
GetCSharpResultAt(
12, 17,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.NewSuffix,
"MyMethodNew"));
}
[Fact]
public void CA1711_Basic_Diagnostic_MethodNameEndsWithNewAndMethodNameWithoutNewExistsInAncestorClass()
{
VerifyBasic(
@"Public Class MyBaseClass
Public Sub MyMethod()
End Sub
End Class
Public Class MyDerivedClass
Inherits MyBaseClass
End Class
Public Class [MyClass]
Inherits MyDerivedClass
Public Sub MyMethodNew()
End Sub
End Class",
GetBasicResultAt(
13, 16,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.NewSuffix,
"MyMethodNew"));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_MethodNameEndingWithNewImplementsInterfaceMethod()
{
VerifyCSharp(
@"public interface MyBaseInterface
{
void MyMethodNew();
}
public interface MyDerivedInterface : MyBaseInterface
{
}
public class MyClass : MyDerivedInterface
{
public void MyMethodNew() { }
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_MethodNameEndsWithNewAndMethodNameWithoutNewExistsInImplementedInterface()
{
VerifyBasic(
@"Public Interface MyBaseInterface
Sub MyMethodNew()
End Interface
Public Interface MyDerivedInterface
Inherits MyBaseInterface
End Interface
Public Class [MyClass]
Implements MyDerivedInterface
Public Sub MyMethodNew() Implements MyBaseInterface.MyMethodNew
End Sub
End Class");
}
[Fact]
public void CA1711_CSharp_Diagnostic_MethodNameEndsWithEx()
{
VerifyCSharp(
@"public class MyClass
{
public void MyMethodEx() { }
}",
GetCSharpResultAt(
3, 17,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyMethodEx"));
;
}
[Fact]
public void CA1711_Basic_Diagnostic_MethodNameEndsWithEx()
{
VerifyBasic(
@"Public Class [MyClass]
Public Sub MyMethodEx()
End Sub
End Class",
GetBasicResultAt(
2, 16,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyMethodEx"));
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_PrivateMethodNameEndsWithEx()
{
VerifyCSharp(
@"public class MyClass
{
private void MyMethodEx() { }
}");
}
[Fact]
public void CA1711_Basic_NoDiagnostic_PrivateMethodNameEndsWithEx()
{
VerifyBasic(
@"Public Class [MyClass]
Private Sub MyMethodEx()
End Sub
End Class");
}
[Fact]
public void CA1711_CSharp_NoDiagnostic_OverriddenMethodNameEndsWithEx()
{
VerifyCSharp(
@"public class MyBaseClass
{
public virtual void MyMethodEx() { }
}
public class MyClass : MyBaseClass
{
public override void MyMethodEx() { }
}",
// Diagnostic for the base class method, but none for the override.
GetCSharpResultAt(
3, 25,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyMethodEx"));
}
[Fact]
public void CA1711_CSharp_Diagnostic_MethodNameEndingWithExImplementsInterfaceMethod()
{
VerifyCSharp(
@"public interface MyBaseInterface
{
void MyMethodEx();
}
public interface MyDerivedInterface : MyBaseInterface
{
}
public class MyClass : MyDerivedInterface
{
public void MyMethodEx() { }
}",
// Diagnostic for the interface method, but none for the implementation.
GetCSharpResultAt(
3, 10,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyMethodEx"));
}
[Fact]
public void CA1711_Basic_Diagnostic_MethodNameEndingWithExImplementsInterfaceMethod()
{
VerifyBasic(
@"Public Interface MyBaseInterface
Sub MyMethodEx()
End Interface
Public Interface MyDerivedInterface
Inherits MyBaseInterface
End Interface
Public Class [MyClass]
Implements MyDerivedInterface
Public Sub MyMethodEx() Implements MyBaseInterface.MyMethodEx
End Sub
End Class",
// Diagnostic for the interface method, but none for the implementation.
GetBasicResultAt(
2, 9,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyMethodEx"));
}
[Fact]
public void CA1711_CSharp_Diagnostic_MethodNameEndsWithImpl()
{
VerifyCSharp(
@"public class MyClass
{
public void MyMethodImpl() { }
}",
GetCSharpResultAt(
3, 17,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyMethodImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_Basic_Diagnostic_MethodNameEndsWithImpl()
{
VerifyBasic(
@"Public Class [MyClass]
Public Sub MyMethodImpl()
End Sub
End Class",
GetBasicResultAt(
2, 16,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberWithAlternateRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ImplSuffix,
"MyMethodImpl",
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.CoreSuffix));
}
[Fact]
public void CA1711_Basic_NoDiagnostic_OverriddenMethodNameEndsWithEx()
{
VerifyBasic(
@"Public Class MyBaseClass
Public Overridable Sub MyMethodEx()
End Sub
End Class
Public Class [MyClass]
Inherits MyBaseClass
Public Overrides Sub MyMethodEx()
End Sub
End Class",
// Diagnostic for the base class method, but none for the override.
GetBasicResultAt(
2, 28,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyMethodEx"));
}
[Fact]
public void CA1711_CSharp_Diagnostic_EventNameEndsWithEx()
{
VerifyCSharp(
@"using System;
public class MyClass
{
public delegate void EventCallback(object sender, EventArgs e);
public event EventCallback MyEventEx;
}",
GetCSharpResultAt(
6, 32,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyEventEx"));
}
[Fact]
public void CA1711_Basic_Diagnostic_EventNameEndsWithEx()
{
VerifyBasic(
@"Imports System
Public Class [MyClass]
Public Delegate Sub EventCallback(sender As Object, e As EventArgs)
Public Event MyEventEx As EventCallback
End Class",
GetBasicResultAt(
5, 18,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyEventEx"));
}
[Fact]
public void CA1711_CSharp_Diagnostic_PropertyNameEndsWithEx()
{
VerifyCSharp(
@"public class MyClass
{
public int MyPropertyEx { get; set; }
}",
GetCSharpResultAt(
3, 16,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyPropertyEx"));
}
[Fact]
public void CA1711_Basic_Diagnostic_PropertyNameEndsWithEx()
{
VerifyBasic(
@"Public Class [MyClass]
Public Property MyPropertyEx As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class",
GetBasicResultAt(
2, 21,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyPropertyEx"));
}
[Fact]
public void CA1711_CSharp_Diagnostic_FieldNameEndsWithEx()
{
VerifyCSharp(
@"public class MyClass
{
public int MyFieldEx;
}",
GetCSharpResultAt(
3, 16,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyFieldEx"));
}
[Fact]
public void CA1711_Basic_Diagnostic_FieldNameEndsWithEx()
{
VerifyBasic(
@"Public Class [MyClass]
Public MyFieldEx As Integer
End Class",
GetBasicResultAt(
2, 12,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.MemberNewerVersionRule,
IdentifiersShouldNotHaveIncorrectSuffixAnalyzer.ExSuffix,
"MyFieldEx"));
}
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new IdentifiersShouldNotHaveIncorrectSuffixAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new IdentifiersShouldNotHaveIncorrectSuffixAnalyzer();
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2014 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 12.20Release
// Tag = $Name$
////////////////////////////////////////////////////////////////////////////////
#endregion
namespace FitFilePreviewer.Decode.Fit.Mesgs
{
/// <summary>
/// Implements the Record profile message.
/// </summary>
public class RecordMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public RecordMesg() : base((Mesg) Profile.mesgs[Profile.RecordIndex])
{
}
public RecordMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field
/// Units: s</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public Types.DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(Types.DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PositionLat field
/// Units: semicircles</summary>
/// <returns>Returns nullable int representing the PositionLat field</returns>
public int? GetPositionLat()
{
return (int?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set PositionLat field
/// Units: semicircles</summary>
/// <param name="positionLat_">Nullable field value to be set</param>
public void SetPositionLat(int? positionLat_)
{
SetFieldValue(0, 0, positionLat_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PositionLong field
/// Units: semicircles</summary>
/// <returns>Returns nullable int representing the PositionLong field</returns>
public int? GetPositionLong()
{
return (int?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set PositionLong field
/// Units: semicircles</summary>
/// <param name="positionLong_">Nullable field value to be set</param>
public void SetPositionLong(int? positionLong_)
{
SetFieldValue(1, 0, positionLong_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Altitude field
/// Units: m</summary>
/// <returns>Returns nullable float representing the Altitude field</returns>
public float? GetAltitude()
{
return (float?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Altitude field
/// Units: m</summary>
/// <param name="altitude_">Nullable field value to be set</param>
public void SetAltitude(float? altitude_)
{
SetFieldValue(2, 0, altitude_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the HeartRate field</returns>
public byte? GetHeartRate()
{
return (byte?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set HeartRate field
/// Units: bpm</summary>
/// <param name="heartRate_">Nullable field value to be set</param>
public void SetHeartRate(byte? heartRate_)
{
SetFieldValue(3, 0, heartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cadence field
/// Units: rpm</summary>
/// <returns>Returns nullable byte representing the Cadence field</returns>
public byte? GetCadence()
{
return (byte?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cadence field
/// Units: rpm</summary>
/// <param name="cadence_">Nullable field value to be set</param>
public void SetCadence(byte? cadence_)
{
SetFieldValue(4, 0, cadence_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance field
/// Units: m</summary>
/// <returns>Returns nullable float representing the Distance field</returns>
public float? GetDistance()
{
return (float?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance field
/// Units: m</summary>
/// <param name="distance_">Nullable field value to be set</param>
public void SetDistance(float? distance_)
{
SetFieldValue(5, 0, distance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Speed field
/// Units: m/s</summary>
/// <returns>Returns nullable float representing the Speed field</returns>
public float? GetSpeed()
{
return (float?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Speed field
/// Units: m/s</summary>
/// <param name="speed_">Nullable field value to be set</param>
public void SetSpeed(float? speed_)
{
SetFieldValue(6, 0, speed_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Power field
/// Units: watts</summary>
/// <returns>Returns nullable ushort representing the Power field</returns>
public ushort? GetPower()
{
return (ushort?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Power field
/// Units: watts</summary>
/// <param name="power_">Nullable field value to be set</param>
public void SetPower(ushort? power_)
{
SetFieldValue(7, 0, power_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field CompressedSpeedDistance</returns>
public int GetNumCompressedSpeedDistance()
{
return GetNumFieldValues(8, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CompressedSpeedDistance field</summary>
/// <param name="index">0 based index of CompressedSpeedDistance element to retrieve</param>
/// <returns>Returns nullable byte representing the CompressedSpeedDistance field</returns>
public byte? GetCompressedSpeedDistance(int index)
{
return (byte?)GetFieldValue(8, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CompressedSpeedDistance field</summary>
/// <param name="index">0 based index of compressed_speed_distance</param>
/// <param name="compressedSpeedDistance_">Nullable field value to be set</param>
public void SetCompressedSpeedDistance(int index, byte? compressedSpeedDistance_)
{
SetFieldValue(8, index, compressedSpeedDistance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Grade field
/// Units: %</summary>
/// <returns>Returns nullable float representing the Grade field</returns>
public float? GetGrade()
{
return (float?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Grade field
/// Units: %</summary>
/// <param name="grade_">Nullable field value to be set</param>
public void SetGrade(float? grade_)
{
SetFieldValue(9, 0, grade_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Resistance field
/// Comment: Relative. 0 is none 254 is Max.</summary>
/// <returns>Returns nullable byte representing the Resistance field</returns>
public byte? GetResistance()
{
return (byte?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Resistance field
/// Comment: Relative. 0 is none 254 is Max.</summary>
/// <param name="resistance_">Nullable field value to be set</param>
public void SetResistance(byte? resistance_)
{
SetFieldValue(10, 0, resistance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TimeFromCourse field
/// Units: s</summary>
/// <returns>Returns nullable float representing the TimeFromCourse field</returns>
public float? GetTimeFromCourse()
{
return (float?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TimeFromCourse field
/// Units: s</summary>
/// <param name="timeFromCourse_">Nullable field value to be set</param>
public void SetTimeFromCourse(float? timeFromCourse_)
{
SetFieldValue(11, 0, timeFromCourse_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CycleLength field
/// Units: m</summary>
/// <returns>Returns nullable float representing the CycleLength field</returns>
public float? GetCycleLength()
{
return (float?)GetFieldValue(12, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CycleLength field
/// Units: m</summary>
/// <param name="cycleLength_">Nullable field value to be set</param>
public void SetCycleLength(float? cycleLength_)
{
SetFieldValue(12, 0, cycleLength_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Temperature field
/// Units: C</summary>
/// <returns>Returns nullable sbyte representing the Temperature field</returns>
public sbyte? GetTemperature()
{
return (sbyte?)GetFieldValue(13, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Temperature field
/// Units: C</summary>
/// <param name="temperature_">Nullable field value to be set</param>
public void SetTemperature(sbyte? temperature_)
{
SetFieldValue(13, 0, temperature_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field Speed1s</returns>
public int GetNumSpeed1s()
{
return GetNumFieldValues(17, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Speed1s field
/// Units: m/s
/// Comment: Speed at 1s intervals. Timestamp field indicates time of last array element.</summary>
/// <param name="index">0 based index of Speed1s element to retrieve</param>
/// <returns>Returns nullable float representing the Speed1s field</returns>
public float? GetSpeed1s(int index)
{
return (float?)GetFieldValue(17, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Speed1s field
/// Units: m/s
/// Comment: Speed at 1s intervals. Timestamp field indicates time of last array element.</summary>
/// <param name="index">0 based index of speed_1s</param>
/// <param name="speed1s_">Nullable field value to be set</param>
public void SetSpeed1s(int index, float? speed1s_)
{
SetFieldValue(17, index, speed1s_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cycles field</summary>
/// <returns>Returns nullable byte representing the Cycles field</returns>
public byte? GetCycles()
{
return (byte?)GetFieldValue(18, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cycles field</summary>
/// <param name="cycles_">Nullable field value to be set</param>
public void SetCycles(byte? cycles_)
{
SetFieldValue(18, 0, cycles_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TotalCycles field
/// Units: cycles</summary>
/// <returns>Returns nullable uint representing the TotalCycles field</returns>
public uint? GetTotalCycles()
{
return (uint?)GetFieldValue(19, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TotalCycles field
/// Units: cycles</summary>
/// <param name="totalCycles_">Nullable field value to be set</param>
public void SetTotalCycles(uint? totalCycles_)
{
SetFieldValue(19, 0, totalCycles_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CompressedAccumulatedPower field</summary>
/// <returns>Returns nullable ushort representing the CompressedAccumulatedPower field</returns>
public ushort? GetCompressedAccumulatedPower()
{
return (ushort?)GetFieldValue(28, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CompressedAccumulatedPower field</summary>
/// <param name="compressedAccumulatedPower_">Nullable field value to be set</param>
public void SetCompressedAccumulatedPower(ushort? compressedAccumulatedPower_)
{
SetFieldValue(28, 0, compressedAccumulatedPower_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the AccumulatedPower field
/// Units: watts</summary>
/// <returns>Returns nullable uint representing the AccumulatedPower field</returns>
public uint? GetAccumulatedPower()
{
return (uint?)GetFieldValue(29, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set AccumulatedPower field
/// Units: watts</summary>
/// <param name="accumulatedPower_">Nullable field value to be set</param>
public void SetAccumulatedPower(uint? accumulatedPower_)
{
SetFieldValue(29, 0, accumulatedPower_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LeftRightBalance field</summary>
/// <returns>Returns nullable byte representing the LeftRightBalance field</returns>
public byte? GetLeftRightBalance()
{
return (byte?)GetFieldValue(30, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LeftRightBalance field</summary>
/// <param name="leftRightBalance_">Nullable field value to be set</param>
public void SetLeftRightBalance(byte? leftRightBalance_)
{
SetFieldValue(30, 0, leftRightBalance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the GpsAccuracy field
/// Units: m</summary>
/// <returns>Returns nullable byte representing the GpsAccuracy field</returns>
public byte? GetGpsAccuracy()
{
return (byte?)GetFieldValue(31, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set GpsAccuracy field
/// Units: m</summary>
/// <param name="gpsAccuracy_">Nullable field value to be set</param>
public void SetGpsAccuracy(byte? gpsAccuracy_)
{
SetFieldValue(31, 0, gpsAccuracy_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the VerticalSpeed field
/// Units: m/s</summary>
/// <returns>Returns nullable float representing the VerticalSpeed field</returns>
public float? GetVerticalSpeed()
{
return (float?)GetFieldValue(32, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set VerticalSpeed field
/// Units: m/s</summary>
/// <param name="verticalSpeed_">Nullable field value to be set</param>
public void SetVerticalSpeed(float? verticalSpeed_)
{
SetFieldValue(32, 0, verticalSpeed_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Calories field
/// Units: kcal</summary>
/// <returns>Returns nullable ushort representing the Calories field</returns>
public ushort? GetCalories()
{
return (ushort?)GetFieldValue(33, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Calories field
/// Units: kcal</summary>
/// <param name="calories_">Nullable field value to be set</param>
public void SetCalories(ushort? calories_)
{
SetFieldValue(33, 0, calories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the VerticalOscillation field
/// Units: mm</summary>
/// <returns>Returns nullable float representing the VerticalOscillation field</returns>
public float? GetVerticalOscillation()
{
return (float?)GetFieldValue(39, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set VerticalOscillation field
/// Units: mm</summary>
/// <param name="verticalOscillation_">Nullable field value to be set</param>
public void SetVerticalOscillation(float? verticalOscillation_)
{
SetFieldValue(39, 0, verticalOscillation_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the StanceTimePercent field
/// Units: percent</summary>
/// <returns>Returns nullable float representing the StanceTimePercent field</returns>
public float? GetStanceTimePercent()
{
return (float?)GetFieldValue(40, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set StanceTimePercent field
/// Units: percent</summary>
/// <param name="stanceTimePercent_">Nullable field value to be set</param>
public void SetStanceTimePercent(float? stanceTimePercent_)
{
SetFieldValue(40, 0, stanceTimePercent_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the StanceTime field
/// Units: ms</summary>
/// <returns>Returns nullable float representing the StanceTime field</returns>
public float? GetStanceTime()
{
return (float?)GetFieldValue(41, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set StanceTime field
/// Units: ms</summary>
/// <param name="stanceTime_">Nullable field value to be set</param>
public void SetStanceTime(float? stanceTime_)
{
SetFieldValue(41, 0, stanceTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityType field</summary>
/// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns>
public Types.ActivityType? GetActivityType()
{
object obj = GetFieldValue(42, 0, Fit.SubfieldIndexMainField);
Types.ActivityType? value = obj == null ? (Types.ActivityType?)null : (Types.ActivityType)obj;
return value;
}
/// <summary>
/// Set ActivityType field</summary>
/// <param name="activityType_">Nullable field value to be set</param>
public void SetActivityType(Types.ActivityType? activityType_)
{
SetFieldValue(42, 0, activityType_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LeftTorqueEffectiveness field
/// Units: percent</summary>
/// <returns>Returns nullable float representing the LeftTorqueEffectiveness field</returns>
public float? GetLeftTorqueEffectiveness()
{
return (float?)GetFieldValue(43, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LeftTorqueEffectiveness field
/// Units: percent</summary>
/// <param name="leftTorqueEffectiveness_">Nullable field value to be set</param>
public void SetLeftTorqueEffectiveness(float? leftTorqueEffectiveness_)
{
SetFieldValue(43, 0, leftTorqueEffectiveness_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RightTorqueEffectiveness field
/// Units: percent</summary>
/// <returns>Returns nullable float representing the RightTorqueEffectiveness field</returns>
public float? GetRightTorqueEffectiveness()
{
return (float?)GetFieldValue(44, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set RightTorqueEffectiveness field
/// Units: percent</summary>
/// <param name="rightTorqueEffectiveness_">Nullable field value to be set</param>
public void SetRightTorqueEffectiveness(float? rightTorqueEffectiveness_)
{
SetFieldValue(44, 0, rightTorqueEffectiveness_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LeftPedalSmoothness field
/// Units: percent</summary>
/// <returns>Returns nullable float representing the LeftPedalSmoothness field</returns>
public float? GetLeftPedalSmoothness()
{
return (float?)GetFieldValue(45, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LeftPedalSmoothness field
/// Units: percent</summary>
/// <param name="leftPedalSmoothness_">Nullable field value to be set</param>
public void SetLeftPedalSmoothness(float? leftPedalSmoothness_)
{
SetFieldValue(45, 0, leftPedalSmoothness_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RightPedalSmoothness field
/// Units: percent</summary>
/// <returns>Returns nullable float representing the RightPedalSmoothness field</returns>
public float? GetRightPedalSmoothness()
{
return (float?)GetFieldValue(46, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set RightPedalSmoothness field
/// Units: percent</summary>
/// <param name="rightPedalSmoothness_">Nullable field value to be set</param>
public void SetRightPedalSmoothness(float? rightPedalSmoothness_)
{
SetFieldValue(46, 0, rightPedalSmoothness_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CombinedPedalSmoothness field
/// Units: percent</summary>
/// <returns>Returns nullable float representing the CombinedPedalSmoothness field</returns>
public float? GetCombinedPedalSmoothness()
{
return (float?)GetFieldValue(47, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CombinedPedalSmoothness field
/// Units: percent</summary>
/// <param name="combinedPedalSmoothness_">Nullable field value to be set</param>
public void SetCombinedPedalSmoothness(float? combinedPedalSmoothness_)
{
SetFieldValue(47, 0, combinedPedalSmoothness_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Time128 field
/// Units: s</summary>
/// <returns>Returns nullable float representing the Time128 field</returns>
public float? GetTime128()
{
return (float?)GetFieldValue(48, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Time128 field
/// Units: s</summary>
/// <param name="time128_">Nullable field value to be set</param>
public void SetTime128(float? time128_)
{
SetFieldValue(48, 0, time128_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the StrokeType field</summary>
/// <returns>Returns nullable StrokeType enum representing the StrokeType field</returns>
public Types.StrokeType? GetStrokeType()
{
object obj = GetFieldValue(49, 0, Fit.SubfieldIndexMainField);
Types.StrokeType? value = obj == null ? (Types.StrokeType?)null : (Types.StrokeType)obj;
return value;
}
/// <summary>
/// Set StrokeType field</summary>
/// <param name="strokeType_">Nullable field value to be set</param>
public void SetStrokeType(Types.StrokeType? strokeType_)
{
SetFieldValue(49, 0, strokeType_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Zone field</summary>
/// <returns>Returns nullable byte representing the Zone field</returns>
public byte? GetZone()
{
return (byte?)GetFieldValue(50, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Zone field</summary>
/// <param name="zone_">Nullable field value to be set</param>
public void SetZone(byte? zone_)
{
SetFieldValue(50, 0, zone_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the BallSpeed field
/// Units: m/s</summary>
/// <returns>Returns nullable float representing the BallSpeed field</returns>
public float? GetBallSpeed()
{
return (float?)GetFieldValue(51, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set BallSpeed field
/// Units: m/s</summary>
/// <param name="ballSpeed_">Nullable field value to be set</param>
public void SetBallSpeed(float? ballSpeed_)
{
SetFieldValue(51, 0, ballSpeed_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cadence256 field
/// Units: rpm
/// Comment: Log cadence and fractional cadence for backwards compatability</summary>
/// <returns>Returns nullable float representing the Cadence256 field</returns>
public float? GetCadence256()
{
return (float?)GetFieldValue(52, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cadence256 field
/// Units: rpm
/// Comment: Log cadence and fractional cadence for backwards compatability</summary>
/// <param name="cadence256_">Nullable field value to be set</param>
public void SetCadence256(float? cadence256_)
{
SetFieldValue(52, 0, cadence256_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the FractionalCadence field
/// Units: rpm</summary>
/// <returns>Returns nullable float representing the FractionalCadence field</returns>
public float? GetFractionalCadence()
{
return (float?)GetFieldValue(53, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set FractionalCadence field
/// Units: rpm</summary>
/// <param name="fractionalCadence_">Nullable field value to be set</param>
public void SetFractionalCadence(float? fractionalCadence_)
{
SetFieldValue(53, 0, fractionalCadence_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TotalHemoglobinConc field
/// Units: g/dL
/// Comment: Total saturated and unsaturated hemoglobin</summary>
/// <returns>Returns nullable float representing the TotalHemoglobinConc field</returns>
public float? GetTotalHemoglobinConc()
{
return (float?)GetFieldValue(54, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TotalHemoglobinConc field
/// Units: g/dL
/// Comment: Total saturated and unsaturated hemoglobin</summary>
/// <param name="totalHemoglobinConc_">Nullable field value to be set</param>
public void SetTotalHemoglobinConc(float? totalHemoglobinConc_)
{
SetFieldValue(54, 0, totalHemoglobinConc_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TotalHemoglobinConcMin field
/// Units: g/dL
/// Comment: Min saturated and unsaturated hemoglobin</summary>
/// <returns>Returns nullable float representing the TotalHemoglobinConcMin field</returns>
public float? GetTotalHemoglobinConcMin()
{
return (float?)GetFieldValue(55, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TotalHemoglobinConcMin field
/// Units: g/dL
/// Comment: Min saturated and unsaturated hemoglobin</summary>
/// <param name="totalHemoglobinConcMin_">Nullable field value to be set</param>
public void SetTotalHemoglobinConcMin(float? totalHemoglobinConcMin_)
{
SetFieldValue(55, 0, totalHemoglobinConcMin_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TotalHemoglobinConcMax field
/// Units: g/dL
/// Comment: Max saturated and unsaturated hemoglobin</summary>
/// <returns>Returns nullable float representing the TotalHemoglobinConcMax field</returns>
public float? GetTotalHemoglobinConcMax()
{
return (float?)GetFieldValue(56, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TotalHemoglobinConcMax field
/// Units: g/dL
/// Comment: Max saturated and unsaturated hemoglobin</summary>
/// <param name="totalHemoglobinConcMax_">Nullable field value to be set</param>
public void SetTotalHemoglobinConcMax(float? totalHemoglobinConcMax_)
{
SetFieldValue(56, 0, totalHemoglobinConcMax_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SaturatedHemoglobinPercent field
/// Units: %
/// Comment: Percentage of hemoglobin saturated with oxygen</summary>
/// <returns>Returns nullable float representing the SaturatedHemoglobinPercent field</returns>
public float? GetSaturatedHemoglobinPercent()
{
return (float?)GetFieldValue(57, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SaturatedHemoglobinPercent field
/// Units: %
/// Comment: Percentage of hemoglobin saturated with oxygen</summary>
/// <param name="saturatedHemoglobinPercent_">Nullable field value to be set</param>
public void SetSaturatedHemoglobinPercent(float? saturatedHemoglobinPercent_)
{
SetFieldValue(57, 0, saturatedHemoglobinPercent_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SaturatedHemoglobinPercentMin field
/// Units: %
/// Comment: Min percentage of hemoglobin saturated with oxygen</summary>
/// <returns>Returns nullable float representing the SaturatedHemoglobinPercentMin field</returns>
public float? GetSaturatedHemoglobinPercentMin()
{
return (float?)GetFieldValue(58, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SaturatedHemoglobinPercentMin field
/// Units: %
/// Comment: Min percentage of hemoglobin saturated with oxygen</summary>
/// <param name="saturatedHemoglobinPercentMin_">Nullable field value to be set</param>
public void SetSaturatedHemoglobinPercentMin(float? saturatedHemoglobinPercentMin_)
{
SetFieldValue(58, 0, saturatedHemoglobinPercentMin_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SaturatedHemoglobinPercentMax field
/// Units: %
/// Comment: Max percentage of hemoglobin saturated with oxygen</summary>
/// <returns>Returns nullable float representing the SaturatedHemoglobinPercentMax field</returns>
public float? GetSaturatedHemoglobinPercentMax()
{
return (float?)GetFieldValue(59, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SaturatedHemoglobinPercentMax field
/// Units: %
/// Comment: Max percentage of hemoglobin saturated with oxygen</summary>
/// <param name="saturatedHemoglobinPercentMax_">Nullable field value to be set</param>
public void SetSaturatedHemoglobinPercentMax(float? saturatedHemoglobinPercentMax_)
{
SetFieldValue(59, 0, saturatedHemoglobinPercentMax_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DeviceIndex field</summary>
/// <returns>Returns nullable byte representing the DeviceIndex field</returns>
public byte? GetDeviceIndex()
{
return (byte?)GetFieldValue(62, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DeviceIndex field</summary>
/// <param name="deviceIndex_">Nullable field value to be set</param>
public void SetDeviceIndex(byte? deviceIndex_)
{
SetFieldValue(62, 0, deviceIndex_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// Module: use CXMLTypeCoercionTestModule
//
////////////////////////////////////////////////////////////////
[TestModule(Name = "XmlFactoryReader Test", Desc = "XmlFactoryReader Test")]
public partial class FactoryReaderTest : CGenericTestModule
{
public override int Init(object objParam)
{
int ret = base.Init(objParam);
// Create global usage test files
string strFile = string.Empty;
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XSLT_COPY);
// Create reader factory
ReaderFactory = new XmlFactoryReaderFactory();
return ret;
}
public override int Terminate(object objParam)
{
return base.Terminate(objParam);
}
}
////////////////////////////////////////////////////////////////
// FactoryReader factory
//
////////////////////////////////////////////////////////////////
internal class XmlFactoryReaderFactory : ReaderFactory
{
public override XmlReader Create(MyDict<string, object> options)
{
string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
string tcVar = (string)options[ReaderFactory.HT_CURVAR];
CError.Compare(tcDesc == "factoryreader", "Invalid testcase");
XmlReaderSettings rs = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
string filename = (string)options[ReaderFactory.HT_FILENAME];
object readerType = options[ReaderFactory.HT_READERTYPE];
object vt = options[ReaderFactory.HT_VALIDATIONTYPE];
string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER];
if (rs == null)
rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
if (sr != null)
{
CError.WriteLine("StringReader");
XmlReader reader = ReaderHelper.Create(sr, rs, string.Empty);
return reader;
}
if (stream != null)
{
CError.WriteLine("Stream");
XmlReader reader = ReaderHelper.Create(stream, rs, filename);
return reader;
}
if (fragment != null)
{
CError.WriteLine("Fragment");
rs.ConformanceLevel = ConformanceLevel.Fragment;
StringReader tr = new StringReader(fragment);
XmlReader reader = ReaderHelper.Create(tr, rs, (string)null);
return reader;
}
if (filename != null)
{
CError.WriteLine("Filename");
XmlReader reader = ReaderHelper.Create(filename, rs);
return reader;
}
throw new
CTestFailedException("Factory Reader not created");
}
}
[TestCase(Name = "ErrorCondition", Desc = "FactoryReader")]
internal class TCErrorConditionReader : TCErrorCondition
{
}
[TestCase(Name = "XMLException", Desc = "FactoryReader")]
public class TCXMLExceptionReader : TCXMLException
{
}
[TestCase(Name = "LinePos", Desc = "FactoryReader")]
public class TCLinePosReader : TCLinePos
{
}
[TestCase(Name = "Depth", Desc = "FactoryReader")]
internal class TCDepthReader : TCDepth
{
}
[TestCase(Name = "Namespace", Desc = "FactoryReader")]
internal class TCNamespaceReader : TCNamespace
{
}
[TestCase(Name = "LookupNamespace", Desc = "FactoryReader")]
internal class TCLookupNamespaceReader : TCLookupNamespace
{
}
[TestCase(Name = "HasValue", Desc = "FactoryReader")]
internal class TCHasValueReader : TCHasValue
{
}
[TestCase(Name = "IsEmptyElement", Desc = "FactoryReader")]
internal class TCIsEmptyElementReader : TCIsEmptyElement
{
}
[TestCase(Name = "XmlSpace", Desc = "FactoryReader")]
internal class TCXmlSpaceReader : TCXmlSpace
{
}
[TestCase(Name = "XmlLang", Desc = "FactoryReader")]
internal class TCXmlLangReader : TCXmlLang
{
}
[TestCase(Name = "Skip", Desc = "FactoryReader")]
internal class TCSkipReader : TCSkip
{
}
[TestCase(Name = "BaseURI", Desc = "FactoryReader")]
internal class TCBaseURIReader : TCBaseURI
{
}
[TestCase(Name = "InvalidXML", Desc = "FactoryReader")]
internal class TCInvalidXMLReader : TCInvalidXML
{
}
[TestCase(Name = "ReadOuterXml", Desc = "FactoryReader")]
internal class TCReadOuterXmlReader : TCReadOuterXml
{
}
[TestCase(Name = "AttributeAccess", Desc = "FactoryReader")]
internal class TCAttributeAccessReader : TCAttributeAccess
{
}
[TestCase(Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader")]
internal class TCThisNameReader : TCThisName
{
}
[TestCase(Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader")]
internal class TCMoveToAttributeReader : TCMoveToAttribute
{
}
[TestCase(Name = "GetAttribute (Ordinal)", Desc = "FactoryReader")]
internal class TCGetAttributeOrdinalReader : TCGetAttributeOrdinal
{
}
[TestCase(Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader")]
internal class TCGetAttributeNameReader : TCGetAttributeName
{
}
[TestCase(Name = "This [Ordinal]", Desc = "FactoryReader")]
internal class TCThisOrdinalReader : TCThisOrdinal
{
}
[TestCase(Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader")]
internal class TCMoveToAttributeOrdinalReader : TCMoveToAttributeOrdinal
{
}
[TestCase(Name = "MoveToFirstAttribute()", Desc = "FactoryReader")]
internal class TCMoveToFirstAttributeReader : TCMoveToFirstAttribute
{
}
[TestCase(Name = "MoveToNextAttribute()", Desc = "FactoryReader")]
internal class TCMoveToNextAttributeReader : TCMoveToNextAttribute
{
}
[TestCase(Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader")]
internal class TCAttributeTestReader : TCAttributeTest
{
}
[TestCase(Name = "Attributes test on XmlDeclaration DCR52258", Desc = "FactoryReader")]
internal class TCAttributeXmlDeclarationReader : TCAttributeXmlDeclaration
{
}
[TestCase(Name = "xmlns as local name DCR50345", Desc = "FactoryReader")]
internal class TCXmlnsReader : TCXmlns
{
}
[TestCase(Name = "bounded namespace to xmlns prefix DCR50881", Desc = "FactoryReader")]
internal class TCXmlnsPrefixReader : TCXmlnsPrefix
{
}
[TestCase(Name = "ReadState", Desc = "FactoryReader")]
internal class TCReadStateReader : TCReadState
{
}
[TestCase(Name = "ReadInnerXml", Desc = "FactoryReader")]
internal class TCReadInnerXmlReader : TCReadInnerXml
{
}
[TestCase(Name = "MoveToContent", Desc = "FactoryReader")]
internal class TCMoveToContentReader : TCMoveToContent
{
}
[TestCase(Name = "IsStartElement", Desc = "FactoryReader")]
internal class TCIsStartElementReader : TCIsStartElement
{
}
[TestCase(Name = "ReadStartElement", Desc = "FactoryReader")]
internal class TCReadStartElementReader : TCReadStartElement
{
}
[TestCase(Name = "ReadEndElement", Desc = "FactoryReader")]
internal class TCReadEndElementReader : TCReadEndElement
{
}
[TestCase(Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader")]
internal class TCResolveEntityReader : TCResolveEntity
{
}
[TestCase(Name = "ReadAttributeValue", Desc = "FactoryReader")]
internal class TCReadAttributeValueReader : TCReadAttributeValue
{
}
[TestCase(Name = "Read", Desc = "FactoryReader")]
internal class TCReadReader : TCRead2
{
}
[TestCase(Name = "MoveToElement", Desc = "FactoryReader")]
internal class TCMoveToElementReader : TCMoveToElement
{
}
[TestCase(Name = "Dispose", Desc = "FactoryReader")]
internal class TCDisposeReader : TCDispose
{
}
[TestCase(Name = "Buffer Boundaries", Desc = "FactoryReader")]
internal class TCBufferBoundariesReader : TCBufferBoundaries
{
}
//[TestCase(Name = "BeforeRead", Desc = "BeforeRead")]
//[TestCase(Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse")]
//[TestCase(Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle")]
//[TestCase(Name = "AfterClose", Desc = "AfterClose")]
internal class TCXmlNodeIntegrityTestFile : TCXMLIntegrityBase
{
}
[TestCase(Name = "Read Subtree", Desc = "FactoryReader")]
internal class TCReadSubtreeReader : TCReadSubtree
{
}
[TestCase(Name = "ReadToDescendant", Desc = "FactoryReader")]
internal class TCReadToDescendantReader : TCReadToDescendant
{
}
[TestCase(Name = "ReadToNextSibling", Desc = "FactoryReader")]
internal class TCReadToNextSiblingReader : TCReadToNextSibling
{
}
[TestCase(Name = "ReadValue", Desc = "FactoryReader")]
internal class TCReadValueReader : TCReadValue
{
}
[TestCase(Name = "ReadContentAsBase64", Desc = "FactoryReader")]
internal class TCReadContentAsBase64Reader : TCReadContentAsBase64
{
}
[TestCase(Name = "ReadElementContentAsBase64", Desc = "FactoryReader")]
internal class TCReadElementContentAsBase64Reader : TCReadElementContentAsBase64
{
}
[TestCase(Name = "ReadContentAsBinHex", Desc = "FactoryReader")]
internal class TCReadContentAsBinHexReader : TCReadContentAsBinHex
{
}
[TestCase(Name = "ReadElementContentAsBinHex", Desc = "FactoryReader")]
internal class TCReadElementContentAsBinHexReader : TCReadElementContentAsBinHex
{
}
[TestCase(Name = "ReadToFollowing", Desc = "FactoryReader")]
internal class TCReadToFollowingReader : TCReadToFollowing
{
}
}
| |
// Copyright (c) 2011-2013, Eric Maupin
// 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 Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services 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.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Cadenza;
using Gablarski.Clients.Input;
using Tempest;
#if XAMARIN
using SQLiteConnectionStringBuilder=Mono.Data.Sqlite.SqliteConnectionStringBuilder;
using SQLiteConnection=Mono.Data.Sqlite.SqliteConnection;
using SQLiteParameter=Mono.Data.Sqlite.SqliteParameter;
#else
using System.Data.SQLite;
#endif
namespace Gablarski.Clients.Persistence
{
public static class ClientData
{
public static void Setup (bool useLocalFiles)
{
DataDirectory = new DirectoryInfo (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "Gablarski"));
if (!DataDirectory.Exists)
DataDirectory.Create();
if (useLocalFiles) {
KeyFile = new FileInfo ("gablarski.key");
DbFile = new FileInfo ("gablarski.db");
} else {
KeyFile = new FileInfo (Path.Combine (DataDirectory.FullName, "gablarski.key"));
DbFile = new FileInfo (Path.Combine (DataDirectory.FullName, "gablarski.db"));
}
#if !XAMARIN
var builder = new SQLiteConnectionStringBuilder();
builder.DataSource = DbFile.FullName;
db = new SQLiteConnection (builder.ToString());
#else
KeyFile = new FileInfo (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), KeyFile.Name));
DbFile = new FileInfo (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), DbFile.Name));
if (!DbFile.Exists)
SQLiteConnection.CreateFile (DbFile.FullName);
db = new SQLiteConnection ("Data Source=" + DbFile.FullName);
#endif
db.Open();
CreateDbs();
}
sealed class RSAParametersSerializer
: ISerializer<RSAParameters>
{
public static readonly RSAParametersSerializer Instance = new RSAParametersSerializer();
public static void Serialize (IValueWriter writer, RSAParameters element)
{
Instance.Serialize (null, writer, element);
}
public static RSAParameters Deserialize (IValueReader reader)
{
return Instance.Deserialize (null, reader);
}
public void Serialize (ISerializationContext context, IValueWriter writer, RSAParameters element)
{
writer.WriteBytes (element.D);
writer.WriteBytes (element.DP);
writer.WriteBytes (element.DQ);
writer.WriteBytes (element.Exponent);
writer.WriteBytes (element.InverseQ);
writer.WriteBytes (element.Modulus);
writer.WriteBytes (element.P);
writer.WriteBytes (element.Q);
}
public RSAParameters Deserialize (ISerializationContext context, IValueReader reader)
{
return new RSAParameters {
D = reader.ReadBytes(),
DP = reader.ReadBytes(),
DQ = reader.ReadBytes(),
Exponent = reader.ReadBytes(),
InverseQ = reader.ReadBytes(),
Modulus = reader.ReadBytes(),
P = reader.ReadBytes(),
Q = reader.ReadBytes()
};
}
}
public static Task<RSAAsymmetricKey> GetCryptoKeyAsync()
{
return GetCryptoKeyAsync (CancellationToken.None);
}
public static Task<RSAAsymmetricKey> GetCryptoKeyAsync (CancellationToken cancelToken = default(CancellationToken))
{
return Task.Run (() => {
RSAAsymmetricKey key = null;
if (KeyFile.Exists) {
try {
using (var stream = File.OpenRead (KeyFile.FullName)) {
var reader = new StreamValueReader (stream);
RSAParameters parameters = RSAParametersSerializer.Deserialize (reader);
key = new RSAAsymmetricKey (parameters);
}
} catch (Exception ex) {
Trace.TraceWarning ("Failed to read key: {0}", ex);
KeyFile.Delete();
}
}
cancelToken.ThrowIfCancellationRequested();
if (!KeyFile.Exists) {
var rsa = new RSACrypto();
RSAParameters parameters = rsa.ExportKey (true);
key = new RSAAsymmetricKey (parameters);
cancelToken.ThrowIfCancellationRequested();
using (var stream = File.OpenWrite (KeyFile.FullName)) {
var writer = new StreamValueWriter (stream);
RSAParametersSerializer.Serialize (writer, parameters);
}
}
return key;
}, cancelToken);
}
public static bool CheckForUpdates()
{
if (!Settings.Version.IsNullOrWhitespace())
{
string newVersion = Settings.Version = typeof (ClientData).Assembly.GetName().Version.ToString();
Version version = new Version (Settings.Version);
if (version < new Version (0, 13, 1))
{
Settings.TextToSpeech = "Gablarski.SpeechNotifier.EventSpeech, Gablarski.SpeechNotifier";
Settings.Version = newVersion;
Settings.Save();
return true;
}
if (version < new Version (0, 13, 4))
{
Settings.PlaybackDevice = "Default";
Settings.VoiceDevice = "Default";
Settings.Version = newVersion;
Settings.Save();
return true;
}
return false;
}
db.Close();
DbFile.Delete();
Settings.Clear();
DbFile.Refresh();
db.Open();
CreateDbs();
return true;
}
public static IEnumerable<SettingEntry> GetSettings()
{
using (var cmd = db.CreateCommand ("SELECT * FROM settings"))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new SettingEntry (Convert.ToInt32 (reader["settingId"]))
{
Name = Convert.ToString (reader["settingName"]),
Value = Convert.ToString (reader["settingValue"])
};
}
}
}
#region Ignores
public static void SaveOrUpdate (IgnoreEntry ignore)
{
if (ignore == null)
throw new ArgumentNullException ("ignore");
using (var cmd = db.CreateCommand())
{
cmd.CommandText = ignore.Id > 0
? "UPDATE ignores SET ignoreServerId=?,ignoreUsername=? WHERE (ignoreId=?)"
: "INSERT INTO ignores (ignoreServerId,ignoreUsername) VALUES (?,?)";
cmd.Parameters.Add (new SQLiteParameter ("server", ignore.ServerId));
cmd.Parameters.Add (new SQLiteParameter ("username", ignore.Username));
if (ignore.Id > 0)
cmd.Parameters.Add (new SQLiteParameter ("id", ignore.Id));
cmd.ExecuteNonQuery();
}
}
public static IEnumerable<IgnoreEntry> GetIgnores()
{
using (var cmd = db.CreateCommand ("SELECT * FROM ignores"))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new IgnoreEntry (Convert.ToInt32 (reader["ignoreId"]))
{
ServerId = Convert.ToInt32 (reader["ignoreServerId"]),
Username = Convert.ToString (reader["ignoreUsername"])
};
}
}
}
public static void Delete (IgnoreEntry ignore)
{
if (ignore == null)
throw new ArgumentNullException ("ignore");
if (ignore.Id < 1)
throw new ArgumentException ("Can't delete a non-existant ignore", "ignore");
using (var cmd = db.CreateCommand ("DELETE FROM ignores WHERE (ignoreId=?)"))
{
cmd.Parameters.Add (new SQLiteParameter ("id", ignore.Id));
cmd.ExecuteNonQuery();
}
}
#endregion
#region Servers
public static void SaveOrUpdate (SettingEntry setting)
{
if (setting == null)
throw new ArgumentNullException ("setting");
using (var cmd = db.CreateCommand())
{
cmd.CommandText = setting.Id > 0
? "UPDATE settings SET settingName=?,settingValue=? WHERE (settingId=?)"
: "INSERT INTO settings (settingName,settingValue) VALUES (?,?)";
cmd.Parameters.Add (new SQLiteParameter ("name", setting.Name));
cmd.Parameters.Add (new SQLiteParameter ("value", setting.Value));
if (setting.Id > 0)
cmd.Parameters.Add (new SQLiteParameter ("id", setting.Id));
cmd.ExecuteNonQuery();
}
}
public static IEnumerable<ServerEntry> GetServers()
{
using (var cmd = db.CreateCommand ("SELECT * FROM servers"))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new ServerEntry (Convert.ToInt32 (reader[0]))
{
Name = Convert.ToString (reader[1]),
Host = Convert.ToString (reader[2]),
Port = Convert.ToInt32 (reader[3]),
ServerPassword = Convert.ToString (reader[4]),
UserNickname = Convert.ToString (reader[5]),
UserPhonetic = Convert.ToString (reader[6]),
UserName = Convert.ToString (reader[7]),
UserPassword = Convert.ToString (reader[8])
};
}
}
}
public static Task<IEnumerable<ServerEntry>> GetServersAsync()
{
return Task.Run<IEnumerable<ServerEntry>> (() => GetServers().ToArray());
}
public static void SaveOrUpdate (ServerEntry server)
{
if (server == null)
throw new ArgumentNullException ("server");
using (var cmd = db.CreateCommand())
{
cmd.CommandText = server.Id > 0 ? "UPDATE servers SET serverName=?,serverHost=?,serverPort=?,serverPassword=?,serverUserNickname=?,serverUserPhonetic=?,serverUserName=?,serverUserPassword=? WHERE (serverId=?)"
: "INSERT INTO servers (serverName,serverHost,serverPort,serverPassword,serverUserNickname,serverUserPhonetic,serverUserName,serverUserPassword) VALUES (?,?,?,?,?,?,?,?)";
cmd.Parameters.Add (new SQLiteParameter ("name", server.Name));
cmd.Parameters.Add (new SQLiteParameter ("host", server.Host));
cmd.Parameters.Add (new SQLiteParameter ("port", server.Port));
cmd.Parameters.Add (new SQLiteParameter ("password", server.ServerPassword));
cmd.Parameters.Add (new SQLiteParameter ("nickname", server.UserNickname));
cmd.Parameters.Add (new SQLiteParameter ("phonetic", server.UserPhonetic));
cmd.Parameters.Add (new SQLiteParameter ("username", server.UserName));
cmd.Parameters.Add (new SQLiteParameter ("userpassword", server.UserPassword));
if (server.Id > 0)
cmd.Parameters.Add (new SQLiteParameter ("id", server.Id));
cmd.ExecuteNonQuery();
}
}
public static void Delete (ServerEntry server)
{
if (server == null)
throw new ArgumentNullException ("server");
if (server.Id < 1)
throw new ArgumentException ("Can't delete a non-existant server", "server");
using (var cmd = db.CreateCommand ("DELETE FROM servers WHERE (serverId=?)"))
{
cmd.Parameters.Add (new SQLiteParameter ("id", server.Id));
cmd.ExecuteNonQuery();
}
}
#endregion
#region Volume
public static IEnumerable<VolumeEntry> GetVolumes (ServerEntry server)
{
if (server == null)
throw new ArgumentNullException ("server");
using (var cmd = db.CreateCommand())
{
cmd.CommandText = "SELECT * FROM volumes WHERE (volumeServerId=?)";
cmd.Parameters.Add (new SQLiteParameter ("serverId", server.Id));
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new VolumeEntry (Convert.ToInt32 (reader[0]))
{
ServerId = Convert.ToInt32 (reader[1]),
Username = Convert.ToString (reader[2]),
Gain = Convert.ToSingle (reader[3])
};
}
}
}
}
public static void SaveOrUpdate (VolumeEntry volumeEntry)
{
if (volumeEntry == null)
throw new ArgumentNullException ("volumeEntry");
using (var cmd = db.CreateCommand())
{
cmd.CommandText = (volumeEntry.VolumeId > 0)
? "UPDATE volumes SET volumeServerId=?, volumeUsername=?, volumeGain=? WHERE volumeId=?"
: "INSERT INTO volumes (volumeServerId,volumeUsername,volumeGain) VALUES (?,?,?)";
cmd.Parameters.Add (new SQLiteParameter ("serverId", volumeEntry.ServerId));
cmd.Parameters.Add (new SQLiteParameter ("username", volumeEntry.Username));
cmd.Parameters.Add (new SQLiteParameter ("gain", volumeEntry.Gain));
if (volumeEntry.VolumeId > 0)
cmd.Parameters.Add (new SQLiteParameter ("id", volumeEntry.VolumeId));
cmd.ExecuteNonQuery();
}
}
public static void Delete (VolumeEntry volumeEntry)
{
if (volumeEntry == null)
throw new ArgumentNullException ("volumeEntry");
if (volumeEntry.VolumeId < 1)
throw new ArgumentException ("Can't delete a non-existent server", "volumeEntry");
using (var cmd = db.CreateCommand ("DELETE FROM volumes WHERE (volumeId=?)"))
{
cmd.Parameters.Add (new SQLiteParameter ("id", volumeEntry.VolumeId));
cmd.ExecuteNonQuery();
}
}
#endregion
#region Bindings
public static IEnumerable<CommandBindingEntry> GetCommandBindings()
{
using (var cmd = db.CreateCommand ("SELECT * FROM commandbindings"))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new CommandBindingEntry
{
ProviderType = Convert.ToString (reader[0]),
Command = (Command)Convert.ToInt32 (reader[1]),
Input = Convert.ToString (reader[2])
};
}
}
}
public static void Create (CommandBindingEntry bindingEntry)
{
if (bindingEntry == null)
throw new ArgumentNullException ("bindingEntry");
using (var cmd = db.CreateCommand())
{
cmd.CommandText = "INSERT INTO commandbindings (commandbindingProvider,commandbindingCommand,commandbindingInput) VALUES (?,?,?)";
cmd.Parameters.Add (new SQLiteParameter ("provider", bindingEntry.ProviderType));
cmd.Parameters.Add (new SQLiteParameter ("command", (int)bindingEntry.Command));
cmd.Parameters.Add (new SQLiteParameter ("input", bindingEntry.Input));
cmd.ExecuteNonQuery();
}
}
public static void DeleteAllBindings ()
{
using (var cmd = db.CreateCommand ("DELETE FROM commandbindings"))
{
cmd.ExecuteNonQuery();
}
}
#endregion
public static async Task<IEnumerable<string>> GetBuddiesAsync()
{
using (var cmd = db.CreateCommand ("SELECT * FROM buddies"))
using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait (false)) {
List<string> buddies = new List<string>();
while (await reader.ReadAsync().ConfigureAwait (false)) {
buddies. Add(reader.GetString (0));
}
return buddies;
}
}
public static async Task SaveBuddiesAsync (IEnumerable<string> buddies)
{
if (buddies == null)
throw new ArgumentNullException ("buddies");
HashSet<string> buddySet = new HashSet<string> (buddies);
var currentBuddies = await GetBuddiesAsync().ConfigureAwait (false);
buddySet.ExceptWith (currentBuddies);
foreach (string identity in buddySet) {
using (var cmd = db.CreateCommand ("INSERT INTO buddies (identity) VALUES (?)")) {
cmd.Parameters.Add (new SQLiteParameter ("identity", identity));
await cmd.ExecuteNonQueryAsync().ConfigureAwait (false);
}
}
}
private static DirectoryInfo DataDirectory;
private static DbConnection db;
private static FileInfo DbFile;
private static FileInfo KeyFile;
private static void CreateDbs()
{
using (var cmd = db.CreateCommand ("CREATE TABLE IF NOT EXISTS servers (serverId integer primary key autoincrement, serverName varchar(255), serverHost varchar(255), serverPort integer, serverPassword varchar(255), serverUserNickname varchar(255), serverUserPhonetic varchar(255), serverUserName varchar(255), serverUserPassword varchar(255))"))
cmd.ExecuteNonQuery();
using (var cmd = db.CreateCommand ("CREATE TABLE IF NOT EXISTS settings (settingId integer primary key autoincrement, settingName varchar(255), settingValue varchar(255))"))
cmd.ExecuteNonQuery();
using (var cmd = db.CreateCommand ("CREATE TABLE IF NOT EXISTS volumes (volumeId integer primary key autoincrement, volumeServerId integer, volumeUsername varchar(255), volumeGain float)"))
cmd.ExecuteNonQuery();
using (var cmd = db.CreateCommand ("CREATE TABLE IF NOT EXISTS ignores (ignoreId integer primary key autoincrement, ignoreServerId integer, ignoreUsername varchar(255))"))
cmd.ExecuteNonQuery();
using (var cmd = db.CreateCommand ("CREATE TABLE IF NOT EXISTS commandbindings (commandbindingProvider string, commandbindingCommand integer, commandbindingInput varchar(255))"))
cmd.ExecuteNonQuery();
using (var cmd = db.CreateCommand ("CREATE TABLE IF NOT EXISTS buddies (identity string)"))
cmd.ExecuteNonQuery();
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dataflow.V1Beta3
{
/// <summary>Settings for <see cref="JobsV1Beta3Client"/> instances.</summary>
public sealed partial class JobsV1Beta3Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="JobsV1Beta3Settings"/>.</summary>
/// <returns>A new instance of the default <see cref="JobsV1Beta3Settings"/>.</returns>
public static JobsV1Beta3Settings GetDefault() => new JobsV1Beta3Settings();
/// <summary>Constructs a new <see cref="JobsV1Beta3Settings"/> object with default settings.</summary>
public JobsV1Beta3Settings()
{
}
private JobsV1Beta3Settings(JobsV1Beta3Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateJobSettings = existing.CreateJobSettings;
GetJobSettings = existing.GetJobSettings;
UpdateJobSettings = existing.UpdateJobSettings;
ListJobsSettings = existing.ListJobsSettings;
AggregatedListJobsSettings = existing.AggregatedListJobsSettings;
CheckActiveJobsSettings = existing.CheckActiveJobsSettings;
SnapshotJobSettings = existing.SnapshotJobSettings;
OnCopy(existing);
}
partial void OnCopy(JobsV1Beta3Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>JobsV1Beta3Client.CreateJob</c>
/// and <c>JobsV1Beta3Client.CreateJobAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateJobSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>JobsV1Beta3Client.GetJob</c>
/// and <c>JobsV1Beta3Client.GetJobAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetJobSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>JobsV1Beta3Client.UpdateJob</c>
/// and <c>JobsV1Beta3Client.UpdateJobAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateJobSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>JobsV1Beta3Client.ListJobs</c>
/// and <c>JobsV1Beta3Client.ListJobsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListJobsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>JobsV1Beta3Client.AggregatedListJobs</c> and <c>JobsV1Beta3Client.AggregatedListJobsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings AggregatedListJobsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>JobsV1Beta3Client.CheckActiveJobs</c> and <c>JobsV1Beta3Client.CheckActiveJobsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CheckActiveJobsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>JobsV1Beta3Client.SnapshotJob</c> and <c>JobsV1Beta3Client.SnapshotJobAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SnapshotJobSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="JobsV1Beta3Settings"/> object.</returns>
public JobsV1Beta3Settings Clone() => new JobsV1Beta3Settings(this);
}
/// <summary>
/// Builder class for <see cref="JobsV1Beta3Client"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class JobsV1Beta3ClientBuilder : gaxgrpc::ClientBuilderBase<JobsV1Beta3Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public JobsV1Beta3Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public JobsV1Beta3ClientBuilder()
{
UseJwtAccessWithScopes = JobsV1Beta3Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref JobsV1Beta3Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<JobsV1Beta3Client> task);
/// <summary>Builds the resulting client.</summary>
public override JobsV1Beta3Client Build()
{
JobsV1Beta3Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<JobsV1Beta3Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<JobsV1Beta3Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private JobsV1Beta3Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return JobsV1Beta3Client.Create(callInvoker, Settings);
}
private async stt::Task<JobsV1Beta3Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return JobsV1Beta3Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => JobsV1Beta3Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => JobsV1Beta3Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => JobsV1Beta3Client.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>JobsV1Beta3 client wrapper, for convenient use.</summary>
/// <remarks>
/// Provides a method to create and modify Google Cloud Dataflow jobs.
/// A Job is a multi-stage computation graph run by the Cloud Dataflow service.
/// </remarks>
public abstract partial class JobsV1Beta3Client
{
/// <summary>
/// The default endpoint for the JobsV1Beta3 service, which is a host of "dataflow.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dataflow.googleapis.com:443";
/// <summary>The default JobsV1Beta3 scopes.</summary>
/// <remarks>
/// The default JobsV1Beta3 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/userinfo.email</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/userinfo.email",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="JobsV1Beta3Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="JobsV1Beta3ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="JobsV1Beta3Client"/>.</returns>
public static stt::Task<JobsV1Beta3Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new JobsV1Beta3ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="JobsV1Beta3Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="JobsV1Beta3ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="JobsV1Beta3Client"/>.</returns>
public static JobsV1Beta3Client Create() => new JobsV1Beta3ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="JobsV1Beta3Client"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="JobsV1Beta3Settings"/>.</param>
/// <returns>The created <see cref="JobsV1Beta3Client"/>.</returns>
internal static JobsV1Beta3Client Create(grpccore::CallInvoker callInvoker, JobsV1Beta3Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
JobsV1Beta3.JobsV1Beta3Client grpcClient = new JobsV1Beta3.JobsV1Beta3Client(callInvoker);
return new JobsV1Beta3ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC JobsV1Beta3 client</summary>
public virtual JobsV1Beta3.JobsV1Beta3Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates a Cloud Dataflow job.
///
/// To create a job, we recommend using `projects.locations.jobs.create` with a
/// [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.create` is not recommended, as your job will always start
/// in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Job CreateJob(CreateJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a Cloud Dataflow job.
///
/// To create a job, we recommend using `projects.locations.jobs.create` with a
/// [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.create` is not recommended, as your job will always start
/// in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Job> CreateJobAsync(CreateJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a Cloud Dataflow job.
///
/// To create a job, we recommend using `projects.locations.jobs.create` with a
/// [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.create` is not recommended, as your job will always start
/// in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Job> CreateJobAsync(CreateJobRequest request, st::CancellationToken cancellationToken) =>
CreateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the state of the specified Cloud Dataflow job.
///
/// To get the state of a job, we recommend using `projects.locations.jobs.get`
/// with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.get` is not recommended, as you can only get the state of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Job GetJob(GetJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the state of the specified Cloud Dataflow job.
///
/// To get the state of a job, we recommend using `projects.locations.jobs.get`
/// with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.get` is not recommended, as you can only get the state of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Job> GetJobAsync(GetJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the state of the specified Cloud Dataflow job.
///
/// To get the state of a job, we recommend using `projects.locations.jobs.get`
/// with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.get` is not recommended, as you can only get the state of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Job> GetJobAsync(GetJobRequest request, st::CancellationToken cancellationToken) =>
GetJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the state of an existing Cloud Dataflow job.
///
/// To update the state of an existing job, we recommend using
/// `projects.locations.jobs.update` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.update` is not recommended, as you can only update the state
/// of jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Job UpdateJob(UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the state of an existing Cloud Dataflow job.
///
/// To update the state of an existing job, we recommend using
/// `projects.locations.jobs.update` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.update` is not recommended, as you can only update the state
/// of jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Job> UpdateJobAsync(UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the state of an existing Cloud Dataflow job.
///
/// To update the state of an existing job, we recommend using
/// `projects.locations.jobs.update` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.update` is not recommended, as you can only update the state
/// of jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Job> UpdateJobAsync(UpdateJobRequest request, st::CancellationToken cancellationToken) =>
UpdateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// List the jobs of a project.
///
/// To list the jobs of a project in a region, we recommend using
/// `projects.locations.jobs.list` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). To
/// list the all jobs across all regions, use `projects.jobs.aggregated`. Using
/// `projects.jobs.list` is not recommended, as you can only get the list of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Job"/> resources.</returns>
public virtual gax::PagedEnumerable<ListJobsResponse, Job> ListJobs(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// List the jobs of a project.
///
/// To list the jobs of a project in a region, we recommend using
/// `projects.locations.jobs.list` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). To
/// list the all jobs across all regions, use `projects.jobs.aggregated`. Using
/// `projects.jobs.list` is not recommended, as you can only get the list of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Job"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListJobsResponse, Job> ListJobsAsync(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// List the jobs of a project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Job"/> resources.</returns>
public virtual gax::PagedEnumerable<ListJobsResponse, Job> AggregatedListJobs(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// List the jobs of a project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Job"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListJobsResponse, Job> AggregatedListJobsAsync(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Check for existence of active jobs in the given project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual CheckActiveJobsResponse CheckActiveJobs(CheckActiveJobsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Check for existence of active jobs in the given project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CheckActiveJobsResponse> CheckActiveJobsAsync(CheckActiveJobsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Check for existence of active jobs in the given project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CheckActiveJobsResponse> CheckActiveJobsAsync(CheckActiveJobsRequest request, st::CancellationToken cancellationToken) =>
CheckActiveJobsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Snapshot the state of a streaming job.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Snapshot SnapshotJob(SnapshotJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Snapshot the state of a streaming job.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Snapshot> SnapshotJobAsync(SnapshotJobRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Snapshot the state of a streaming job.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Snapshot> SnapshotJobAsync(SnapshotJobRequest request, st::CancellationToken cancellationToken) =>
SnapshotJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>JobsV1Beta3 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Provides a method to create and modify Google Cloud Dataflow jobs.
/// A Job is a multi-stage computation graph run by the Cloud Dataflow service.
/// </remarks>
public sealed partial class JobsV1Beta3ClientImpl : JobsV1Beta3Client
{
private readonly gaxgrpc::ApiCall<CreateJobRequest, Job> _callCreateJob;
private readonly gaxgrpc::ApiCall<GetJobRequest, Job> _callGetJob;
private readonly gaxgrpc::ApiCall<UpdateJobRequest, Job> _callUpdateJob;
private readonly gaxgrpc::ApiCall<ListJobsRequest, ListJobsResponse> _callListJobs;
private readonly gaxgrpc::ApiCall<ListJobsRequest, ListJobsResponse> _callAggregatedListJobs;
private readonly gaxgrpc::ApiCall<CheckActiveJobsRequest, CheckActiveJobsResponse> _callCheckActiveJobs;
private readonly gaxgrpc::ApiCall<SnapshotJobRequest, Snapshot> _callSnapshotJob;
/// <summary>
/// Constructs a client wrapper for the JobsV1Beta3 service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="JobsV1Beta3Settings"/> used within this client.</param>
public JobsV1Beta3ClientImpl(JobsV1Beta3.JobsV1Beta3Client grpcClient, JobsV1Beta3Settings settings)
{
GrpcClient = grpcClient;
JobsV1Beta3Settings effectiveSettings = settings ?? JobsV1Beta3Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateJob = clientHelper.BuildApiCall<CreateJobRequest, Job>(grpcClient.CreateJobAsync, grpcClient.CreateJob, effectiveSettings.CreateJobSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location);
Modify_ApiCall(ref _callCreateJob);
Modify_CreateJobApiCall(ref _callCreateJob);
_callGetJob = clientHelper.BuildApiCall<GetJobRequest, Job>(grpcClient.GetJobAsync, grpcClient.GetJob, effectiveSettings.GetJobSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location).WithGoogleRequestParam("job_id", request => request.JobId);
Modify_ApiCall(ref _callGetJob);
Modify_GetJobApiCall(ref _callGetJob);
_callUpdateJob = clientHelper.BuildApiCall<UpdateJobRequest, Job>(grpcClient.UpdateJobAsync, grpcClient.UpdateJob, effectiveSettings.UpdateJobSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location).WithGoogleRequestParam("job_id", request => request.JobId);
Modify_ApiCall(ref _callUpdateJob);
Modify_UpdateJobApiCall(ref _callUpdateJob);
_callListJobs = clientHelper.BuildApiCall<ListJobsRequest, ListJobsResponse>(grpcClient.ListJobsAsync, grpcClient.ListJobs, effectiveSettings.ListJobsSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location);
Modify_ApiCall(ref _callListJobs);
Modify_ListJobsApiCall(ref _callListJobs);
_callAggregatedListJobs = clientHelper.BuildApiCall<ListJobsRequest, ListJobsResponse>(grpcClient.AggregatedListJobsAsync, grpcClient.AggregatedListJobs, effectiveSettings.AggregatedListJobsSettings).WithGoogleRequestParam("project_id", request => request.ProjectId);
Modify_ApiCall(ref _callAggregatedListJobs);
Modify_AggregatedListJobsApiCall(ref _callAggregatedListJobs);
_callCheckActiveJobs = clientHelper.BuildApiCall<CheckActiveJobsRequest, CheckActiveJobsResponse>(grpcClient.CheckActiveJobsAsync, grpcClient.CheckActiveJobs, effectiveSettings.CheckActiveJobsSettings);
Modify_ApiCall(ref _callCheckActiveJobs);
Modify_CheckActiveJobsApiCall(ref _callCheckActiveJobs);
_callSnapshotJob = clientHelper.BuildApiCall<SnapshotJobRequest, Snapshot>(grpcClient.SnapshotJobAsync, grpcClient.SnapshotJob, effectiveSettings.SnapshotJobSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location).WithGoogleRequestParam("job_id", request => request.JobId);
Modify_ApiCall(ref _callSnapshotJob);
Modify_SnapshotJobApiCall(ref _callSnapshotJob);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateJobApiCall(ref gaxgrpc::ApiCall<CreateJobRequest, Job> call);
partial void Modify_GetJobApiCall(ref gaxgrpc::ApiCall<GetJobRequest, Job> call);
partial void Modify_UpdateJobApiCall(ref gaxgrpc::ApiCall<UpdateJobRequest, Job> call);
partial void Modify_ListJobsApiCall(ref gaxgrpc::ApiCall<ListJobsRequest, ListJobsResponse> call);
partial void Modify_AggregatedListJobsApiCall(ref gaxgrpc::ApiCall<ListJobsRequest, ListJobsResponse> call);
partial void Modify_CheckActiveJobsApiCall(ref gaxgrpc::ApiCall<CheckActiveJobsRequest, CheckActiveJobsResponse> call);
partial void Modify_SnapshotJobApiCall(ref gaxgrpc::ApiCall<SnapshotJobRequest, Snapshot> call);
partial void OnConstruction(JobsV1Beta3.JobsV1Beta3Client grpcClient, JobsV1Beta3Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC JobsV1Beta3 client</summary>
public override JobsV1Beta3.JobsV1Beta3Client GrpcClient { get; }
partial void Modify_CreateJobRequest(ref CreateJobRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetJobRequest(ref GetJobRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateJobRequest(ref UpdateJobRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListJobsRequest(ref ListJobsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CheckActiveJobsRequest(ref CheckActiveJobsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_SnapshotJobRequest(ref SnapshotJobRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates a Cloud Dataflow job.
///
/// To create a job, we recommend using `projects.locations.jobs.create` with a
/// [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.create` is not recommended, as your job will always start
/// in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Job CreateJob(CreateJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateJobRequest(ref request, ref callSettings);
return _callCreateJob.Sync(request, callSettings);
}
/// <summary>
/// Creates a Cloud Dataflow job.
///
/// To create a job, we recommend using `projects.locations.jobs.create` with a
/// [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.create` is not recommended, as your job will always start
/// in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Job> CreateJobAsync(CreateJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateJobRequest(ref request, ref callSettings);
return _callCreateJob.Async(request, callSettings);
}
/// <summary>
/// Gets the state of the specified Cloud Dataflow job.
///
/// To get the state of a job, we recommend using `projects.locations.jobs.get`
/// with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.get` is not recommended, as you can only get the state of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Job GetJob(GetJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetJobRequest(ref request, ref callSettings);
return _callGetJob.Sync(request, callSettings);
}
/// <summary>
/// Gets the state of the specified Cloud Dataflow job.
///
/// To get the state of a job, we recommend using `projects.locations.jobs.get`
/// with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.get` is not recommended, as you can only get the state of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Job> GetJobAsync(GetJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetJobRequest(ref request, ref callSettings);
return _callGetJob.Async(request, callSettings);
}
/// <summary>
/// Updates the state of an existing Cloud Dataflow job.
///
/// To update the state of an existing job, we recommend using
/// `projects.locations.jobs.update` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.update` is not recommended, as you can only update the state
/// of jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Job UpdateJob(UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateJobRequest(ref request, ref callSettings);
return _callUpdateJob.Sync(request, callSettings);
}
/// <summary>
/// Updates the state of an existing Cloud Dataflow job.
///
/// To update the state of an existing job, we recommend using
/// `projects.locations.jobs.update` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). Using
/// `projects.jobs.update` is not recommended, as you can only update the state
/// of jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Job> UpdateJobAsync(UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateJobRequest(ref request, ref callSettings);
return _callUpdateJob.Async(request, callSettings);
}
/// <summary>
/// List the jobs of a project.
///
/// To list the jobs of a project in a region, we recommend using
/// `projects.locations.jobs.list` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). To
/// list the all jobs across all regions, use `projects.jobs.aggregated`. Using
/// `projects.jobs.list` is not recommended, as you can only get the list of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Job"/> resources.</returns>
public override gax::PagedEnumerable<ListJobsResponse, Job> ListJobs(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListJobsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListJobsRequest, ListJobsResponse, Job>(_callListJobs, request, callSettings);
}
/// <summary>
/// List the jobs of a project.
///
/// To list the jobs of a project in a region, we recommend using
/// `projects.locations.jobs.list` with a [regional endpoint]
/// (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). To
/// list the all jobs across all regions, use `projects.jobs.aggregated`. Using
/// `projects.jobs.list` is not recommended, as you can only get the list of
/// jobs that are running in `us-central1`.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Job"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListJobsResponse, Job> ListJobsAsync(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListJobsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListJobsRequest, ListJobsResponse, Job>(_callListJobs, request, callSettings);
}
/// <summary>
/// List the jobs of a project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Job"/> resources.</returns>
public override gax::PagedEnumerable<ListJobsResponse, Job> AggregatedListJobs(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListJobsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListJobsRequest, ListJobsResponse, Job>(_callAggregatedListJobs, request, callSettings);
}
/// <summary>
/// List the jobs of a project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Job"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListJobsResponse, Job> AggregatedListJobsAsync(ListJobsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListJobsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListJobsRequest, ListJobsResponse, Job>(_callAggregatedListJobs, request, callSettings);
}
/// <summary>
/// Check for existence of active jobs in the given project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override CheckActiveJobsResponse CheckActiveJobs(CheckActiveJobsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CheckActiveJobsRequest(ref request, ref callSettings);
return _callCheckActiveJobs.Sync(request, callSettings);
}
/// <summary>
/// Check for existence of active jobs in the given project across all regions.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<CheckActiveJobsResponse> CheckActiveJobsAsync(CheckActiveJobsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CheckActiveJobsRequest(ref request, ref callSettings);
return _callCheckActiveJobs.Async(request, callSettings);
}
/// <summary>
/// Snapshot the state of a streaming job.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Snapshot SnapshotJob(SnapshotJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SnapshotJobRequest(ref request, ref callSettings);
return _callSnapshotJob.Sync(request, callSettings);
}
/// <summary>
/// Snapshot the state of a streaming job.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Snapshot> SnapshotJobAsync(SnapshotJobRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SnapshotJobRequest(ref request, ref callSettings);
return _callSnapshotJob.Async(request, callSettings);
}
}
public partial class ListJobsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListJobsResponse : gaxgrpc::IPageResponse<Job>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Job> GetEnumerator() => Jobs.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1
{
internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer
{
private readonly int _correlationId;
private readonly MemberRangeMap _memberRangeMap;
private readonly AnalyzerExecutor _executor;
private readonly StateManager _stateManager;
private readonly SimpleTaskQueue _eventQueue;
public DiagnosticIncrementalAnalyzer(
DiagnosticAnalyzerService owner,
int correlationId,
Workspace workspace,
HostAnalyzerManager analyzerManager,
AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
: base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
{
_correlationId = correlationId;
_memberRangeMap = new MemberRangeMap();
_executor = new AnalyzerExecutor(this);
_eventQueue = new SimpleTaskQueue(TaskScheduler.Default);
_stateManager = new StateManager(analyzerManager);
_stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
}
private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e)
{
if (e.Removed.Length == 0)
{
// nothing to refresh
return;
}
// guarantee order of the events.
var asyncToken = Owner.Listener.BeginAsyncOperation(nameof(OnProjectAnalyzerReferenceChanged));
_eventQueue.ScheduleTask(() => ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None), CancellationToken.None).CompletesAsyncOperation(asyncToken);
}
public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
{
return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken);
}
}
public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken))
{
// we don't need the info for closed file
_memberRangeMap.Remove(document.Id);
return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken);
}
}
public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
{
// unlike document open or close where we don't know whether this document will be re-analyzed again due to
// engine's option such as "Close File Diagnostics", this one will be called when we want to re-analyze the document
// for whatever reason. so we let events to be raised when actual analysis happens but clear the cache so that
// we don't return existing data without re-analysis.
return ClearOnlyDocumentStates(document, raiseEvent: false, cancellationToken: cancellationToken);
}
}
private Task ClearOnlyDocumentStates(Document document, bool raiseEvent, CancellationToken cancellationToken)
{
// we remove whatever information we used to have on document open/close and re-calculate diagnostics
// we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not.
// so we can't use cached information.
ClearDocumentStates(document, _stateManager.GetStateSets(document.Project), raiseEvent, includeProjectState: false, cancellationToken: cancellationToken);
return SpecializedTasks.EmptyTask;
}
private bool CheckOption(Workspace workspace, string language, bool documentOpened)
{
var optionService = workspace.Services.GetService<IOptionService>();
if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language))
{
return true;
}
if (documentOpened)
{
return true;
}
return false;
}
internal IEnumerable<DiagnosticAnalyzer> GetAnalyzers(Project project)
{
return _stateManager.GetAnalyzers(project);
}
public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken);
var openedDocument = document.IsOpen();
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project))
{
if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds))
{
var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsCreated(StateType.Syntax, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
var state = stateSet.GetState(StateType.Syntax);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion, projectVersion);
if (bodyOpt == null)
{
await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false);
}
else
{
// only open file can go this route
await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken)
{
try
{
// syntax facts service must exist, otherwise, this method won't have called.
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberId = syntaxFacts.GetMethodLevelMemberId(root, member);
var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, this, cancellationToken);
var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this, cancellationToken);
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project))
{
if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document))
{
var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis();
var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver;
var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document);
var data = await _executor.GetDocumentBodyAnalysisDataAsync(
stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false);
_memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges);
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsCreated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken);
bool openedDocument = document.IsOpen();
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project))
{
if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds))
{
var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsCreated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
if (openedDocument)
{
_memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion);
}
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken)
{
try
{
// Compilation actions can report diagnostics on open files, so "documentOpened = true"
if (!CheckOption(project.Solution.Workspace, project.Language, documentOpened: true))
{
return;
}
var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, cancellationToken);
var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion);
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(project))
{
// Compilation actions can report diagnostics on open files, so we skipClosedFileChecks.
if (SkipRunningAnalyzer(project.CompilationOptions, analyzerDriver, openedDocument: true, skipClosedFileChecks: true, stateSet: stateSet))
{
await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null))
{
var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseProjectDiagnosticsUpdated(project, stateSet, data.Items);
continue;
}
var state = stateSet.GetState(StateType.Project);
await PersistProjectData(project, state, data).ConfigureAwait(false);
RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private bool SkipRunningAnalyzer(
CompilationOptions compilationOptions,
DiagnosticAnalyzerDriver userDiagnosticDriver,
bool openedDocument,
bool skipClosedFileChecks,
StateSet stateSet)
{
if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, userDiagnosticDriver.Project))
{
return true;
}
if (skipClosedFileChecks)
{
return false;
}
if (ShouldRunAnalyzerForClosedFile(compilationOptions, openedDocument, stateSet.Analyzer))
{
return false;
}
return true;
}
private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data)
{
// TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to
// things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesn't come online soon enough
// more refactoring is required on project state.
// clear all existing data
state.Remove(project.Id);
foreach (var document in project.Documents)
{
state.Remove(document.Id);
}
// quick bail out
if (data.Items.Length == 0)
{
return;
}
// save new data
var group = data.Items.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
// save project scope diagnostics
await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
continue;
}
// save document scope diagnostics
var document = project.GetDocument(kv.Key);
if (document == null)
{
continue;
}
await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
}
}
public override void RemoveDocument(DocumentId documentId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
{
_memberRangeMap.Remove(documentId);
foreach (var stateSet in _stateManager.GetStateSets(documentId.ProjectId))
{
stateSet.Remove(documentId);
var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId);
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
RaiseDiagnosticsRemoved((StateType)stateType, documentId, stateSet, solutionArgs);
}
}
}
}
public override void RemoveProject(ProjectId projectId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
{
foreach (var stateSet in _stateManager.GetStateSets(projectId))
{
stateSet.Remove(projectId);
var solutionArgs = new SolutionArgument(null, projectId, null);
RaiseDiagnosticsRemoved(StateType.Project, projectId, stateSet, solutionArgs);
}
}
_stateManager.RemoveStateSet(projectId);
}
public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken);
return await getter.TryGetAsync().ConfigureAwait(false);
}
public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken);
var result = await getter.TryGetAsync().ConfigureAwait(false);
Contract.Requires(result);
return getter.Diagnostics;
}
private bool ShouldRunAnalyzerForClosedFile(CompilationOptions options, bool openedDocument, DiagnosticAnalyzer analyzer)
{
// we have opened document, doesn't matter
if (openedDocument || analyzer.IsCompilerAnalyzer())
{
return true;
}
// PERF: Don't query descriptors for compiler analyzer, always execute it.
if (analyzer.IsCompilerAnalyzer())
{
return true;
}
return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden);
}
private static ReportDiagnostic GetEffectiveSeverity(DiagnosticDescriptor descriptor, CompilationOptions options)
{
return options == null
? MapSeverityToReport(descriptor.DefaultSeverity)
: descriptor.GetEffectiveSeverity(options);
}
private static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity)
{
switch (severity)
{
case DiagnosticSeverity.Hidden:
return ReportDiagnostic.Hidden;
case DiagnosticSeverity.Info:
return ReportDiagnostic.Info;
case DiagnosticSeverity.Warning:
return ReportDiagnostic.Warn;
case DiagnosticSeverity.Error:
return ReportDiagnostic.Error;
default:
throw ExceptionUtilities.Unreachable;
}
}
private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds)
{
return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors);
}
private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId,
ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null)
{
// PERF: Don't query descriptors for compiler analyzer, always execute it for all state types.
if (analyzer.IsCompilerAnalyzer())
{
return true;
}
if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id)))
{
return false;
}
switch (stateTypeId)
{
case StateType.Syntax:
return analyzer.SupportsSyntaxDiagnosticAnalysis();
case StateType.Document:
return analyzer.SupportsSemanticDiagnosticAnalysis();
case StateType.Project:
return analyzer.SupportsProjectDiagnosticAnalysis();
default:
throw ExceptionUtilities.Unreachable;
}
}
public override void LogAnalyzerCountSummary()
{
DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator);
DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator);
// reset the log aggregator
ResetDiagnosticLogAggregator();
}
private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) &&
project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private void RaiseDocumentDiagnosticsUpdatedIfNeeded(
StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseDiagnosticsCreated(type, document.Id, stateSet, new SolutionArgument(document), newItems);
}
private void RaiseProjectDiagnosticsUpdatedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems);
RaiseProjectDiagnosticsUpdated(project, stateSet, newItems);
}
private void RaiseProjectDiagnosticsRemovedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
if (existingItems.Length == 0)
{
return;
}
var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key));
foreach (var documentId in removedItems)
{
if (documentId == null)
{
RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project));
continue;
}
var document = project.GetDocument(documentId);
var argument = documentId == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document);
RaiseDiagnosticsRemoved(StateType.Project, documentId, stateSet, argument);
}
}
private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics)
{
var group = diagnostics.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
RaiseDiagnosticsCreated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty());
continue;
}
RaiseDiagnosticsCreated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty());
}
}
private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId)
{
return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty;
}
private void RaiseDiagnosticsCreated(
StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics)
{
if (Owner == null)
{
return;
}
// get right arg id for the given analyzer
var id = CreateArgumentKey(type, key, stateSet);
Owner.RaiseDiagnosticsUpdated(this,
DiagnosticsUpdatedArgs.DiagnosticsCreated(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics));
}
private static ArgumentKey CreateArgumentKey(StateType type, object key, StateSet stateSet)
{
return stateSet.ErrorSourceName != null
? new HostAnalyzerKey(stateSet.Analyzer, type, key, stateSet.ErrorSourceName)
: new ArgumentKey(stateSet.Analyzer, type, key);
}
private void RaiseDiagnosticsRemoved(
StateType type, object key, StateSet stateSet, SolutionArgument solution)
{
if (Owner == null)
{
return;
}
// get right arg id for the given analyzer
var id = CreateArgumentKey(type, key, stateSet);
Owner.RaiseDiagnosticsUpdated(this,
DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId));
}
private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics(
AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics,
SyntaxTree tree, SyntaxNode member, int memberId)
{
// get old span
var oldSpan = range[memberId];
// get old diagnostics
var diagnostics = existingData.Items;
// check quick exit cases
if (diagnostics.Length == 0 && memberDiagnostics.Length == 0)
{
return diagnostics;
}
// simple case
if (diagnostics.Length == 0 && memberDiagnostics.Length > 0)
{
return memberDiagnostics;
}
// regular case
var result = new List<DiagnosticData>();
// update member location
Contract.Requires(member.FullSpan.Start == oldSpan.Start);
var delta = member.FullSpan.End - oldSpan.End;
var replaced = false;
foreach (var diagnostic in diagnostics)
{
if (diagnostic.TextSpan.Start < oldSpan.Start)
{
result.Add(diagnostic);
continue;
}
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
if (oldSpan.End <= diagnostic.TextSpan.Start)
{
result.Add(UpdatePosition(diagnostic, tree, delta));
continue;
}
}
// if it haven't replaced, replace it now
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
return result.ToImmutableArray();
}
private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta)
{
var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length);
var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length);
var mappedLineInfo = tree.GetMappedLineSpan(newSpan);
var originalLineInfo = tree.GetLineSpan(newSpan);
return new DiagnosticData(
diagnostic.Id,
diagnostic.Category,
diagnostic.Message,
diagnostic.ENUMessageForBingSearch,
diagnostic.Severity,
diagnostic.DefaultSeverity,
diagnostic.IsEnabledByDefault,
diagnostic.WarningLevel,
diagnostic.CustomTags,
diagnostic.Properties,
diagnostic.Workspace,
diagnostic.ProjectId,
new DiagnosticDataLocation(diagnostic.DocumentId, newSpan,
originalFilePath: originalLineInfo.Path,
originalStartLine: originalLineInfo.StartLinePosition.Line,
originalStartColumn: originalLineInfo.StartLinePosition.Character,
originalEndLine: originalLineInfo.EndLinePosition.Line,
originalEndColumn: originalLineInfo.EndLinePosition.Character,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
mappedStartLine: mappedLineInfo.StartLinePosition.Line,
mappedStartColumn: mappedLineInfo.StartLinePosition.Character,
mappedEndLine: mappedLineInfo.EndLinePosition.Line,
mappedEndColumn: mappedLineInfo.EndLinePosition.Character),
description: diagnostic.Description,
helpLink: diagnostic.HelpLink,
isSuppressed: diagnostic.IsSuppressed);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics)
{
return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null;
}
private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span)
{
if (diagnostic == null)
{
return false;
}
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
return false;
}
if (diagnostic.Location.SourceTree != tree)
{
return false;
}
if (span == null)
{
return true;
}
return span.Value.Contains(diagnostic.Location.SourceSpan);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics)
{
if (diagnostics == null)
{
yield break;
}
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
yield return DiagnosticData.Create(project, diagnostic);
continue;
}
var document = project.GetDocument(diagnostic.Location.SourceTree);
if (document == null)
{
continue;
}
yield return DiagnosticData.Create(document, diagnostic);
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private void ClearDocumentStates(
Document document, IEnumerable<StateSet> states,
bool raiseEvent, bool includeProjectState,
CancellationToken cancellationToken)
{
// Compiler + User diagnostics
foreach (var state in states)
{
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
if (!includeProjectState && stateType == (int)StateType.Project)
{
// don't re-set project state type
continue;
}
cancellationToken.ThrowIfCancellationRequested();
ClearDocumentState(document, state, (StateType)stateType, raiseEvent);
}
}
}
private void ClearDocumentState(Document document, StateSet stateSet, StateType type, bool raiseEvent)
{
var state = stateSet.GetState(type);
// remove saved info
state.Remove(document.Id);
if (raiseEvent)
{
// raise diagnostic updated event
var documentId = document.Id;
var solutionArgs = new SolutionArgument(document);
RaiseDiagnosticsRemoved(type, document.Id, stateSet, solutionArgs);
}
}
private void ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken)
{
foreach (var document in project.Documents)
{
ClearDocumentStates(document, states, raiseEvent: true, includeProjectState: true, cancellationToken: cancellationToken);
}
foreach (var stateSet in states)
{
cancellationToken.ThrowIfCancellationRequested();
ClearProjectState(project, stateSet);
}
}
private void ClearProjectState(Project project, StateSet stateSet)
{
var state = stateSet.GetState(StateType.Project);
// remove saved cache
state.Remove(project.Id);
// raise diagnostic updated event
var solutionArgs = new SolutionArgument(project);
RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, solutionArgs);
}
private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken)
{
var state = stateSet.GetState(type);
var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
ClearDocumentState(document, stateSet, type, raiseEvent: true);
}
}
private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken)
{
var state = stateSet.GetState(StateType.Project);
var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
ClearProjectState(project, stateSet);
}
}
private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer)
{
return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString());
}
private static string GetResetLogMessage(Document document)
{
return string.Format("document reset: {0}", document.FilePath ?? document.Name);
}
private static string GetOpenLogMessage(Document document)
{
return string.Format("document open: {0}", document.FilePath ?? document.Name);
}
private static string GetRemoveLogMessage(DocumentId id)
{
return string.Format("document remove: {0}", id.ToString());
}
private static string GetRemoveLogMessage(ProjectId id)
{
return string.Format("project remove: {0}", id.ToString());
}
public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
}
}
| |
using ShopifySharp.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace ShopifySharp.Tests
{
[Trait("Category", "Product")]
public class Product_Tests : IClassFixture<Product_Tests_Fixture>
{
private Product_Tests_Fixture Fixture { get; }
public Product_Tests(Product_Tests_Fixture fixture)
{
this.Fixture = fixture;
}
[Fact]
public async Task Counts_Products()
{
var count = await Fixture.Service.CountAsync();
Assert.True(count > 0);
}
[Fact]
public async Task Lists_Products_NoFilter()
{
var list = await Fixture.Service.ListAsync();
Assert.True(list.Items.Any());
if (list.LinkHeader != null)
{
Assert.NotNull(list.LinkHeader.NextLink);
Assert.NotNull(list.LinkHeader.NextLink.PageInfo);
Assert.NotNull(list.LinkHeader.NextLink.Url);
}
}
[Fact]
public async Task Lists_Products_ComparePagingByCursorAndBySinceId()
{
var list = await Fixture.Service.ListAsync(new ProductListFilter
{
SinceId = 0,
Limit = 2
});
Assert.True(list.Items.Count() == 2);
Assert.NotNull(list.LinkHeader.NextLink);
Assert.NotNull(list.LinkHeader.NextLink.PageInfo);
Assert.NotNull(list.LinkHeader.NextLink.Url);
var nextPageViaCursor = await Fixture.Service.ListAsync(list.GetNextPageFilter(2));
Assert.True(list.Items.Count() == 2);
Assert.NotNull(list.LinkHeader.NextLink);
Assert.NotNull(list.LinkHeader.NextLink.PageInfo);
Assert.NotNull(list.LinkHeader.NextLink.Url);
var nextPageViaSinceId = await Fixture.Service.ListAsync(new ProductListFilter
{
SinceId = list.Items.Last().Id.Value,
Limit = 2
});
Assert.True(list.Items.Count() == 2);
Assert.NotNull(list.LinkHeader.NextLink);
Assert.NotNull(list.LinkHeader.NextLink.PageInfo);
Assert.NotNull(list.LinkHeader.NextLink.Url);
Assert.True(Enumerable.SequenceEqual(nextPageViaCursor.Items.Select(i => i.Id.Value),
nextPageViaSinceId.Items.Select(i => i.Id.Value)));
}
[Fact]
public async Task Lists_Products_PageAll()
{
var svc = Fixture.Service;
var list = await svc.ListAsync(new ProductListFilter { Limit = 5 });
while (true)
{
Assert.True(list.Items.Any());
list = await svc.ListAsync(list.GetNextPageFilter());
if (!list.HasNextPage)
break;
}
}
[Fact]
public async Task List_Products_By_Status()
{
var svc = Fixture.Service;
var list = await svc.ListAsync(new ProductListFilter { Limit = 5 });
Assert.True(list.Items.Any()); //if we get something here, then...
list = await svc.ListAsync(new ProductListFilter { Limit = 5, Status = "active" });
bool anyActive = list.Items.Any();
if (anyActive)
Assert.True(list.Items.All(x => x.Status == "active"));
list = await svc.ListAsync(new ProductListFilter { Limit = 5, Status = "draft" });
bool anyDraft = list.Items.Any();
if (anyDraft)
Assert.True(list.Items.All(x => x.Status == "draft"));
list = await svc.ListAsync(new ProductListFilter { Limit = 5, Status = "archived" });
bool anyArchive = list.Items.Any();
if (anyDraft)
Assert.True(list.Items.All(x => x.Status == "archived"));
Assert.False(!anyActive && !anyDraft && !anyArchive); //we should make sure we get something here (these represent all statuses for a product)
}
[Fact]
public async Task Deletes_Products()
{
var created = await Fixture.Create(true);
bool threw = false;
try
{
await Fixture.Service.DeleteAsync(created.Id.Value);
}
catch (ShopifyException ex)
{
Console.WriteLine($"{nameof(Deletes_Products)} failed. {ex.Message}");
threw = true;
}
Assert.False(threw);
}
[Fact]
public async Task Gets_Products()
{
var obj = await Fixture.Service.GetAsync(Fixture.Created.First().Id.Value);
Assert.NotNull(obj);
Assert.True(obj.Id.HasValue);
Assert.Equal(Fixture.Title, obj.Title);
Assert.Equal(Fixture.BodyHtml, obj.BodyHtml);
Assert.Equal(Fixture.ProductType, obj.ProductType);
Assert.Equal(Fixture.Vendor, obj.Vendor);
}
[Fact]
public async Task Creates_Products()
{
var obj = await Fixture.Create();
Assert.NotNull(obj);
Assert.True(obj.Id.HasValue);
Assert.Equal(Fixture.Title, obj.Title);
Assert.Equal(Fixture.BodyHtml, obj.BodyHtml);
Assert.Equal(Fixture.ProductType, obj.ProductType);
Assert.Equal(Fixture.Vendor, obj.Vendor);
}
[Fact]
public async Task Creates_Unpublished_Products()
{
var created = await Fixture.Create(options: new ProductCreateOptions()
{
Published = false
});
Assert.False(created.PublishedAt.HasValue);
}
[Fact]
public async Task Updates_Products()
{
string title = "ShopifySharp Updated Test Product";
var created = await Fixture.Create();
long id = created.Id.Value;
created.Title = title;
created.Id = null;
var updated = await Fixture.Service.UpdateAsync(id, created);
// Reset the id so the Fixture can properly delete this object.
created.Id = id;
Assert.Equal(title, updated.Title);
}
[Fact]
public async Task Publishes_Products()
{
var created = await Fixture.Create(options: new ProductCreateOptions()
{
Published = false
});
var published = await Fixture.Service.PublishAsync(created.Id.Value);
Assert.True(published.PublishedAt.HasValue);
}
[Fact]
public async Task Unpublishes_Products()
{
var created = await Fixture.Create(options: new ProductCreateOptions()
{
Published = true
});
var unpublished = await Fixture.Service.UnpublishAsync(created.Id.Value);
Assert.False(unpublished.PublishedAt.HasValue);
}
}
public class Product_Tests_Fixture : IAsyncLifetime
{
public ProductService Service { get; } = new ProductService(Utils.MyShopifyUrl, Utils.AccessToken);
public List<Product> Created { get; } = new List<Product>();
public string Title => "ShopifySharp Test Product";
public string Vendor = "Auntie Dot";
public string BodyHtml => "<strong>This product was created while testing ShopifySharp!</strong>";
public string ProductType => "Foobars";
public async Task InitializeAsync()
{
Service.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
// Create one for count, list, get, etc. orders.
await Create();
}
public async Task DisposeAsync()
{
foreach (var obj in Created)
{
try
{
await Service.DeleteAsync(obj.Id.Value);
}
catch (ShopifyException ex)
{
if (ex.HttpStatusCode != HttpStatusCode.NotFound)
{
Console.WriteLine($"Failed to delete created Product with id {obj.Id.Value}. {ex.Message}");
}
}
}
}
/// <summary>
/// Convenience function for running tests. Creates an object and automatically adds it to the queue for deleting after tests finish.
/// </summary>
public async Task<Product> Create(bool skipAddToCreateList = false, ProductCreateOptions options = null)
{
var obj = await Service.CreateAsync(new Product()
{
Title = Title,
Vendor = Vendor,
BodyHtml = BodyHtml,
ProductType = ProductType,
Handle = Guid.NewGuid().ToString(),
Images = new List<ProductImage>
{
new ProductImage
{
Attachment = "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
}
},
}, options);
if (!skipAddToCreateList)
{
Created.Add(obj);
}
return obj;
}
}
}
| |
namespace AngleSharp.Html.Dom
{
using AngleSharp.Common;
using AngleSharp.Dom;
using AngleSharp.Io;
using AngleSharp.Media.Dom;
using AngleSharp.Text;
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Represents the HTML canvas element.
/// See: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html
/// Alternative: http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#the-canvas-element
/// </summary>
sealed class HtmlCanvasElement : HtmlElement, IHtmlCanvasElement
{
#region Fields
private readonly IEnumerable<IRenderingService> _renderServices;
private ContextMode _mode;
private IRenderingContext? _current;
#endregion
#region ctor
/// <summary>
/// Creates a new HTML canvas element.
/// </summary>
public HtmlCanvasElement(Document owner, String? prefix = null)
: base(owner, TagNames.Canvas, prefix)
{
_renderServices = owner.Context.GetServices<IRenderingService>();
_mode = ContextMode.None;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the displayed width of the canvas element.
/// </summary>
public Int32 Width
{
get => this.GetOwnAttribute(AttributeNames.Width).ToInteger(300);
set => this.SetOwnAttribute(AttributeNames.Width, value.ToString());
}
/// <summary>
/// Gets or sets the displayed height of the canvas element.
/// </summary>
public Int32 Height
{
get => this.GetOwnAttribute(AttributeNames.Height).ToInteger(150);
set => this.SetOwnAttribute(AttributeNames.Height, value.ToString());
}
#endregion
#region Methods
/// <summary>
/// Gets the drawing context.
/// </summary>
/// <param name="contextId">A context id like 2d.</param>
/// <returns>An object that defines the drawing context.</returns>
public IRenderingContext GetContext(String contextId)
{
if (_current is null || contextId.Isi(_current.ContextId))
{
foreach (var renderService in _renderServices)
{
if (renderService.IsSupportingContext(contextId))
{
var context = renderService.CreateContext(this, contextId);
if (context != null)
{
_mode = GetModeFrom(contextId);
_current = context;
}
return context!;
}
}
return null!;
}
return _current;
}
/// <summary>
/// Gets an indicator if a context with the given parameters could be created.
/// </summary>
/// <param name="contextId">A context id like 2d.</param>
/// <returns>True if the context is supported, otherwise false.</returns>
public Boolean IsSupportingContext(String contextId)
{
foreach (var renderService in _renderServices)
{
if (renderService.IsSupportingContext(contextId))
{
return true;
}
}
return false;
}
/// <summary>
/// Changes the context the element is related to the given one.
/// </summary>
/// <param name="context">The new context.</param>
public void SetContext(IRenderingContext context)
{
if (_mode != ContextMode.None && _mode != ContextMode.Indirect)
{
throw new DomException(DomError.InvalidState);
}
if (context.IsFixed)
{
throw new DomException(DomError.InvalidState);
}
if (context.Host != this)
{
throw new DomException(DomError.InUse);
}
_current = context;
_mode = ContextMode.Indirect;
}
/// <summary>
/// Returns a Data URI with the bitmap data of the context.
/// </summary>
/// <param name="type">The type of image e.g image/png.</param>
/// <returns>A data URI with the data if any.</returns>
public String ToDataUrl(String? type = null)
{
var content = GetImageData(type);
return Convert.ToBase64String(content);
}
/// <summary>
/// Creates a BLOB out of the canvas pixel data and passes it
/// to the given callback.
/// </summary>
/// <param name="callback">The callback function.</param>
/// <param name="type">The type of object to create.</param>
public void ToBlob(Action<Stream> callback, String? type = null)
{
var content = GetImageData(type);
var ms = new MemoryStream(content);
callback(ms);
}
#endregion
#region Helpers
private Byte[] GetImageData(String? type)
{
return _current?.ToImage(type ?? MimeTypeNames.Plain) ?? new Byte[0];
}
private static ContextMode GetModeFrom(String contextId)
{
if (contextId.Isi(Keywords.TwoD))
{
return ContextMode.Direct2d;
}
else if (contextId.Isi(Keywords.WebGl))
{
return ContextMode.DirectWebGl;
}
return ContextMode.None;
}
#endregion
#region Context Mode
private enum ContextMode : byte
{
None,
Direct2d,
DirectWebGl,
Indirect,
Proxied
}
#endregion
}
}
| |
//
// load-exceptions.cs: Tests for loading missing types/methods/fields from IL
//
using System;
using System.IO;
using System.Reflection;
class Miss1 : Missing.Foo1 {
}
public class Miss2 {
public class Foo : Missing.Foo1 {
}
}
public class Tests : LoadMissing {
public delegate void TestDel ();
internal static int check_type_load (TestDel d) {
try {
d ();
}
catch (TypeLoadException ex) {
//Console.WriteLine (ex.TypeName);
//Console.WriteLine (ex);
return 0;
}
return 1;
}
internal static int check_missing_method (TestDel d) {
try {
d ();
}
catch (MissingMethodException ex) {
//Console.WriteLine (ex);
return 0;
}
return 1;
}
internal static int check_file_not_found (TestDel d){
try {
d ();
} catch (FileNotFoundException ex){
return 0;
}
return 1;
}
internal static int check_missing_field (TestDel d) {
try {
d ();
}
catch (MissingFieldException ex) {
//Console.WriteLine (ex);
return 0;
}
return 1;
}
//
// Base instructions
//
public static int test_0_call () {
return check_missing_method (new TestDel (missing_call));
}
public static int test_0_jmp () {
return check_missing_method (new TestDel (missing_jmp));
}
public static int test_0_ldftn () {
return check_missing_method (new TestDel (missing_ldftn));
}
//
// Object model instructions
//
public static int test_0_box () {
// Thrown earlier
return 0;
}
public static int test_0_callvirt () {
return check_missing_method (new TestDel (missing_callvirt));
}
public static int test_0_castclass () {
return check_type_load (new TestDel (missing_castclass));
}
public static int test_0_cpobj () {
return check_type_load (new TestDel (missing_cpobj));
}
public static int test_0_missing_type_on_parameter () {
return check_type_load (new TestDel (missing_external_type_reference_on_parameter));
}
public static int test_0_initobj () {
return check_type_load (new TestDel (missing_initobj));
}
public static int test_0_isinst () {
return check_type_load (new TestDel (missing_isinst));
}
public static int test_0_ldelem () {
// Thrown earlier
return 0;
}
public static int test_0_ldelema () {
// Thrown earlier
return 0;
}
public static int test_0_ldfld () {
return check_missing_field (new TestDel (missing_ldfld));
}
public static int test_0_ldflda () {
return check_missing_field (new TestDel (missing_ldflda));
}
public static int test_0_ldobj () {
// Thrown earlier
return 0;
}
public static int test_0_ldsfld () {
return check_missing_field (new TestDel (missing_ldsfld));
}
public static int test_0_ldsflda () {
return check_missing_field (new TestDel (missing_ldsflda));
}
public static int test_0_ldtoken_type () {
return check_type_load (new TestDel (missing_ldtoken_type));
}
public static int test_0_ldtoken_method () {
return check_missing_method (new TestDel (missing_ldtoken_method));
}
public static int test_0_ldtoken_field () {
return check_missing_field (new TestDel (missing_ldtoken_field));
}
public static int test_0_ldvirtftn () {
return check_missing_method (new TestDel (missing_ldvirtftn));
}
public static int test_0_mkrefany () {
// Thrown earlier
return 0;
}
public static int test_0_newarr () {
return check_type_load (new TestDel (missing_newarr));
}
public static int test_0_newobj () {
return check_missing_method (new TestDel (missing_newobj));
}
public static int test_0_refanyval () {
return check_type_load (new TestDel (missing_refanyval));
}
public static int test_0_sizeof () {
return check_type_load (new TestDel (missing_sizeof));
}
public static int test_0_stelem () {
// Thrown earlier
return 0;
}
public static int test_0_stfld () {
return check_missing_field (new TestDel (missing_stfld));
}
public static int test_0_stobj () {
// Thrown earlier
return 0;
}
public static int test_0_stsfld () {
return check_missing_field (new TestDel (missing_stsfld));
}
public static int test_0_unbox () {
return check_type_load (new TestDel (missing_unbox));
}
public static int test_0_unbox_any () {
return check_type_load (new TestDel (missing_unbox_any));
}
#if false
// Bummer: we regressed! I should have put this before
public static int test_0_missing_assembly_in_fieldref () {
return check_file_not_found (new TestDel (missing_assembly_in_fieldref));
}
#endif
// FIXME: the corrent exception here is FileNotFoundException
public static int test_0_missing_assembly_in_call () {
return check_type_load (new TestDel (missing_assembly_in_call));
}
public static int test_0_missing_assembly_in_newobj () {
return check_type_load (new TestDel (missing_assembly_in_newobj));
}
public static int test_0_missing_delegate_ctor_argument () {
return check_type_load (new TestDel (missing_delegate_ctor_argument));
}
//
// Missing classes referenced from metadata
//
public static int test_0_missing_local () {
try {
missing_local ();
}
catch (TypeLoadException ex) {
}
/* MS.NET doesn't throw an exception if a local is not found */
return 0;
}
//Regression test for #508532
public static int test_0_assembly_throws_on_loader_error ()
{
try {
Assembly asm = Assembly.Load ("load-missing");
asm.GetType ("BrokenClass", false);
return 1;
} catch (TypeLoadException) {}
return 0;
}
public static int test_0_bad_method_override1 ()
{
try {
BadOverridesDriver.bad_override1 ();
return 1;
} catch (TypeLoadException) {}
return 0;
}
public static int test_0_bad_method_override2 ()
{
try {
BadOverridesDriver.bad_override2 ();
return 1;
} catch (TypeLoadException) {}
return 0;
}
public static int test_0_bad_method_override3 ()
{
try {
BadOverridesDriver.bad_override3 ();
return 1;
} catch (TypeLoadException) {}
return 0;
}
public static int test_0_bad_method_override4 ()
{
try {
BadOverridesDriver.bad_override4 ();
return 1;
} catch (TypeLoadException) {}
return 0;
}
public static void missing_outer () {
new Missing.Foo1.InnerFoo ();
}
//Regression test for #508487
public static int test_0_missing_outer_type_in_typeref () {
return check_type_load (new TestDel (missing_outer));
}
// #524498
public static int test_0_exception_while_jitting_cctor () {
try {
CCtorClass.foo ();
} catch (TypeInitializationException) {
return 0;
}
return 1;
}
#if FALSE
public static void missing_parent () {
new Miss1 ();
}
public static int test_0_missing_parent () {
return check_type_load (new TestDel (missing_parent));
}
#endif
public static int test_0_missing_nested () {
if (typeof (Miss2).GetNestedTypes ().Length != 0)
return 1;
return 0;
}
public static int test_0_reflection_on_field_with_missing_type () {
var t = typeof (BadOverridesDriver).Assembly.GetType ("FieldWithMissingType");
foreach (var f in t.GetFields (BindingFlags.Public | BindingFlags.Static)) {
try {
Console.WriteLine (f.Name);
f.GetValue (null);
return 1;
} catch (TypeLoadException) {
return 0;
}
}
return 2;
}
public static int Main () {
return TestDriver.RunTests (typeof (Tests));
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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 EventStore.Core.Helpers;
using EventStore.Core.Messaging;
using EventStore.Core.Services.TimerService;
using EventStore.Core.Services.UserManagement;
using EventStore.Core.Tests.Fakes;
using EventStore.Projections.Core.Messages;
using EventStore.Projections.Core.Services;
using EventStore.Projections.Core.Services.Processing;
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.Services.core_projection
{
[TestFixture]
public class when_creating_a_projection
{
[SetUp]
public void Setup()
{
var fakePublisher = new FakePublisher();
_ioDispatcher = new IODispatcher(fakePublisher, new PublishEnvelope(fakePublisher));
_subscriptionDispatcher =
new ReaderSubscriptionDispatcher(new FakePublisher());
}
private readonly ProjectionConfig _defaultProjectionConfig = new ProjectionConfig(
null, 5, 10, 1000, 250, true, true, true, true, false);
private IODispatcher _ioDispatcher;
private
ReaderSubscriptionDispatcher
_subscriptionDispatcher;
[Test, ExpectedException(typeof (ArgumentException))]
public void a_checkpoint_threshold_less_tan_checkpoint_handled_threshold_throws_argument_out_of_range_exception(
)
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
var projectionConfig = new ProjectionConfig(null, 10, 5, 1000, 250, true, true, false, false, false);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, projectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof (ArgumentOutOfRangeException))]
public void a_negative_checkpoint_handled_interval_throws_argument_out_of_range_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
var projectionConfig = new ProjectionConfig(null, -1, 10, 1000, 250, true, true, false, false, false);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, projectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof (ArgumentNullException))]
public void a_null_io_dispatcher__throws_argument_null_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), null,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof (ArgumentNullException))]
public void a_null_name_throws_argument_null_excveption()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
null, version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof (ArgumentNullException))]
public void a_null_publisher_throws_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, null, _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof(ArgumentNullException))]
public void a_null_input_queue_throws_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), null, SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test]
public void a_null_run_as_does_not_throw_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), null, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof(ArgumentNullException))]
public void a_null_subscription_dispatcher__throws_argument_null_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
null, new RealTimeProvider());
}
[Test, ExpectedException(typeof (ArgumentNullException))]
public void a_null_time_provider__throws_argument_null_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, null);
}
[Test, ExpectedException(typeof (ArgumentOutOfRangeException))]
public void a_zero_checkpoint_handled_threshold_throws_argument_out_of_range_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
var projectionConfig = new ProjectionConfig(null, 0, 10, 1000, 250, true, true, false, false, false);
new ContinuousProjectionProcessingStrategy(
"projection", version, projectionStateHandler, projectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
[Test, ExpectedException(typeof (ArgumentException))]
public void an_empty_name_throws_argument_exception()
{
IProjectionStateHandler projectionStateHandler = new FakeProjectionStateHandler();
var version = new ProjectionVersion(1, 0, 0);
new ContinuousProjectionProcessingStrategy(
"", version, projectionStateHandler, _defaultProjectionConfig,
projectionStateHandler.GetSourceDefinition(), null, _subscriptionDispatcher).Create(
Guid.NewGuid(), new FakePublisher(), SystemAccount.Principal, new FakePublisher(), _ioDispatcher,
_subscriptionDispatcher, new RealTimeProvider());
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Repl;
namespace Microsoft.PythonTools {
/// <summary>
/// Exposes language specific options for Python via automation. This object
/// can be fetched using Dte.GetObject("VsPython").
/// </summary>
[ComVisible(true)]
public sealed class PythonAutomation : IVsPython, IPythonOptions3, IPythonIntellisenseOptions {
private readonly IServiceProvider _serviceProvider;
private readonly PythonToolsService _pyService;
private AutomationInteractiveOptions _interactiveOptions;
internal PythonAutomation(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
_pyService = serviceProvider.GetPythonToolsService();
Debug.Assert(_pyService != null, "Did not find PythonToolsService");
}
#region IPythonOptions Members
IPythonIntellisenseOptions IPythonOptions.Intellisense {
get { return this; }
}
IPythonInteractiveOptions IPythonOptions.Interactive {
get {
if (_interactiveOptions == null) {
_interactiveOptions = new AutomationInteractiveOptions(_serviceProvider);
}
return _interactiveOptions;
}
}
bool IPythonOptions.PromptBeforeRunningWithBuildErrorSetting {
get {
return _pyService.DebuggerOptions.PromptBeforeRunningWithBuildError;
}
set {
_pyService.DebuggerOptions.PromptBeforeRunningWithBuildError = value;
_pyService.DebuggerOptions.Save();
}
}
Severity IPythonOptions.IndentationInconsistencySeverity {
get {
return _pyService.GeneralOptions.IndentationInconsistencySeverity;
}
set {
_pyService.GeneralOptions.IndentationInconsistencySeverity = value;
_pyService.GeneralOptions.Save();
}
}
bool IPythonOptions.AutoAnalyzeStandardLibrary {
get {
return _pyService.GeneralOptions.AutoAnalyzeStandardLibrary;
}
set {
_pyService.GeneralOptions.AutoAnalyzeStandardLibrary = value;
_pyService.GeneralOptions.Save();
}
}
bool IPythonOptions.TeeStandardOutput {
get {
return _pyService.DebuggerOptions.TeeStandardOutput;
}
set {
_pyService.DebuggerOptions.TeeStandardOutput = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions.WaitOnAbnormalExit {
get {
return _pyService.DebuggerOptions.WaitOnAbnormalExit;
}
set {
_pyService.DebuggerOptions.WaitOnAbnormalExit = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions.WaitOnNormalExit {
get {
return _pyService.DebuggerOptions.WaitOnNormalExit;
}
set {
_pyService.DebuggerOptions.WaitOnNormalExit = value;
_pyService.DebuggerOptions.Save();
}
}
public bool UseLegacyDebugger {
get {
return _pyService.DebuggerOptions.UseLegacyDebugger;
}
set {
_pyService.DebuggerOptions.UseLegacyDebugger = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions3.PromptForEnvCreate {
get {
return _pyService.GeneralOptions.PromptForEnvCreate;
}
set {
_pyService.GeneralOptions.PromptForEnvCreate = value;
_pyService.GeneralOptions.Save();
}
}
bool IPythonOptions3.PromptForPackageInstallation {
get {
return _pyService.GeneralOptions.PromptForPackageInstallation;
}
set {
_pyService.GeneralOptions.PromptForPackageInstallation = value;
_pyService.GeneralOptions.Save();
}
}
#endregion
#region IPythonIntellisenseOptions Members
bool IPythonIntellisenseOptions.AddNewLineAtEndOfFullyTypedWord {
get {
return _pyService.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord;
}
set {
_pyService.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord = value;
_pyService.AdvancedOptions.Save();
}
}
bool IPythonIntellisenseOptions.EnterCommitsCompletion {
get {
return _pyService.AdvancedOptions.EnterCommitsIntellisense;
}
set {
_pyService.AdvancedOptions.EnterCommitsIntellisense = value;
_pyService.AdvancedOptions.Save();
}
}
bool IPythonIntellisenseOptions.UseMemberIntersection {
get {
return _pyService.AdvancedOptions.IntersectMembers;
}
set {
_pyService.AdvancedOptions.IntersectMembers = value;
_pyService.AdvancedOptions.Save();
}
}
string IPythonIntellisenseOptions.CompletionCommittedBy {
get {
return _pyService.AdvancedOptions.CompletionCommittedBy;
}
set {
_pyService.AdvancedOptions.CompletionCommittedBy = value;
_pyService.AdvancedOptions.Save();
}
}
bool IPythonIntellisenseOptions.AutoListIdentifiers {
get {
return _pyService.AdvancedOptions.AutoListIdentifiers;
}
set {
_pyService.AdvancedOptions.AutoListIdentifiers = value;
_pyService.AdvancedOptions.Save();
}
}
#endregion
void IVsPython.OpenInteractive(string description) {
var compModel = _pyService.ComponentModel;
if (compModel == null) {
throw new InvalidOperationException("Could not activate component model");
}
var provider = compModel.GetService<InteractiveWindowProvider>();
var interpreters = compModel.GetService<IInterpreterRegistryService>();
var factory = interpreters.Configurations
.Where(PythonInterpreterFactoryExtensions.IsRunnable)
.FirstOrDefault(f => f.Description.Equals(description, StringComparison.CurrentCultureIgnoreCase));
if (factory == null) {
throw new KeyNotFoundException("Could not create interactive window with name: " + description);
}
var window = provider.OpenOrCreate(
PythonReplEvaluatorProvider.GetEvaluatorId(factory)
);
if (window == null) {
throw new InvalidOperationException("Could not create interactive window");
}
window.Show(true);
}
}
[ComVisible(true)]
public sealed class AutomationInteractiveOptions : IPythonInteractiveOptions {
private readonly IServiceProvider _serviceProvider;
public AutomationInteractiveOptions(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
internal PythonInteractiveOptions CurrentOptions {
get {
return _serviceProvider.GetPythonToolsService().InteractiveOptions;
}
}
private void SaveSettingsToStorage() {
CurrentOptions.Save();
}
bool IPythonInteractiveOptions.UseSmartHistory {
get {
return CurrentOptions.UseSmartHistory;
}
set {
CurrentOptions.UseSmartHistory = value;
SaveSettingsToStorage();
}
}
string IPythonInteractiveOptions.CompletionMode {
get {
return CurrentOptions.CompletionMode.ToString();
}
set {
ReplIntellisenseMode mode;
if (Enum.TryParse(value, out mode)) {
CurrentOptions.CompletionMode = mode;
SaveSettingsToStorage();
} else {
throw new InvalidOperationException(
String.Format(
"Bad intellisense mode, must be one of: {0}",
String.Join(", ", Enum.GetNames(typeof(ReplIntellisenseMode)))
)
);
}
}
}
string IPythonInteractiveOptions.StartupScripts {
get {
return CurrentOptions.Scripts;
}
set {
CurrentOptions.Scripts = value;
SaveSettingsToStorage();
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Dialog.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.UI
{
using System.Globalization;
using Microsoft.Build.Framework;
using MSBuild.ExtensionPack.UI.Extended;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Confirm</i> (<b>Required: </b>Text <b>Optional: </b>Title, Height, Width, ConfirmText, ErrorText, ErrorTitle, Button1Text, Button2Text, MaskText <b>Output: </b>ButtonClickedText, UserText)</para>
/// <para><i>Show</i> (<b>Required: </b>Text <b>Optional: </b>Title, Height, Width, Button1Text, Button2Text, Button3Text, MessageColour, MessageBold <b>Output: </b>ButtonClickedText)</para>
/// <para><i>Prompt</i> (<b>Required: </b>Text <b>Optional: </b>Title, Height, Width, Button1Text, Button2Text, Button3Text, MessageColour, MessageBold, MaskText <b>Output: </b>ButtonClickedText, UserText)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Confirm a Password -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Confirm" Title="Confirmation Required" Button2Text="Cancel" Text="Enter Password" ConfirmText="Confirm Password" MaskText="true">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// <Output TaskParameter="UserText" PropertyName="Typed"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <Message Text="User Typed: $(Typed)"/>
/// <!-- A simple message -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Show" Text="Hello MSBuild">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <!-- A longer message with a few more attributes set -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Show" Title="A Longer Message" MessageBold="True" Button2Text="Cancel" MessageColour="Green" Height="300" Width="600" Text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras vitae velit. Pellentesque malesuada diam eget sem. Praesent vestibulum. Donec egestas, quam at viverra volutpat, eros nulla gravida nisi, sed bibendum metus mauris ut diam. Aliquam interdum lacus nec quam. Etiam porta, elit sed pretium vestibulum, nisi dui condimentum enim, ut rhoncus ipsum leo nec est. Nullam congue velit id ligula. Sed imperdiet bibendum pede. In hac habitasse platea dictumst. Praesent eleifend, elit quis convallis aliquam, mi arcu feugiat sem, at blandit mauris nisi eget mauris.">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <!-- A simple prompt for input -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Prompt" Title="Information Required" Button2Text="Cancel" Text="Please enter your Name below">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// <Output TaskParameter="UserText" PropertyName="Typed"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <Message Text="User Typed: $(Typed)"/>
/// <!-- A prompt for password input -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Prompt" Title="Sensitive Information Required" Button2Text="Cancel" Text="Please enter your Password below" MessageColour="Red" MaskText="true">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// <Output TaskParameter="UserText" PropertyName="Typed"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <Message Text="User Typed: $(Typed)"/>
/// </Target >
/// </Project>
/// ]]></code>
/// </example>
public class Dialog : BaseTask
{
private const string ShowTaskAction = "Show";
private const string PromptTaskAction = "Prompt";
private const string ConfirmTaskAction = "Confirm";
private string title = "Message";
private int height = 180;
private int width = 400;
private string button1Text = "OK";
private string errorTitle = "Error";
private string errorText = "The supplied values do not match";
private string confirmText = "Confirm";
/// <summary>
/// Sets the height of the form. Default is 180
/// </summary>
public int Height
{
get { return this.height; }
set { this.height = value; }
}
/// <summary>
/// Sets the width of the form. Default is 400
/// </summary>
public int Width
{
get { return this.width; }
set { this.width = value; }
}
/// <summary>
/// Sets the text for Button1. Default is 'Ok'
/// </summary>
public string Button1Text
{
get { return this.button1Text; }
set { this.button1Text = value; }
}
/// <summary>
/// Sets the text for Button2. If no text is set the button will not be displayed
/// </summary>
public string Button2Text { get; set; }
/// <summary>
/// Set the text for Button3. If no text is set the button will not be displayed
/// </summary>
public string Button3Text { get; set; }
/// <summary>
/// Sets the text for the message that is displayed
/// </summary>
[Required]
public string Text { get; set; }
/// <summary>
/// Sets the title for the error messagebox if Confirm fails. Default is 'Error'
/// </summary>
public string ErrorTitle
{
get { return this.errorTitle; }
set { this.errorTitle = value; }
}
/// <summary>
/// Sets the text for the error messagebox if Confirm fails. Default is 'The supplied values do not match'
/// </summary>
public string ErrorText
{
get { return this.errorText; }
set { this.errorText = value; }
}
/// <summary>
/// Sets the confirmation text for the message that is displayed. Default is 'Confirm'
/// </summary>
public string ConfirmText
{
get { return this.confirmText; }
set { this.confirmText = value; }
}
/// <summary>
/// Sets the Title of the Dialog. Default is 'Message' for Show and Prompt, 'Confirm' for Confirm TaskAction
/// </summary>
public string Title
{
get { return this.title; }
set { this.title = value; }
}
/// <summary>
/// Sets the message text colour. Default is ControlText (usually black).
/// </summary>
public string MessageColour { get; set; }
/// <summary>
/// Sets whether the message text is bold. Default is false.
/// </summary>
public bool MessageBold { get; set; }
/// <summary>
/// Set to true to use the default password character to mask the user input
/// </summary>
public bool MaskText { get; set; }
/// <summary>
/// Gets the text of the button that the user clicked
/// </summary>
[Output]
public string ButtonClickedText { get; set; }
/// <summary>
/// Gets the text that the user typed into the Prompt
/// </summary>
[Output]
public string UserText { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
switch (this.TaskAction)
{
case ShowTaskAction:
this.Show();
break;
case PromptTaskAction:
this.Prompt();
break;
case ConfirmTaskAction:
this.Confirm();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Show()
{
using (MessageForm form = new MessageForm(this.Text, this.MessageColour, this.MessageBold, this.Button1Text, this.Button2Text, this.Button3Text))
{
form.Width = this.Width;
form.Height = this.Height;
form.Text = this.Title;
form.ShowDialog();
this.ButtonClickedText = form.ButtonClickedText;
}
}
private void Prompt()
{
using (PromptForm form = new PromptForm(this.Text, this.MessageColour, this.MessageBold, this.Button1Text, this.Button2Text, this.Button3Text, this.MaskText))
{
form.Width = this.Width;
form.Height = this.Height;
form.Text = this.Title;
form.ShowDialog();
this.ButtonClickedText = form.ButtonClickedText;
this.UserText = form.UserText;
}
}
private void Confirm()
{
using (ConfirmForm form = new ConfirmForm(this.Text, this.ConfirmText, this.ErrorTitle, this.ErrorText, this.Button1Text, this.Button2Text, this.MaskText))
{
form.Width = this.Width;
form.Height = this.Height;
form.Text = this.Title;
form.ShowDialog();
this.ButtonClickedText = form.ButtonClickedText;
this.UserText = form.UserText;
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || PORTABLE40)
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonContract _rootContract;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootContract = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
if (_serializeStack.IndexOf(value) != -1)
{
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
#endif
#if NETFX_CORE || PORTABLE
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
return false;
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = 0; i < values.GetLength(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
return writeMetadataObject;
}
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35)
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
#if !(NET35 || NET20 || PORTABLE40)
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
continue;
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return false;
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
return false;
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
{
if (contract.UnderlyingType != _rootContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
if (contract.KeyContract == null)
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if !NET20
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
writer.WriteNull();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
return isSpecified;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System;
using System.Activities.DynamicUpdate;
using System.Activities.Expressions;
using System.Activities.Hosting;
using System.Activities.Runtime;
using System.Activities.Validation;
using System.Activities.XamlIntegration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime;
using System.Threading;
using System.Windows.Markup;
using System.Xaml;
[ContentProperty("Implementation")]
public abstract class Activity
{
const string generatedArgumentPrefix = "Argument";
static int nextCacheId;
static readonly IList<Activity> emptyChildren = new List<Activity>(0);
static readonly IList<Variable> emptyVariables = new List<Variable>(0);
static readonly IList<RuntimeArgument> emptyArguments = new List<RuntimeArgument>(0);
static readonly IList<ActivityDelegate> emptyDelegates = new List<ActivityDelegate>(0);
internal static readonly ReadOnlyCollection<Constraint> EmptyConstraints = new ReadOnlyCollection<Constraint>(new Constraint[0]);
string displayName;
bool isDisplayNameSet;
int id;
RootProperties rootProperties;
IList<RuntimeArgument> arguments;
IList<Activity> children;
IList<Activity> implementationChildren;
IList<Activity> importedChildren;
IList<ActivityDelegate> delegates;
IList<ActivityDelegate> implementationDelegates;
IList<ActivityDelegate> importedDelegates;
IList<Variable> variables;
IList<Variable> implementationVariables;
IList<ValidationError> tempValidationErrors;
IList<RuntimeArgument> tempAutoGeneratedArguments;
Collection<Constraint> constraints;
Activity runtimeImplementation;
Activity rootActivity;
object thisLock;
QualifiedId qualifiedId;
// For a given cacheId this tells us whether we've called InternalCacheMetadata yet or not
CacheStates isMetadataCached;
int cacheId;
RelationshipType relationshipToParent;
Nullable<bool> isSubtreeEmpty;
int symbolCount;
// alternatives are extended through DynamicActivity, CodeActivity, and NativeActivity
protected Activity()
{
this.thisLock = new object();
}
[TypeConverter(typeof(ImplementationVersionConverter))]
[DefaultValue(null)]
protected virtual internal Version ImplementationVersion
{
get;
set;
}
[XamlDeferLoad(typeof(FuncDeferringLoader), typeof(Activity))]
[DefaultValue(null)]
[Browsable(false)]
[Ambient]
protected virtual Func<Activity> Implementation
{
get;
set;
}
protected Collection<Constraint> Constraints
{
get
{
if (this.constraints == null)
{
this.constraints = new Collection<Constraint>();
}
return this.constraints;
}
}
protected internal int CacheId
{
get
{
return this.cacheId;
}
}
internal RelationshipType RelationshipToParent
{
get
{
return this.relationshipToParent;
}
}
internal bool HasNonEmptySubtree
{
get
{
if (this.isSubtreeEmpty.HasValue)
{
return !this.isSubtreeEmpty.Value;
}
else
{
if (this.Children.Count > 0 || this.ImplementationChildren.Count > 0 || this.ImportedChildren.Count > 0 ||
this.Delegates.Count > 0 || this.ImplementationDelegates.Count > 0 || this.ImportedDelegates.Count > 0 ||
this.RuntimeVariables.Count > 0 || this.ImplementationVariables.Count > 0 ||
this.RuntimeArguments.Count > 0)
{
this.isSubtreeEmpty = false;
}
else
{
this.isSubtreeEmpty = true;
}
return !this.isSubtreeEmpty.Value;
}
}
}
internal int SymbolCount
{
get
{
return this.symbolCount;
}
}
internal IdSpace MemberOf
{
get;
set;
}
internal IdSpace ParentOf
{
get;
set;
}
internal QualifiedId QualifiedId
{
get
{
if (this.qualifiedId == null)
{
this.qualifiedId = new QualifiedId(this);
}
return this.qualifiedId;
}
}
// This flag governs special behavior that we need to keep for back-compat on activities
// that implemented TryGetValue in 4.0.
internal bool UseOldFastPath
{
get;
set;
}
internal bool SkipArgumentResolution
{
get;
set;
}
internal bool IsFastPath
{
get
{
return this.SkipArgumentResolution && IsActivityWithResult;
}
}
internal virtual bool IsActivityWithResult
{
get
{
return false;
}
}
internal object Origin
{
get;
set;
}
public string DisplayName
{
get
{
if (!this.isDisplayNameSet && string.IsNullOrEmpty(this.displayName))
{
this.displayName = ActivityUtilities.GetDisplayName(this);
}
return this.displayName;
}
set
{
if (value == null)
{
this.displayName = string.Empty;
}
else
{
this.displayName = value;
}
this.isDisplayNameSet = true;
}
}
public string Id
{
get
{
if (this.id == 0)
{
return null;
}
else
{
return this.QualifiedId.ToString();
}
}
}
internal bool IsExpressionRoot
{
get
{
return this.relationshipToParent == RelationshipType.ArgumentExpression;
}
}
internal bool HasStartedCachingMetadata
{
get
{
return this.isMetadataCached != CacheStates.Uncached;
}
}
internal bool IsMetadataCached
{
get
{
return this.isMetadataCached != CacheStates.Uncached;
}
}
internal bool IsMetadataFullyCached
{
get
{
return (this.isMetadataCached & CacheStates.Full) == CacheStates.Full;
}
}
internal bool IsRuntimeReady
{
get
{
return (this.isMetadataCached & CacheStates.RuntimeReady) == CacheStates.RuntimeReady;
}
}
internal Activity RootActivity
{
get
{
return this.rootActivity;
}
}
internal int InternalId
{
get
{
return this.id;
}
set
{
Fx.Assert(value != 0, "0 is an invalid ID");
ClearIdInfo();
this.id = value;
}
}
internal ActivityDelegate HandlerOf
{
get;
private set;
}
internal Activity Parent
{
get;
private set;
}
internal LocationReferenceEnvironment HostEnvironment
{
get
{
if (this.RootActivity != null && this.RootActivity.rootProperties != null)
{
return this.RootActivity.rootProperties.HostEnvironment;
}
return null;
}
}
internal IList<RuntimeArgument> RuntimeArguments
{
get
{
return this.arguments;
}
}
internal IList<Activity> Children
{
get
{
return this.children;
}
}
internal IList<Activity> ImplementationChildren
{
get
{
return this.implementationChildren;
}
}
internal IList<Activity> ImportedChildren
{
get
{
return this.importedChildren;
}
}
internal IList<ActivityDelegate> Delegates
{
get
{
return this.delegates;
}
}
internal IList<ActivityDelegate> ImplementationDelegates
{
get
{
return this.implementationDelegates;
}
}
internal IList<ActivityDelegate> ImportedDelegates
{
get
{
return this.importedDelegates;
}
}
internal bool HasBeenAssociatedWithAnInstance
{
get
{
if (this.rootProperties != null)
{
return this.rootProperties.HasBeenAssociatedWithAnInstance;
}
else if (this.IsMetadataCached && this.RootActivity != null && this.RootActivity.rootProperties != null)
{
return this.RootActivity.rootProperties.HasBeenAssociatedWithAnInstance;
}
else
{
return false;
}
}
set
{
Fx.Assert(this.rootProperties != null, "This should only be called on the root and we should already be cached.");
Fx.Assert(value, "We really only let you set this to true.");
this.rootProperties.HasBeenAssociatedWithAnInstance = value;
}
}
internal Dictionary<string, List<RuntimeArgument>> OverloadGroups
{
get
{
Fx.Assert(this.rootProperties != null || System.Diagnostics.Debugger.IsAttached, "This should only be called on the root.");
return this.rootProperties.OverloadGroups;
}
set
{
Fx.Assert(this.rootProperties != null, "This should only be called on the root.");
this.rootProperties.OverloadGroups = value;
}
}
internal List<RuntimeArgument> RequiredArgumentsNotInOverloadGroups
{
get
{
Fx.Assert(this.rootProperties != null || System.Diagnostics.Debugger.IsAttached, "This should only be called on the root.");
return this.rootProperties.RequiredArgumentsNotInOverloadGroups;
}
set
{
Fx.Assert(this.rootProperties != null, "This should only be called on the root.");
this.rootProperties.RequiredArgumentsNotInOverloadGroups = value;
}
}
internal ValidationHelper.OverloadGroupEquivalenceInfo EquivalenceInfo
{
get
{
Fx.Assert(this.rootProperties != null || System.Diagnostics.Debugger.IsAttached, "This should only be called on the root.");
return this.rootProperties.EquivalenceInfo;
}
set
{
Fx.Assert(this.rootProperties != null, "This should only be called on the root.");
this.rootProperties.EquivalenceInfo = value;
}
}
internal IList<Variable> RuntimeVariables
{
get
{
return this.variables;
}
}
internal IList<Variable> ImplementationVariables
{
get
{
return this.implementationVariables;
}
}
internal IList<Constraint> RuntimeConstraints
{
get
{
return InternalGetConstraints();
}
}
internal LocationReferenceEnvironment PublicEnvironment
{
get;
set;
}
internal LocationReferenceEnvironment ImplementationEnvironment
{
get;
set;
}
internal virtual bool InternalCanInduceIdle
{
get
{
return false;
}
}
internal bool HasTempViolations
{
get
{
return (this.tempValidationErrors != null && this.tempValidationErrors.Count > 0);
}
}
internal object ThisLock
{
get
{
return this.thisLock;
}
}
internal int RequiredExtensionTypesCount
{
get
{
Fx.Assert(this.rootProperties != null || System.Diagnostics.Debugger.IsAttached, "only callable on the root");
return this.rootProperties.RequiredExtensionTypesCount;
}
}
internal int DefaultExtensionsCount
{
get
{
Fx.Assert(this.rootProperties != null || System.Diagnostics.Debugger.IsAttached, "only callable on the root");
return this.rootProperties.DefaultExtensionsCount;
}
}
internal bool GetActivityExtensionInformation(out Dictionary<Type, WorkflowInstanceExtensionProvider> activityExtensionProviders, out HashSet<Type> requiredActivityExtensionTypes)
{
Fx.Assert(this.rootProperties != null, "only callable on the root");
return this.rootProperties.GetActivityExtensionInformation(out activityExtensionProviders, out requiredActivityExtensionTypes);
}
internal virtual bool IsResultArgument(RuntimeArgument argument)
{
return false;
}
internal bool CanBeScheduledBy(Activity parent)
{
// fast path if we're the sole (or first) child
if (object.ReferenceEquals(parent, this.Parent))
{
return this.relationshipToParent == RelationshipType.ImplementationChild || this.relationshipToParent == RelationshipType.Child;
}
else
{
return parent.Children.Contains(this) || parent.ImplementationChildren.Contains(this);
}
}
internal void ClearIdInfo()
{
if (this.ParentOf != null)
{
this.ParentOf.Dispose();
this.ParentOf = null;
}
this.id = 0;
this.qualifiedId = null;
}
// We use these Set methods rather than a setter on the property since
// we don't want to make it seem like setting these collections is the
// "normal" thing to do. Only OnInternalCacheMetadata implementations
// should call these methods.
internal void SetChildrenCollection(Collection<Activity> children)
{
this.children = children;
}
internal void AddChild(Activity child)
{
if (this.children == null)
{
this.children = new Collection<Activity>();
}
this.children.Add(child);
}
internal void SetImplementationChildrenCollection(Collection<Activity> implementationChildren)
{
this.implementationChildren = implementationChildren;
}
internal void AddImplementationChild(Activity implementationChild)
{
if (this.implementationChildren == null)
{
this.implementationChildren = new Collection<Activity>();
}
this.implementationChildren.Add(implementationChild);
}
internal void SetImportedChildrenCollection(Collection<Activity> importedChildren)
{
this.importedChildren = importedChildren;
}
internal void AddImportedChild(Activity importedChild)
{
if (this.importedChildren == null)
{
this.importedChildren = new Collection<Activity>();
}
this.importedChildren.Add(importedChild);
}
internal void SetDelegatesCollection(Collection<ActivityDelegate> delegates)
{
this.delegates = delegates;
}
internal void AddDelegate(ActivityDelegate activityDelegate)
{
if (this.delegates == null)
{
this.delegates = new Collection<ActivityDelegate>();
}
this.delegates.Add(activityDelegate);
}
internal void SetImplementationDelegatesCollection(Collection<ActivityDelegate> implementationDelegates)
{
this.implementationDelegates = implementationDelegates;
}
internal void AddImplementationDelegate(ActivityDelegate implementationDelegate)
{
if (this.implementationDelegates == null)
{
this.implementationDelegates = new Collection<ActivityDelegate>();
}
this.implementationDelegates.Add(implementationDelegate);
}
internal void SetImportedDelegatesCollection(Collection<ActivityDelegate> importedDelegates)
{
this.importedDelegates = importedDelegates;
}
internal void AddImportedDelegate(ActivityDelegate importedDelegate)
{
if (this.importedDelegates == null)
{
this.importedDelegates = new Collection<ActivityDelegate>();
}
this.importedDelegates.Add(importedDelegate);
}
internal void SetVariablesCollection(Collection<Variable> variables)
{
this.variables = variables;
}
internal void AddVariable(Variable variable)
{
if (this.variables == null)
{
this.variables = new Collection<Variable>();
}
this.variables.Add(variable);
}
internal void SetImplementationVariablesCollection(Collection<Variable> implementationVariables)
{
this.implementationVariables = implementationVariables;
}
internal void AddImplementationVariable(Variable implementationVariable)
{
if (this.implementationVariables == null)
{
this.implementationVariables = new Collection<Variable>();
}
this.implementationVariables.Add(implementationVariable);
}
internal void SetArgumentsCollection(Collection<RuntimeArgument> arguments, bool createEmptyBindings)
{
this.arguments = arguments;
// Arguments should always be "as bound as possible"
if (this.arguments != null && this.arguments.Count > 0)
{
for (int i = 0; i < this.arguments.Count; i++)
{
RuntimeArgument argument = this.arguments[i];
argument.SetupBinding(this, createEmptyBindings);
}
this.arguments.QuickSort(RuntimeArgument.EvaluationOrderComparer);
}
}
internal void AddArgument(RuntimeArgument argument, bool createEmptyBindings)
{
if (this.arguments == null)
{
this.arguments = new Collection<RuntimeArgument>();
}
argument.SetupBinding(this, createEmptyBindings);
int insertionIndex = this.arguments.BinarySearch(argument, RuntimeArgument.EvaluationOrderComparer);
if (insertionIndex < 0)
{
this.arguments.Insert(~insertionIndex, argument);
}
else
{
this.arguments.Insert(insertionIndex, argument);
}
}
internal void SetTempValidationErrorCollection(IList<ValidationError> validationErrors)
{
this.tempValidationErrors = validationErrors;
}
internal void TransferTempValidationErrors(ref IList<ValidationError> newList)
{
if (this.tempValidationErrors != null)
{
for (int i = 0; i < this.tempValidationErrors.Count; i++)
{
ActivityUtilities.Add(ref newList, this.tempValidationErrors[i]);
}
}
this.tempValidationErrors = null;
}
internal void AddTempValidationError(ValidationError validationError)
{
if (this.tempValidationErrors == null)
{
this.tempValidationErrors = new Collection<ValidationError>();
}
this.tempValidationErrors.Add(validationError);
}
internal RuntimeArgument AddTempAutoGeneratedArgument(Type argumentType, ArgumentDirection direction)
{
if (this.tempAutoGeneratedArguments == null)
{
this.tempAutoGeneratedArguments = new Collection<RuntimeArgument>();
}
string name = generatedArgumentPrefix + this.tempAutoGeneratedArguments.Count.ToString(CultureInfo.InvariantCulture);
RuntimeArgument argument = new RuntimeArgument(name, argumentType, direction);
this.tempAutoGeneratedArguments.Add(argument);
return argument;
}
internal void ResetTempAutoGeneratedArguments()
{
this.tempAutoGeneratedArguments = null;
}
internal virtual IList<Constraint> InternalGetConstraints()
{
if (this.constraints != null && this.constraints.Count > 0)
{
return this.constraints;
}
else
{
return Activity.EmptyConstraints;
}
}
internal static bool NullCheck<T>(T obj)
{
return (obj == null);
}
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{0}: {1}", this.Id, this.DisplayName);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeDisplayName()
{
return this.isDisplayNameSet;
}
// subclasses are responsible for creating/disposing the necessary contexts
internal virtual void InternalAbort(ActivityInstance instance, ActivityExecutor executor, Exception terminationReason)
{
}
// subclasses are responsible for creating/disposing the necessary contexts
internal virtual void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
if (this.runtimeImplementation != null)
{
executor.ScheduleActivity(this.runtimeImplementation, instance, null, null, null);
}
}
// subclasses are responsible for creating/disposing the necessary contexts. This implementation
// covers Activity, Activity<T>, DynamicActivity, DynamicActivity<T>
internal virtual void InternalCancel(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
NativeActivityContext context = executor.NativeActivityContextPool.Acquire();
try
{
context.Initialize(instance, executor, bookmarkManager);
context.Cancel();
}
finally
{
context.Dispose();
executor.NativeActivityContextPool.Release(context);
}
}
internal bool IsSingletonActivityDeclared(string name)
{
if (this.rootActivity == null || this.rootActivity.rootProperties == null)
{
return false;
}
else
{
return this.rootActivity.rootProperties.IsSingletonActivityDeclared(name);
}
}
internal void DeclareSingletonActivity(string name, Activity activity)
{
if (this.rootActivity != null && this.rootActivity.rootProperties != null)
{
this.rootActivity.rootProperties.DeclareSingletonActivity(name, activity);
}
}
internal Activity GetSingletonActivity(string name)
{
if (this.rootActivity != null && this.rootActivity.rootProperties != null)
{
return this.rootActivity.rootProperties.GetSingletonActivity(name);
}
return null;
}
internal void ClearCachedInformation()
{
ClearCachedMetadata();
this.isMetadataCached = CacheStates.Uncached;
}
internal void InitializeAsRoot(LocationReferenceEnvironment hostEnvironment)
{
// We're being treated as the root of the workflow
this.Parent = null;
this.ParentOf = null;
Interlocked.CompareExchange(ref nextCacheId, 1, int.MaxValue);
this.cacheId = Interlocked.Increment(ref nextCacheId);
ClearCachedInformation();
this.MemberOf = new IdSpace();
this.rootProperties = new RootProperties();
this.rootProperties.HostEnvironment = hostEnvironment;
this.rootActivity = this;
}
internal LocationReferenceEnvironment GetParentEnvironment()
{
LocationReferenceEnvironment parentEnvironment = null;
if (this.Parent == null)
{
Fx.Assert(this.rootProperties != null, "Root properties must be available now.");
parentEnvironment = new ActivityLocationReferenceEnvironment(this.rootProperties.HostEnvironment) { InternalRoot = this };
}
else
{
switch (this.relationshipToParent)
{
case RelationshipType.ArgumentExpression:
parentEnvironment = this.Parent.PublicEnvironment.Parent;
if (parentEnvironment == null)
{
parentEnvironment = this.RootActivity.rootProperties.HostEnvironment;
}
break;
case RelationshipType.DelegateHandler:
Fx.Assert(this.HandlerOf != null, "Must have the parent delegate set");
parentEnvironment = this.HandlerOf.Environment;
break;
case RelationshipType.Child:
case RelationshipType.ImportedChild:
case RelationshipType.VariableDefault:
parentEnvironment = this.Parent.PublicEnvironment;
break;
case RelationshipType.ImplementationChild:
parentEnvironment = this.Parent.ImplementationEnvironment;
break;
}
}
return parentEnvironment;
}
internal bool InitializeRelationship(ActivityDelegate activityDelegate, ActivityCollectionType collectionType, ref IList<ValidationError> validationErrors)
{
if (this.cacheId == activityDelegate.Owner.CacheId)
{
// This means that we already have a parent and a delegate is trying to initialize
// a relationship. Delegate handlers MUST be declared.
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ActivityDelegateHandlersMustBeDeclarations(this.DisplayName, activityDelegate.Owner.DisplayName, this.Parent.DisplayName), false, activityDelegate.Owner));
return false;
}
if (InitializeRelationship(activityDelegate.Owner, collectionType != ActivityCollectionType.Implementation, RelationshipType.DelegateHandler, ref validationErrors))
{
this.HandlerOf = activityDelegate;
return true;
}
return false;
}
internal bool InitializeRelationship(RuntimeArgument argument, ref IList<ValidationError> validationErrors)
{
return InitializeRelationship(argument.Owner, true, RelationshipType.ArgumentExpression, ref validationErrors);
}
internal bool InitializeRelationship(Variable variable, bool isPublic, ref IList<ValidationError> validationErrors)
{
return InitializeRelationship(variable.Owner, isPublic, RelationshipType.VariableDefault, ref validationErrors);
}
internal bool InitializeRelationship(Activity parent, ActivityCollectionType collectionType, ref IList<ValidationError> validationErrors)
{
RelationshipType relationshipType = RelationshipType.Child;
if (collectionType == ActivityCollectionType.Imports)
{
relationshipType = RelationshipType.ImportedChild;
}
else if (collectionType == ActivityCollectionType.Implementation)
{
relationshipType = RelationshipType.ImplementationChild;
}
return InitializeRelationship(parent, collectionType != ActivityCollectionType.Implementation, relationshipType, ref validationErrors);
}
bool InitializeRelationship(Activity parent, bool isPublic, RelationshipType relationship, ref IList<ValidationError> validationErrors)
{
if (this.cacheId == parent.cacheId)
{
// This means that we've already encountered a parent in the tree
// Validate that it is visible.
// In order to see the activity the new parent must be
// in the implementation IdSpace of an activity which has
// a public reference to it.
Activity referenceTarget = parent.MemberOf.Owner;
if (object.ReferenceEquals(this, parent))
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ActivityCannotReferenceItself(this.DisplayName), parent));
return false;
}
else if (this.Parent == null)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.RootActivityCannotBeReferenced(this.DisplayName, parent.DisplayName), parent));
return false;
}
else if (referenceTarget == null)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ActivityCannotBeReferencedWithoutTarget(this.DisplayName, parent.DisplayName, this.Parent.DisplayName), parent));
return false;
}
else if (!referenceTarget.Children.Contains(this) && !referenceTarget.ImportedChildren.Contains(this))
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ActivityCannotBeReferenced(this.DisplayName, parent.DisplayName, referenceTarget.DisplayName, this.Parent.DisplayName), false, parent));
return false;
}
// This is a valid reference so we want to allow
// normal processing to proceed.
return true;
}
this.Parent = parent;
this.HandlerOf = null;
this.rootActivity = parent.RootActivity;
this.cacheId = parent.cacheId;
this.isMetadataCached = CacheStates.Uncached;
ClearCachedMetadata();
this.relationshipToParent = relationship;
if (isPublic)
{
this.MemberOf = parent.MemberOf;
}
else
{
if (parent.ParentOf == null)
{
parent.ParentOf = new IdSpace(parent.MemberOf, parent.InternalId);
}
this.MemberOf = parent.ParentOf;
}
return true;
}
void ClearCachedMetadata()
{
this.symbolCount = 0;
this.arguments = null;
this.children = null;
this.implementationChildren = null;
this.importedChildren = null;
this.delegates = null;
this.implementationDelegates = null;
this.importedDelegates = null;
this.variables = null;
this.implementationVariables = null;
}
internal void InternalCacheMetadata(bool createEmptyBindings, ref IList<ValidationError> validationErrors)
{
OnInternalCacheMetadata(createEmptyBindings);
if (this.tempAutoGeneratedArguments != null)
{
Fx.Assert(this.tempAutoGeneratedArguments.Count > 0, "We should only have a non-null value here if we generated an argument");
if (!this.SkipArgumentResolution)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(
SR.PublicReferencesOnActivityRequiringArgumentResolution(this.DisplayName), false, this));
}
if (this.arguments == null)
{
this.arguments = this.tempAutoGeneratedArguments;
}
else
{
for (int i = 0; i < this.tempAutoGeneratedArguments.Count; i++)
{
this.arguments.Add(this.tempAutoGeneratedArguments[i]);
}
}
this.tempAutoGeneratedArguments = null;
}
if (this.arguments != null && this.arguments.Count > 1)
{
ActivityValidationServices.ValidateEvaluationOrder(this.arguments, this, ref this.tempValidationErrors);
}
if (this.tempValidationErrors != null)
{
if (validationErrors == null)
{
validationErrors = new List<ValidationError>();
}
for (int i = 0; i < this.tempValidationErrors.Count; i++)
{
ValidationError validationError = this.tempValidationErrors[i];
validationError.Source = this;
validationError.Id = this.Id;
validationErrors.Add(validationError);
}
this.tempValidationErrors = null;
}
if (this.arguments == null)
{
this.arguments = emptyArguments;
}
else
{
this.symbolCount += this.arguments.Count;
}
if (this.variables == null)
{
this.variables = emptyVariables;
}
else
{
this.symbolCount += this.variables.Count;
}
if (this.implementationVariables == null)
{
this.implementationVariables = emptyVariables;
}
else
{
this.symbolCount += this.implementationVariables.Count;
}
if (this.children == null)
{
this.children = emptyChildren;
}
if (this.importedChildren == null)
{
this.importedChildren = emptyChildren;
}
if (this.implementationChildren == null)
{
this.implementationChildren = emptyChildren;
}
if (this.delegates == null)
{
this.delegates = emptyDelegates;
}
if (this.importedDelegates == null)
{
this.importedDelegates = emptyDelegates;
}
if (this.implementationDelegates == null)
{
this.implementationDelegates = emptyDelegates;
}
this.isMetadataCached = CacheStates.Partial;
}
// Note that this is relative to the type of walk we've done. If we
// skipped implementation then we can still be "Cached" even though
// we never ignored the implementation.
internal void SetCached(bool isSkippingPrivateChildren)
{
if (isSkippingPrivateChildren)
{
this.isMetadataCached = CacheStates.Partial;
}
else
{
this.isMetadataCached = CacheStates.Full;
}
}
internal void SetRuntimeReady()
{
this.isMetadataCached |= CacheStates.RuntimeReady;
}
internal virtual void OnInternalCacheMetadata(bool createEmptyBindings)
{
// By running CacheMetadata first we allow the user
// to set their Implementation during CacheMetadata.
ActivityMetadata metadata = new ActivityMetadata(this, GetParentEnvironment(), createEmptyBindings);
CacheMetadata(metadata);
metadata.Dispose();
if (this.Implementation != null)
{
this.runtimeImplementation = this.Implementation();
}
else
{
this.runtimeImplementation = null;
}
if (this.runtimeImplementation != null)
{
SetImplementationChildrenCollection(new Collection<Activity>
{
this.runtimeImplementation
});
}
}
protected virtual void CacheMetadata(ActivityMetadata metadata)
{
ReflectedInformation information = new ReflectedInformation(this);
SetImportedChildrenCollection(information.GetChildren());
SetVariablesCollection(information.GetVariables());
SetImportedDelegatesCollection(information.GetDelegates());
SetArgumentsCollection(information.GetArguments(), metadata.CreateEmptyBindings);
}
internal virtual void OnInternalCreateDynamicUpdateMap(DynamicUpdateMapBuilder.Finalizer finalizer,
DynamicUpdateMapBuilder.IDefinitionMatcher matcher, Activity originalActivity)
{
UpdateMapMetadata metadata = new UpdateMapMetadata(finalizer, matcher, this);
try
{
OnCreateDynamicUpdateMap(metadata, originalActivity);
}
finally
{
metadata.Dispose();
}
}
protected virtual void OnCreateDynamicUpdateMap(UpdateMapMetadata metadata, Activity originalActivity)
{
}
internal void AddDefaultExtensionProvider<T>(Func<T> extensionProvider)
where T : class
{
Fx.Assert(extensionProvider != null, "caller must verify");
Fx.Assert(this.rootActivity != null && this.rootActivity.rootProperties != null, "need a valid root");
this.rootActivity.rootProperties.AddDefaultExtensionProvider(extensionProvider);
}
internal void RequireExtension(Type extensionType)
{
Fx.Assert(extensionType != null && !extensionType.IsValueType, "caller should verify we have a valid reference type");
Fx.Assert(this.rootActivity != null && this.rootActivity.rootProperties != null, "need a valid root");
this.rootActivity.rootProperties.RequireExtension(extensionType);
}
// information used by root activities
class RootProperties
{
Dictionary<string, Activity> singletonActivityNames;
Dictionary<Type, WorkflowInstanceExtensionProvider> activityExtensionProviders;
HashSet<Type> requiredExtensionTypes;
public RootProperties()
{
}
public bool HasBeenAssociatedWithAnInstance
{
get;
set;
}
public LocationReferenceEnvironment HostEnvironment
{
get;
set;
}
public Dictionary<string, List<RuntimeArgument>> OverloadGroups
{
get;
set;
}
public List<RuntimeArgument> RequiredArgumentsNotInOverloadGroups
{
get;
set;
}
public ValidationHelper.OverloadGroupEquivalenceInfo EquivalenceInfo
{
get;
set;
}
public int DefaultExtensionsCount
{
get
{
if (this.activityExtensionProviders != null)
{
return this.activityExtensionProviders.Count;
}
else
{
return 0;
}
}
}
public int RequiredExtensionTypesCount
{
get
{
if (this.requiredExtensionTypes != null)
{
return this.requiredExtensionTypes.Count;
}
else
{
return 0;
}
}
}
public bool GetActivityExtensionInformation(out Dictionary<Type, WorkflowInstanceExtensionProvider> activityExtensionProviders, out HashSet<Type> requiredActivityExtensionTypes)
{
activityExtensionProviders = this.activityExtensionProviders;
requiredActivityExtensionTypes = this.requiredExtensionTypes;
return activityExtensionProviders != null || (requiredExtensionTypes != null && requiredExtensionTypes.Count > 0);
}
public void AddDefaultExtensionProvider<T>(Func<T> extensionProvider)
where T : class
{
Type key = typeof(T);
if (this.activityExtensionProviders == null)
{
this.activityExtensionProviders = new Dictionary<Type, WorkflowInstanceExtensionProvider>();
}
else
{
if (this.activityExtensionProviders.ContainsKey(key))
{
return; // already have a provider of this type
}
}
this.activityExtensionProviders.Add(key, new WorkflowInstanceExtensionProvider<T>(extensionProvider));
// if we're providing an extension that exactly matches a required type, simplify further bookkeeping
if (this.requiredExtensionTypes != null)
{
this.requiredExtensionTypes.Remove(key);
}
}
public void RequireExtension(Type extensionType)
{
// if we're providing an extension that exactly matches a required type, don't bother with further bookkeeping
if (this.activityExtensionProviders != null && this.activityExtensionProviders.ContainsKey(extensionType))
{
return;
}
if (this.requiredExtensionTypes == null)
{
this.requiredExtensionTypes = new HashSet<Type>();
}
this.requiredExtensionTypes.Add(extensionType);
}
public bool IsSingletonActivityDeclared(string name)
{
if (this.singletonActivityNames == null)
{
return false;
}
else
{
return this.singletonActivityNames.ContainsKey(name);
}
}
public void DeclareSingletonActivity(string name, Activity activity)
{
if (this.singletonActivityNames == null)
{
this.singletonActivityNames = new Dictionary<string, Activity>(1);
}
this.singletonActivityNames.Add(name, activity);
}
public Activity GetSingletonActivity(string name)
{
Activity result = null;
if (this.singletonActivityNames != null)
{
this.singletonActivityNames.TryGetValue(name, out result);
}
return result;
}
}
internal class ReflectedInformation
{
Activity parent;
Collection<RuntimeArgument> arguments;
Collection<Variable> variables;
Collection<Activity> children;
Collection<ActivityDelegate> delegates;
static Type DictionaryArgumentHelperType = typeof(DictionaryArgumentHelper<>);
static Type OverloadGroupAttributeType = typeof(OverloadGroupAttribute);
public ReflectedInformation(Activity owner)
: this(owner, ReflectedType.All)
{
}
ReflectedInformation(Activity activity, ReflectedType reflectType)
{
this.parent = activity;
// reflect over our activity and gather relevant pieces of the system so that the developer
// doesn't need to worry about "zipping up" his model to the constructs necessary for the
// runtime to function correctly
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(activity))
{
ArgumentDirection direction;
Type argumentType;
if ((reflectType & ReflectedType.Argument) == ReflectedType.Argument &&
ActivityUtilities.TryGetArgumentDirectionAndType(propertyDescriptor.PropertyType, out direction, out argumentType))
{
// We only do our magic for generic argument types. If the property is a non-generic
// argument type then that means the type of the RuntimeArgument should be based on
// the type of the argument bound to it. The activity author is responsible for dealing
// with these dynamic typing cases.
if (propertyDescriptor.PropertyType.IsGenericType)
{
bool isRequired = GetIsArgumentRequired(propertyDescriptor);
List<string> overloadGroupNames = GetOverloadGroupNames(propertyDescriptor);
RuntimeArgument argument = new RuntimeArgument(propertyDescriptor.Name, argumentType, direction, isRequired, overloadGroupNames, propertyDescriptor, activity);
Add<RuntimeArgument>(ref this.arguments, argument);
}
}
else if ((reflectType & ReflectedType.Variable) == ReflectedType.Variable &&
ActivityUtilities.IsVariableType(propertyDescriptor.PropertyType))
{
Variable variable = propertyDescriptor.GetValue(activity) as Variable;
if (variable != null)
{
Add<Variable>(ref this.variables, variable);
}
}
else if ((reflectType & ReflectedType.Child) == ReflectedType.Child &&
ActivityUtilities.IsActivityType(propertyDescriptor.PropertyType))
{
Activity workflowElement = propertyDescriptor.GetValue(activity) as Activity;
Add<Activity>(ref this.children, workflowElement);
}
else if ((reflectType & ReflectedType.ActivityDelegate) == ReflectedType.ActivityDelegate &&
ActivityUtilities.IsActivityDelegateType(propertyDescriptor.PropertyType))
{
ActivityDelegate activityDelegate = propertyDescriptor.GetValue(activity) as ActivityDelegate;
Add<ActivityDelegate>(ref this.delegates, activityDelegate);
}
else
{
Type innerType;
bool foundMatch = false;
if ((reflectType & ReflectedType.Argument) == ReflectedType.Argument)
{
object property = propertyDescriptor.GetValue(activity);
if (property != null)
{
IList<RuntimeArgument> runtimeArguments = DictionaryArgumentHelper.TryGetRuntimeArguments(property, propertyDescriptor.Name);
if (runtimeArguments != null)
{
this.AddCollection(ref this.arguments, runtimeArguments);
foundMatch = true;
}
else if (ActivityUtilities.IsArgumentDictionaryType(propertyDescriptor.PropertyType, out innerType))
{
Type concreteHelperType = DictionaryArgumentHelperType.MakeGenericType(innerType);
DictionaryArgumentHelper helper = Activator.CreateInstance(concreteHelperType, new object[] { property, propertyDescriptor.Name }) as DictionaryArgumentHelper;
this.AddCollection(ref this.arguments, helper.RuntimeArguments);
foundMatch = true;
}
}
}
if (!foundMatch && ActivityUtilities.IsKnownCollectionType(propertyDescriptor.PropertyType, out innerType))
{
if ((reflectType & ReflectedType.Variable) == ReflectedType.Variable &&
ActivityUtilities.IsVariableType(innerType))
{
IEnumerable enumerable = propertyDescriptor.GetValue(activity) as IEnumerable;
AddCollection(ref this.variables, enumerable);
}
else if ((reflectType & ReflectedType.Child) == ReflectedType.Child &&
ActivityUtilities.IsActivityType(innerType, false))
{
IEnumerable enumerable = propertyDescriptor.GetValue(activity) as IEnumerable;
AddCollection(ref this.children, enumerable);
}
else if ((reflectType & ReflectedType.ActivityDelegate) == ReflectedType.ActivityDelegate &&
ActivityUtilities.IsActivityDelegateType(innerType))
{
IEnumerable enumerable = propertyDescriptor.GetValue(activity) as IEnumerable;
AddCollection(ref this.delegates, enumerable);
}
}
}
}
}
public static Collection<RuntimeArgument> GetArguments(Activity parent)
{
Collection<RuntimeArgument> arguments = null;
if (parent != null)
{
arguments = new ReflectedInformation(parent, ReflectedType.Argument).GetArguments();
}
if (arguments == null)
{
arguments = new Collection<RuntimeArgument>();
}
return arguments;
}
public static Collection<Variable> GetVariables(Activity parent)
{
Collection<Variable> variables = null;
if (parent != null)
{
variables = new ReflectedInformation(parent, ReflectedType.Variable).GetVariables();
}
if (variables == null)
{
variables = new Collection<Variable>();
}
return variables;
}
public static Collection<Activity> GetChildren(Activity parent)
{
Collection<Activity> children = null;
if (parent != null)
{
children = new ReflectedInformation(parent, ReflectedType.Child).GetChildren();
}
if (children == null)
{
children = new Collection<Activity>();
}
return children;
}
public static Collection<ActivityDelegate> GetDelegates(Activity parent)
{
Collection<ActivityDelegate> delegates = null;
if (parent != null)
{
delegates = new ReflectedInformation(parent, ReflectedType.ActivityDelegate).GetDelegates();
}
if (delegates == null)
{
delegates = new Collection<ActivityDelegate>();
}
return delegates;
}
public Collection<RuntimeArgument> GetArguments()
{
return this.arguments;
}
public Collection<Variable> GetVariables()
{
return this.variables;
}
public Collection<Activity> GetChildren()
{
return this.children;
}
public Collection<ActivityDelegate> GetDelegates()
{
return this.delegates;
}
void AddCollection<T>(ref Collection<T> list, IEnumerable enumerable)
where T : class
{
if (enumerable != null)
{
foreach (object obj in enumerable)
{
if (obj != null && obj is T)
{
Add<T>(ref list, (T)obj);
}
}
}
}
void Add<T>(ref Collection<T> list, T data)
{
if (data != null)
{
if (list == null)
{
list = new Collection<T>();
}
list.Add(data);
}
}
bool GetIsArgumentRequired(PropertyDescriptor propertyDescriptor)
{
return propertyDescriptor.Attributes[typeof(RequiredArgumentAttribute)] != null;
}
List<string> GetOverloadGroupNames(PropertyDescriptor propertyDescriptor)
{
List<string> overloadGroupNames = new List<string>(0);
AttributeCollection propertyAttributes = propertyDescriptor.Attributes;
for (int i = 0; i < propertyAttributes.Count; i++)
{
Attribute attribute = propertyAttributes[i];
if (ReflectedInformation.OverloadGroupAttributeType.IsAssignableFrom(attribute.GetType()))
{
overloadGroupNames.Add(((OverloadGroupAttribute)attribute).GroupName);
}
}
return overloadGroupNames;
}
[Flags]
enum ReflectedType
{
Argument = 0X1,
Variable = 0X2,
Child = 0X4,
ActivityDelegate = 0X8,
All = 0XF
}
class DictionaryArgumentHelper
{
protected DictionaryArgumentHelper()
{
}
public IList<RuntimeArgument> RuntimeArguments
{
get;
protected set;
}
public static IList<RuntimeArgument> TryGetRuntimeArguments(object propertyValue, string propertyName)
{
// special case each of the non-generic argument types to avoid reflection costs
IEnumerable<KeyValuePair<string, Argument>> argumentEnumerable = propertyValue as IEnumerable<KeyValuePair<string, Argument>>;
if (argumentEnumerable != null)
{
return GetRuntimeArguments(argumentEnumerable, propertyName);
}
IEnumerable<KeyValuePair<string, InArgument>> inArgumentEnumerable = propertyValue as IEnumerable<KeyValuePair<string, InArgument>>;
if (inArgumentEnumerable != null)
{
return GetRuntimeArguments(inArgumentEnumerable, propertyName);
}
IEnumerable<KeyValuePair<string, OutArgument>> outArgumentEnumerable = propertyValue as IEnumerable<KeyValuePair<string, OutArgument>>;
if (outArgumentEnumerable != null)
{
return GetRuntimeArguments(outArgumentEnumerable, propertyName);
}
IEnumerable<KeyValuePair<string, InOutArgument>> inOutArgumentEnumerable = propertyValue as IEnumerable<KeyValuePair<string, InOutArgument>>;
if (inOutArgumentEnumerable != null)
{
return GetRuntimeArguments(inOutArgumentEnumerable, propertyName);
}
return null;
}
protected static IList<RuntimeArgument> GetRuntimeArguments<T>(IEnumerable<KeyValuePair<string, T>> argumentDictionary, string propertyName) where T : Argument
{
IList<RuntimeArgument> runtimeArguments = new List<RuntimeArgument>();
foreach (KeyValuePair<string, T> pair in argumentDictionary)
{
string key = pair.Key;
Argument value = pair.Value;
if (value == null)
{
string argName = (key == null) ? "<null>" : key;
throw FxTrace.Exception.AsError(new ValidationException(SR.MissingArgument(argName, propertyName)));
}
if (string.IsNullOrEmpty(key))
{
throw FxTrace.Exception.AsError(new ValidationException(SR.MissingNameProperty(value.ArgumentType)));
}
RuntimeArgument runtimeArgument = new RuntimeArgument(key, value.ArgumentType, value.Direction, false, null, value);
runtimeArguments.Add(runtimeArgument);
}
return runtimeArguments;
}
}
class DictionaryArgumentHelper<T> : DictionaryArgumentHelper where T : Argument
{
public DictionaryArgumentHelper(object propertyValue, string propertyName)
: base()
{
IEnumerable<KeyValuePair<string, T>> argumentDictionary = propertyValue as IEnumerable<KeyValuePair<string, T>>;
this.RuntimeArguments = GetRuntimeArguments(argumentDictionary, propertyName);
}
}
}
internal enum RelationshipType : byte
{
Child = 0x00,
ImportedChild = 0x01,
ImplementationChild = 0x02,
DelegateHandler = 0x03,
ArgumentExpression = 0x04,
VariableDefault = 0x05
}
enum CacheStates : byte
{
// We don't have valid cached data
Uncached = 0x00,
// The next two states are mutually exclusive:
// The activity has its own metadata cached, or private implementation are skipped
Partial = 0x01,
// The activity has its own metadata and its private implementation cached
// We can make use of the roll-up metadata (like
// SubtreeHasConstraints).
Full = 0x02,
// The next state can be ORed with the last two:
// The cached data is ready for runtime use
RuntimeReady = 0x04
}
}
[TypeConverter(typeof(ActivityWithResultConverter))]
[ValueSerializer(typeof(ActivityWithResultValueSerializer))]
public abstract class Activity<TResult> : ActivityWithResult
{
// alternatives are extended through DynamicActivity<TResult>, CodeActivity<TResult>, and NativeActivity<TResult>
protected Activity()
: base()
{
}
[DefaultValue(null)]
public new OutArgument<TResult> Result
{
get;
set;
}
internal override Type InternalResultType
{
get
{
return typeof(TResult);
}
}
internal override OutArgument ResultCore
{
get
{
return this.Result;
}
set
{
this.Result = value as OutArgument<TResult>;
if (this.Result == null && value != null)
{
throw FxTrace.Exception.Argument("value", SR.ResultArgumentMustBeSpecificType(typeof(TResult)));
}
}
}
public static implicit operator Activity<TResult>(TResult constValue)
{
return FromValue(constValue);
}
public static implicit operator Activity<TResult>(Variable variable)
{
return FromVariable(variable);
}
public static implicit operator Activity<TResult>(Variable<TResult> variable)
{
return FromVariable(variable);
}
public static Activity<TResult> FromValue(TResult constValue)
{
return new Literal<TResult> { Value = constValue };
}
public static Activity<TResult> FromVariable(Variable variable)
{
if (variable == null)
{
throw FxTrace.Exception.ArgumentNull("variable");
}
if (TypeHelper.AreTypesCompatible(variable.Type, typeof(TResult)))
{
return new VariableValue<TResult> { Variable = variable };
}
else
{
Type locationGenericType;
if (ActivityUtilities.IsLocationGenericType(typeof(TResult), out locationGenericType))
{
if (locationGenericType == variable.Type)
{
return (Activity<TResult>)ActivityUtilities.CreateVariableReference(variable);
}
}
}
throw FxTrace.Exception.Argument("variable", SR.ConvertVariableToValueExpressionFailed(variable.GetType().FullName, typeof(Activity<TResult>).FullName));
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.ConsiderPassingBaseTypesAsParameters,
Justification = "Generic needed for type inference")]
public static Activity<TResult> FromVariable(Variable<TResult> variable)
{
if (variable == null)
{
throw FxTrace.Exception.ArgumentNull("variable");
}
return new VariableValue<TResult>(variable);
}
internal override bool IsResultArgument(RuntimeArgument argument)
{
return object.ReferenceEquals(argument, this.ResultRuntimeArgument);
}
internal sealed override void OnInternalCacheMetadata(bool createEmptyBindings)
{
OnInternalCacheMetadataExceptResult(createEmptyBindings);
bool foundResult = false;
// This could be null at this point
IList<RuntimeArgument> runtimeArguments = this.RuntimeArguments;
int runtimeArgumentCount = 0;
if (runtimeArguments != null)
{
runtimeArgumentCount = runtimeArguments.Count;
for (int i = 0; i < runtimeArgumentCount; i++)
{
RuntimeArgument argument = runtimeArguments[i];
if (argument.Name == "Result")
{
foundResult = true;
if (argument.Type != typeof(TResult) || argument.Direction != ArgumentDirection.Out)
{
// The user supplied "Result" is incorrect so we
// log a violation.
AddTempValidationError(new ValidationError(SR.ResultArgumentHasRequiredTypeAndDirection(typeof(TResult), argument.Direction, argument.Type)));
}
else if (!IsBoundArgumentCorrect(argument, createEmptyBindings))
{
// The user supplied "Result" is not bound to the correct
// argument object.
AddTempValidationError(new ValidationError(SR.ResultArgumentMustBeBoundToResultProperty));
}
else
{
// The user supplied "Result" is correct so we
// cache it.
this.ResultRuntimeArgument = argument;
}
break;
}
}
}
if (!foundResult)
{
this.ResultRuntimeArgument = new RuntimeArgument("Result", typeof(TResult), ArgumentDirection.Out);
if (this.Result == null)
{
if (createEmptyBindings)
{
this.Result = new OutArgument<TResult>();
Argument.Bind(this.Result, this.ResultRuntimeArgument);
}
else
{
OutArgument<TResult> tempArgument = new OutArgument<TResult>();
Argument.Bind(tempArgument, this.ResultRuntimeArgument);
}
}
else
{
Argument.Bind(this.Result, this.ResultRuntimeArgument);
}
AddArgument(this.ResultRuntimeArgument, createEmptyBindings);
}
}
bool IsBoundArgumentCorrect(RuntimeArgument argument, bool createEmptyBindings)
{
if (createEmptyBindings)
{
// We must match if we've gone through
// RuntimeArgument.SetupBinding with
// createEmptyBindings == true.
return object.ReferenceEquals(argument.BoundArgument, this.Result);
}
else
{
// Otherwise, if the Result is null then
// SetupBinding has created a default
// BoundArgument which is fine. If it
// is non-null then it had better match.
return this.Result == null || object.ReferenceEquals(argument.BoundArgument, this.Result);
}
}
internal virtual void OnInternalCacheMetadataExceptResult(bool createEmptyBindings)
{
// default to Activity's behavior
base.OnInternalCacheMetadata(createEmptyBindings);
}
internal override object InternalExecuteInResolutionContextUntyped(CodeActivityContext resolutionContext)
{
return InternalExecuteInResolutionContext(resolutionContext);
}
internal virtual TResult InternalExecuteInResolutionContext(CodeActivityContext resolutionContext)
{
throw Fx.AssertAndThrow("This should only be called on CodeActivity<T>");
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Globalization;
using Common.Logging;
using Quartz.Impl.Matchers;
using Quartz.Spi;
namespace Quartz.Plugin.History
{
/// <summary>
/// Logs a history of all job executions (and execution vetos) via common
/// logging.
/// </summary>
/// <remarks>
/// <para>
/// The logged message is customizable by setting one of the following message
/// properties to a string that conforms to the syntax of <see cref="string.Format(string,object)"/>.
/// </para>
/// <para>
/// JobToBeFiredMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Triggers's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}"</i>
/// </para>
/// <para>
/// JobSuccessMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Triggers's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// <tr>
/// <td>8</td>
/// <td>Object</td>
/// <td>The string value (toString() having been called) of the result (if any)
/// that the Job set on the JobExecutionContext, with on it. "NULL" if no
/// result was set.</td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} execution complete at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}"</i>
/// </para>
/// <para>
/// JobFailedMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Triggers's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// <tr>
/// <td>8</td>
/// <td>String</td>
/// <td>The message from the thrown JobExecution Exception.
/// </td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} execution failed at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}"</i>
/// </para>
/// <para>
/// JobWasVetoedMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Triggers's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} was vetoed. It was to be fired
/// (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}"</i>
/// </para>
/// </remarks>
/// <author>Marko Lahma (.NET)</author>
public class LoggingJobHistoryPlugin : ISchedulerPlugin, IJobListener
{
private string name;
private string jobToBeFiredMessage = "Job {1}.{0} fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}";
private string jobSuccessMessage = "Job {1}.{0} execution complete at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}";
private string jobFailedMessage = "Job {1}.{0} execution failed at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}";
private string jobWasVetoedMessage =
"Job {1}.{0} was vetoed. It was to be fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}";
private ILog log = LogManager.GetLogger(typeof (LoggingJobHistoryPlugin));
/// <summary>
/// Logger instance to use. Defaults to common logging.
/// </summary>
public ILog Log
{
get { return log; }
set { log = value; }
}
/// <summary>
/// Get or sets the message that is logged when a Job successfully completes its
/// execution.
/// </summary>
public virtual string JobSuccessMessage
{
get { return jobSuccessMessage; }
set { jobSuccessMessage = value; }
}
/// <summary>
/// Get or sets the message that is logged when a Job fails its
/// execution.
/// </summary>
public virtual string JobFailedMessage
{
get { return jobFailedMessage; }
set { jobFailedMessage = value; }
}
/// <summary>
/// Gets or sets the message that is logged when a Job is about to Execute.
/// </summary>
public virtual string JobToBeFiredMessage
{
get { return jobToBeFiredMessage; }
set { jobToBeFiredMessage = value; }
}
/// <summary>
/// Gets or sets the message that is logged when a Job execution is vetoed by a
/// trigger listener.
/// </summary>
public virtual string JobWasVetoedMessage
{
get { return jobWasVetoedMessage; }
set { jobWasVetoedMessage = value; }
}
/// <summary>
/// Get the name of the <see cref="IJobListener" />.
/// </summary>
/// <value></value>
public virtual string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Called during creation of the <see cref="IScheduler" /> in order to give
/// the <see cref="ISchedulerPlugin" /> a chance to Initialize.
/// </summary>
public virtual void Initialize(string pluginName, IScheduler sched)
{
name = pluginName;
sched.ListenerManager.AddJobListener(this, EverythingMatcher<JobKey>.AllJobs());
}
/// <summary>
/// Called when the associated <see cref="IScheduler" /> is started, in order
/// to let the plug-in know it can now make calls into the scheduler if it
/// needs to.
/// </summary>
public virtual void Start()
{
// do nothing...
}
/// <summary>
/// Called in order to inform the <see cref="ISchedulerPlugin" /> that it
/// should free up all of it's resources because the scheduler is shutting
/// down.
/// </summary>
public virtual void Shutdown()
{
// nothing to do...
}
/// <summary>
/// Called by the <see cref="IScheduler"/> when a <see cref="IJobDetail"/> is
/// about to be executed (an associated <see cref="ITrigger"/> has occurred).
/// <para>
/// This method will not be invoked if the execution of the Job was vetoed by a
/// <see cref="ITriggerListener"/>.
/// </para>
/// </summary>
/// <seealso cref="JobExecutionVetoed(IJobExecutionContext)"/>
public virtual void JobToBeExecuted(IJobExecutionContext context)
{
if (!Log.IsInfoEnabled)
{
return;
}
ITrigger trigger = context.Trigger;
object[] args =
new object[]
{
context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount
};
Log.Info(String.Format(CultureInfo.InvariantCulture, JobToBeFiredMessage, args));
}
/// <summary>
/// Called by the <see cref="IScheduler" /> after a <see cref="IJobDetail" />
/// has been executed, and be for the associated <see cref="ITrigger" />'s
/// <see cref="IOperableTrigger.Triggered" /> method has been called.
/// </summary>
/// <param name="context"></param>
/// <param name="jobException"></param>
public virtual void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
{
ITrigger trigger = context.Trigger;
object[] args;
if (jobException != null)
{
if (!Log.IsWarnEnabled)
{
return;
}
string errMsg = jobException.Message;
args =
new object[]
{
context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, errMsg
};
Log.Warn(String.Format(CultureInfo.InvariantCulture, JobFailedMessage, args), jobException);
}
else
{
if (!Log.IsInfoEnabled)
{
return;
}
string result = Convert.ToString(context.Result, CultureInfo.InvariantCulture);
args =
new object[]
{
context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, result
};
Log.Info(String.Format(CultureInfo.InvariantCulture, JobSuccessMessage, args));
}
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="IJobDetail" />
/// was about to be executed (an associated <see cref="ITrigger" />
/// has occured), but a <see cref="ITriggerListener" /> vetoed it's
/// execution.
/// </summary>
/// <param name="context"></param>
/// <seealso cref="JobToBeExecuted(IJobExecutionContext)"/>
public virtual void JobExecutionVetoed(IJobExecutionContext context)
{
if (!Log.IsInfoEnabled)
{
return;
}
ITrigger trigger = context.Trigger;
object[] args =
new object[]
{
context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount
};
Log.Info(String.Format(CultureInfo.InvariantCulture, JobWasVetoedMessage, args));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Should;
using Xunit;
using System.Linq;
namespace AutoMapper.UnitTests
{
namespace ExpressionBridge
{
using QueryableExtensions;
public class SimpleProductDto
{
public string Name { set; get; }
public string ProductSubcategoryName { set; get; }
public string CategoryName { set; get; }
}
public class ExtendedProductDto
{
public string Name { set; get; }
public string ProductSubcategoryName { set; get; }
public string CategoryName { set; get; }
public List<BillOfMaterialsDto> BOM { set; get; }
}
public class ComplexProductDto
{
public string Name { get; set; }
public ProductSubcategoryDto ProductSubcategory { get; set; }
}
public class ProductSubcategoryDto
{
public string Name { get; set; }
public ProductCategoryDto ProductCategory { get; set; }
}
public class ProductCategoryDto
{
public string Name { get; set; }
}
public class AbstractProductDto
{
public string Name { set; get; }
public string ProductSubcategoryName { set; get; }
public string CategoryName { set; get; }
public List<ProductTypeDto> Types { get; set; }
}
public abstract class ProductTypeDto { }
public class ProdTypeA : ProductTypeDto {}
public class ProdTypeB : ProductTypeDto {}
public class ProductTypeConverter : TypeConverter<ProductType, ProductTypeDto>
{
protected override ProductTypeDto ConvertCore(ProductType source)
{
if (source.Name == "A")
return new ProdTypeA();
if (source.Name == "B")
return new ProdTypeB();
throw new ArgumentException();
}
}
public class ProductType
{
public string Name { get; set; }
}
public class BillOfMaterialsDto
{
public int BillOfMaterialsID { set; get; }
}
public class Product
{
public string Name { get; set; }
public ProductSubcategory ProductSubcategory { get; set; }
public List<BillOfMaterials> BillOfMaterials { set; get; }
public List<ProductType> Types { get; set; }
}
public class ProductSubcategory
{
public string Name { get; set; }
public ProductCategory ProductCategory { get; set; }
}
public class ProductCategory
{
public string Name { get; set; }
}
public class BillOfMaterials
{
public int BillOfMaterialsID { set; get; }
}
public class When_mapping_using_expressions : NonValidatingSpecBase
{
private List<Product> _products;
private Expression<Func<Product, SimpleProductDto>> _simpleProductConversionLinq;
private Expression<Func<Product, ExtendedProductDto>> _extendedProductConversionLinq;
private Expression<Func<Product, AbstractProductDto>> _abstractProductConversionLinq;
private List<SimpleProductDto> _simpleProducts;
private List<ExtendedProductDto> _extendedProducts;
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Product, SimpleProductDto>()
.ForMember(m => m.CategoryName, dst => dst.MapFrom(p => p.ProductSubcategory.ProductCategory.Name));
cfg.CreateMap<Product, ExtendedProductDto>()
.ForMember(m => m.CategoryName, dst => dst.MapFrom(p => p.ProductSubcategory.ProductCategory.Name))
.ForMember(m => m.BOM, dst => dst.MapFrom(p => p.BillOfMaterials));
cfg.CreateMap<BillOfMaterials, BillOfMaterialsDto>();
cfg.CreateMap<Product, ComplexProductDto>();
cfg.CreateMap<ProductSubcategory, ProductSubcategoryDto>();
cfg.CreateMap<ProductCategory, ProductCategoryDto>();
cfg.CreateMap<Product, AbstractProductDto>();
cfg.CreateMap<ProductType, ProductTypeDto>()
//.ConvertUsing(x => ProductTypeDto.GetProdType(x));
.ConvertUsing<ProductTypeConverter>();
});
_simpleProductConversionLinq = Mapper.Engine.CreateMapExpression<Product, SimpleProductDto>();
_extendedProductConversionLinq = Mapper.Engine.CreateMapExpression<Product, ExtendedProductDto>();
_abstractProductConversionLinq = Mapper.Engine.CreateMapExpression<Product, AbstractProductDto>();
_products = new List<Product>()
{
new Product
{
Name = "Foo",
ProductSubcategory = new ProductSubcategory
{
Name = "Bar",
ProductCategory = new ProductCategory
{
Name = "Baz"
}
},
BillOfMaterials = new List<BillOfMaterials>
{
new BillOfMaterials
{
BillOfMaterialsID = 5
}
}
,
Types = new List<ProductType>
{
new ProductType() { Name = "A" },
new ProductType() { Name = "B" },
new ProductType() { Name = "A" }
}
}
};
}
protected override void Because_of()
{
var queryable = _products.AsQueryable();
_simpleProducts = queryable.Select(_simpleProductConversionLinq).ToList();
_extendedProducts = queryable.Select(_extendedProductConversionLinq).ToList();
}
[Fact]
public void Should_map_and_flatten()
{
_simpleProducts.Count.ShouldEqual(1);
_simpleProducts[0].Name.ShouldEqual("Foo");
_simpleProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
_simpleProducts[0].CategoryName.ShouldEqual("Baz");
_extendedProducts.Count.ShouldEqual(1);
_extendedProducts[0].Name.ShouldEqual("Foo");
_extendedProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
_extendedProducts[0].CategoryName.ShouldEqual("Baz");
_extendedProducts[0].BOM.Count.ShouldEqual(1);
_extendedProducts[0].BOM[0].BillOfMaterialsID.ShouldEqual(5);
}
[Fact]
public void Should_use_extension_methods()
{
var queryable = _products.AsQueryable();
var simpleProducts = queryable.Project().To<SimpleProductDto>().ToList();
simpleProducts.Count.ShouldEqual(1);
simpleProducts[0].Name.ShouldEqual("Foo");
simpleProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
simpleProducts[0].CategoryName.ShouldEqual("Baz");
var extendedProducts = queryable.Project().To<ExtendedProductDto>().ToList();
extendedProducts.Count.ShouldEqual(1);
extendedProducts[0].Name.ShouldEqual("Foo");
extendedProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
extendedProducts[0].CategoryName.ShouldEqual("Baz");
extendedProducts[0].BOM.Count.ShouldEqual(1);
extendedProducts[0].BOM[0].BillOfMaterialsID.ShouldEqual(5);
var complexProducts = queryable.Project().To<ComplexProductDto>().ToList();
complexProducts.Count.ShouldEqual(1);
complexProducts[0].Name.ShouldEqual("Foo");
complexProducts[0].ProductSubcategory.Name.ShouldEqual("Bar");
complexProducts[0].ProductSubcategory.ProductCategory.Name.ShouldEqual("Baz");
}
#if !SILVERLIGHT
[Fact(Skip = "Won't work for normal query providers")]
public void List_of_abstract_should_be_mapped()
{
var mapped = Mapper.Map<AbstractProductDto>(_products[0]);
mapped.Types.Count.ShouldEqual(3);
var queryable = _products.AsQueryable();
var abstractProducts = queryable.Project().To<AbstractProductDto>().ToList();
abstractProducts[0].Types.Count.ShouldEqual(3);
abstractProducts[0].Types[0].GetType().ShouldEqual(typeof (ProdTypeA));
abstractProducts[0].Types[1].GetType().ShouldEqual(typeof (ProdTypeB));
abstractProducts[0].Types[2].GetType().ShouldEqual(typeof (ProdTypeA));
}
#endif
}
#if !NETFX_CORE && !SILVERLIGHT
namespace CircularReferences
{
public class A
{
public int AP1 { get; set; }
public string AP2 { get; set; }
public virtual B B { get; set; }
}
public class B
{
public B()
{
BP2 = new HashSet<A>();
}
public int BP1 { get; set; }
public virtual ICollection<A> BP2 { get; set; }
}
public class AEntity
{
public int AP1 { get; set; }
public string AP2 { get; set; }
public virtual BEntity B { get; set; }
}
public class BEntity
{
public BEntity()
{
BP2 = new HashSet<AEntity>();
}
public int BP1 { get; set; }
public virtual ICollection<AEntity> BP2 { get; set; }
}
public class C
{
public C Value { get; set; }
}
public class When_mapping_circular_references : AutoMapperSpecBase
{
private IQueryable<BEntity> _bei;
protected override void Establish_context()
{
Mapper.CreateMap<BEntity, B>().MaxDepth(3);
Mapper.CreateMap<AEntity, A>().MaxDepth(3);
}
protected override void Because_of()
{
var be = new BEntity();
be.BP1 = 3;
be.BP2.Add(new AEntity() { AP1 = 1, AP2 = "hello", B = be });
be.BP2.Add(new AEntity() { AP1 = 2, AP2 = "two", B = be });
var belist = new List<BEntity>();
belist.Add(be);
_bei = belist.AsQueryable();
}
[Fact]
public void Should_not_throw_exception()
{
typeof(StackOverflowException).ShouldNotBeThrownBy(() => _bei.Project().To<B>());
}
}
}
#endif
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Xml.Transform.Stream.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Javax.Xml.Transform.Stream
{
/// <summary>
/// <para>Acts as an holder for a transformation Source in the form of a stream of XML markup.</para><para><b>Note:</b> Due to their internal use of either a Reader or InputStream instance, <code>StreamSource</code> instances may only be used once.</para><para><para> </para><para></para><title>Revision:</title><para>829971 </para>, <title>Date:</title><para>2009-10-26 14:15:39 -0700 (Mon, 26 Oct 2009) </para></para>
/// </summary>
/// <java-name>
/// javax/xml/transform/stream/StreamSource
/// </java-name>
[Dot42.DexImport("javax/xml/transform/stream/StreamSource", AccessFlags = 33)]
public partial class StreamSource : global::Javax.Xml.Transform.ISource
/* scope: __dot42__ */
{
/// <summary>
/// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Source input of this type. </para>
/// </summary>
/// <java-name>
/// FEATURE
/// </java-name>
[Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)]
public const string FEATURE = "http://javax.xml.transform.stream.StreamSource/feature";
/// <summary>
/// <para>Zero-argument default constructor. If this constructor is used, and no Stream source is set using setInputStream(java.io.InputStream inputStream) or setReader(java.io.Reader reader), then the <code>Transformer</code> will create an empty source java.io.InputStream using new InputStream().</para><para><para>javax.xml.transform.Transformer::transform(Source xmlSource, Result outputTarget) </para></para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public StreamSource() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/InputStream;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.InputStream inputStream) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/io/InputStream;Ljava/lang/String;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.InputStream inputStream, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/Reader;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.Reader inputStream) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/io/Reader;Ljava/lang/String;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.Reader reader, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public StreamSource(string inputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/File;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.File inputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the byte stream to be used as input. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this Source object is used to process a stylesheet, normally setSystemId should also be called, so that relative URL references can be resolved.</para><para></para>
/// </summary>
/// <java-name>
/// setInputStream
/// </java-name>
[Dot42.DexImport("setInputStream", "(Ljava/io/InputStream;)V", AccessFlags = 1)]
public virtual void SetInputStream(global::Java.Io.InputStream inputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the byte stream that was set with setByteStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setByteStream, or null if setByteStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getInputStream
/// </java-name>
[Dot42.DexImport("getInputStream", "()Ljava/io/InputStream;", AccessFlags = 1)]
public virtual global::Java.Io.InputStream GetInputStream() /* MethodBuilder.Create */
{
return default(global::Java.Io.InputStream);
}
/// <summary>
/// <para>Set the input to be a character reader. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.</para><para></para>
/// </summary>
/// <java-name>
/// setReader
/// </java-name>
[Dot42.DexImport("setReader", "(Ljava/io/Reader;)V", AccessFlags = 1)]
public virtual void SetReader(global::Java.Io.Reader reader) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the character stream that was set with setReader.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setReader, or null if setReader or the Reader constructor was not called. </para>
/// </returns>
/// <java-name>
/// getReader
/// </java-name>
[Dot42.DexImport("getReader", "()Ljava/io/Reader;", AccessFlags = 1)]
public virtual global::Java.Io.Reader GetReader() /* MethodBuilder.Create */
{
return default(global::Java.Io.Reader);
}
/// <summary>
/// <para>Set the public identifier for this Source.</para><para>The public identifier is always optional: if the application writer includes one, it will be provided as part of the location information.</para><para></para>
/// </summary>
/// <java-name>
/// setPublicId
/// </java-name>
[Dot42.DexImport("setPublicId", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetPublicId(string publicId) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the public identifier that was set with setPublicId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The public identifier that was set with setPublicId, or null if setPublicId was not called. </para>
/// </returns>
/// <java-name>
/// getPublicId
/// </java-name>
[Dot42.DexImport("getPublicId", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPublicId() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Set the system ID from a File reference.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetSystemId(string f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetSystemId() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Set the system ID from a File reference.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/io/File;)V", AccessFlags = 1)]
public virtual void SetSystemId(global::Java.Io.File f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the byte stream that was set with setByteStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setByteStream, or null if setByteStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getInputStream
/// </java-name>
public global::Java.Io.InputStream InputStream
{
[Dot42.DexImport("getInputStream", "()Ljava/io/InputStream;", AccessFlags = 1)]
get{ return GetInputStream(); }
[Dot42.DexImport("setInputStream", "(Ljava/io/InputStream;)V", AccessFlags = 1)]
set{ SetInputStream(value); }
}
/// <summary>
/// <para>Get the character stream that was set with setReader.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setReader, or null if setReader or the Reader constructor was not called. </para>
/// </returns>
/// <java-name>
/// getReader
/// </java-name>
public global::Java.Io.Reader Reader
{
[Dot42.DexImport("getReader", "()Ljava/io/Reader;", AccessFlags = 1)]
get{ return GetReader(); }
[Dot42.DexImport("setReader", "(Ljava/io/Reader;)V", AccessFlags = 1)]
set{ SetReader(value); }
}
/// <summary>
/// <para>Get the public identifier that was set with setPublicId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The public identifier that was set with setPublicId, or null if setPublicId was not called. </para>
/// </returns>
/// <java-name>
/// getPublicId
/// </java-name>
public string PublicId
{
[Dot42.DexImport("getPublicId", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPublicId(); }
[Dot42.DexImport("setPublicId", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetPublicId(value); }
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
public string SystemId
{
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSystemId(); }
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetSystemId(value); }
}
}
/// <summary>
/// <para>Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// javax/xml/transform/stream/StreamResult
/// </java-name>
[Dot42.DexImport("javax/xml/transform/stream/StreamResult", AccessFlags = 33)]
public partial class StreamResult : global::Javax.Xml.Transform.IResult
/* scope: __dot42__ */
{
/// <summary>
/// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Result output of this type. </para>
/// </summary>
/// <java-name>
/// FEATURE
/// </java-name>
[Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)]
public const string FEATURE = "http://javax.xml.transform.stream.StreamResult/feature";
/// <summary>
/// <para>Zero-argument default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public StreamResult() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/OutputStream;)V", AccessFlags = 1)]
public StreamResult(global::Java.Io.OutputStream outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/Writer;)V", AccessFlags = 1)]
public StreamResult(global::Java.Io.Writer outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public StreamResult(string outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/File;)V", AccessFlags = 1)]
public StreamResult(global::Java.Io.File outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the ByteStream that is to be written to. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
/// <java-name>
/// setOutputStream
/// </java-name>
[Dot42.DexImport("setOutputStream", "(Ljava/io/OutputStream;)V", AccessFlags = 1)]
public virtual void SetOutputStream(global::Java.Io.OutputStream outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the byte stream that was set with setOutputStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setOutputStream, or null if setOutputStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getOutputStream
/// </java-name>
[Dot42.DexImport("getOutputStream", "()Ljava/io/OutputStream;", AccessFlags = 1)]
public virtual global::Java.Io.OutputStream GetOutputStream() /* MethodBuilder.Create */
{
return default(global::Java.Io.OutputStream);
}
/// <summary>
/// <para>Set the writer that is to receive the result. Normally, a stream should be used rather than a writer, so that the transformer may use instructions contained in the transformation instructions to control the encoding. However, there are times when it is useful to write to a writer, such as when using a StringWriter.</para><para></para>
/// </summary>
/// <java-name>
/// setWriter
/// </java-name>
[Dot42.DexImport("setWriter", "(Ljava/io/Writer;)V", AccessFlags = 1)]
public virtual void SetWriter(global::Java.Io.Writer writer) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the character stream that was set with setWriter.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setWriter, or null if setWriter or the Writer constructor was not called. </para>
/// </returns>
/// <java-name>
/// getWriter
/// </java-name>
[Dot42.DexImport("getWriter", "()Ljava/io/Writer;", AccessFlags = 1)]
public virtual global::Java.Io.Writer GetWriter() /* MethodBuilder.Create */
{
return default(global::Java.Io.Writer);
}
/// <summary>
/// <para>Set the system ID from a <code>File</code> reference.</para><para>Note the use of File#toURI() and File#toURL(). <code>toURI()</code> is preferred and used if possible. To allow JAXP 1.3 to run on J2SE 1.3, <code>toURL()</code> is used if a NoSuchMethodException is thrown by the attempt to use <code>toURI()</code>.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetSystemId(string f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the system ID from a <code>File</code> reference.</para><para>Note the use of File#toURI() and File#toURL(). <code>toURI()</code> is preferred and used if possible. To allow JAXP 1.3 to run on J2SE 1.3, <code>toURL()</code> is used if a NoSuchMethodException is thrown by the attempt to use <code>toURI()</code>.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/io/File;)V", AccessFlags = 1)]
public virtual void SetSystemId(global::Java.Io.File f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetSystemId() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Get the byte stream that was set with setOutputStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setOutputStream, or null if setOutputStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getOutputStream
/// </java-name>
public global::Java.Io.OutputStream OutputStream
{
[Dot42.DexImport("getOutputStream", "()Ljava/io/OutputStream;", AccessFlags = 1)]
get{ return GetOutputStream(); }
[Dot42.DexImport("setOutputStream", "(Ljava/io/OutputStream;)V", AccessFlags = 1)]
set{ SetOutputStream(value); }
}
/// <summary>
/// <para>Get the character stream that was set with setWriter.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setWriter, or null if setWriter or the Writer constructor was not called. </para>
/// </returns>
/// <java-name>
/// getWriter
/// </java-name>
public global::Java.Io.Writer Writer
{
[Dot42.DexImport("getWriter", "()Ljava/io/Writer;", AccessFlags = 1)]
get{ return GetWriter(); }
[Dot42.DexImport("setWriter", "(Ljava/io/Writer;)V", AccessFlags = 1)]
set{ SetWriter(value); }
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
public string SystemId
{
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSystemId(); }
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetSystemId(value); }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------
//------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Runtime.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using System.Collections;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Globalization;
using System.Reflection;
using System.Security;
public sealed class DataContractJsonSerializer
{
private const char BACK_SLASH = '\\';
private const char FORWARD_SLASH = '/';
private const char HIGH_SURROGATE_START = (char)0xd800;
private const char LOW_SURROGATE_END = (char)0xdfff;
private const char MAX_CHAR = (char)0xfffe;
private const char WHITESPACE = ' ';
private const char CARRIAGE_RETURN = '\r';
private const char NEWLINE = '\n';
internal IList<Type> knownTypeList;
internal DataContractDictionary knownDataContracts;
private EmitTypeInformation _emitTypeInformation;
private bool _ignoreExtensionDataObject;
private ReadOnlyCollection<Type> _knownTypeCollection;
private int _maxItemsInObjectGraph;
private DataContract _rootContract; // post-surrogate
private XmlDictionaryString _rootName;
private JavaScriptSerializer _jsonSerializer;
private JavaScriptDeserializer _jsonDeserializer;
private bool _rootNameRequiresMapping;
private Type _rootType;
private bool _serializeReadOnlyTypes;
private DateTimeFormat _dateTimeFormat;
private bool _useSimpleDictionaryFormat;
public DataContractJsonSerializer(Type type)
: this(type, (IEnumerable<Type>)null)
{
}
public DataContractJsonSerializer(Type type, IEnumerable<Type> knownTypes)
{
Initialize(type, knownTypes);
}
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings)
{
if (settings == null)
{
settings = new DataContractJsonSerializerSettings();
}
XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName);
Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject,
settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat);
}
public ReadOnlyCollection<Type> KnownTypes
{
get
{
if (_knownTypeCollection == null)
{
if (knownTypeList != null)
{
_knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList);
}
else
{
_knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>());
}
}
return _knownTypeCollection;
}
}
internal DataContractDictionary KnownDataContracts
{
get
{
if (this.knownDataContracts == null && this.knownTypeList != null)
{
// This assignment may be performed concurrently and thus is a race condition.
// It's safe, however, because at worse a new (and identical) dictionary of
// data contracts will be created and re-assigned to this field. Introduction
// of a lock here could lead to deadlocks.
this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList);
}
return this.knownDataContracts;
}
}
public int MaxItemsInObjectGraph
{
get { return _maxItemsInObjectGraph; }
}
internal bool AlwaysEmitTypeInformation
{
get
{
return _emitTypeInformation == EmitTypeInformation.Always;
}
}
public DateTimeFormat DateTimeFormat
{
get
{
return _dateTimeFormat;
}
}
public EmitTypeInformation EmitTypeInformation
{
get
{
return _emitTypeInformation;
}
}
public bool SerializeReadOnlyTypes
{
get
{
return _serializeReadOnlyTypes;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return _useSimpleDictionaryFormat;
}
}
private DataContract RootContract
{
get
{
if (_rootContract == null)
{
_rootContract = DataContract.GetDataContract(_rootType);
CheckIfTypeIsReference(_rootContract);
}
return _rootContract;
}
}
private void AddCollectionItemTypeToKnownTypes(Type knownType)
{
Type itemType;
Type typeToCheck = knownType;
while (CollectionDataContract.IsCollection(typeToCheck, out itemType))
{
if (itemType.GetTypeInfo().IsGenericType && (itemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
{
itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GetGenericArguments());
}
this.knownTypeList.Add(itemType);
typeToCheck = itemType;
}
}
private void Initialize(Type type,
IEnumerable<Type> knownTypes)
{
XmlObjectSerializer.CheckNull(type, "type");
_rootType = type;
if (knownTypes != null)
{
this.knownTypeList = new List<Type>();
foreach (Type knownType in knownTypes)
{
this.knownTypeList.Add(knownType);
if (knownType != null)
{
AddCollectionItemTypeToKnownTypes(knownType);
}
}
}
}
private void Initialize(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
EmitTypeInformation emitTypeInformation,
bool serializeReadOnlyTypes,
DateTimeFormat dateTimeFormat,
bool useSimpleDictionaryFormat)
{
CheckNull(type, "type");
_rootType = type;
if (knownTypes != null)
{
this.knownTypeList = new List<Type>();
foreach (Type knownType in knownTypes)
{
this.knownTypeList.Add(knownType);
if (knownType != null)
{
AddCollectionItemTypeToKnownTypes(knownType);
}
}
}
if (maxItemsInObjectGraph < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.Format(SR.ValueMustBeNonNegative)));
}
_maxItemsInObjectGraph = maxItemsInObjectGraph;
_ignoreExtensionDataObject = ignoreExtensionDataObject;
_emitTypeInformation = emitTypeInformation;
_serializeReadOnlyTypes = serializeReadOnlyTypes;
_dateTimeFormat = dateTimeFormat;
_useSimpleDictionaryFormat = useSimpleDictionaryFormat;
}
private void Initialize(Type type,
XmlDictionaryString rootName,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
EmitTypeInformation emitTypeInformation,
bool serializeReadOnlyTypes,
DateTimeFormat dateTimeFormat,
bool useSimpleDictionaryFormat)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat);
_rootName = ConvertXmlNameToJsonName(rootName);
_rootNameRequiresMapping = CheckIfJsonNameRequiresMapping(_rootName);
}
internal static void CheckIfTypeIsReference(DataContract dataContract)
{
if (dataContract.IsReference)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.Format(
SR.JsonUnsupportedForIsReference,
DataContract.GetClrTypeFullName(dataContract.UnderlyingType),
dataContract.IsReference)));
}
}
internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
{
DataContract contract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType);
CheckIfTypeIsReference(contract);
return contract;
}
public void WriteObject(Stream stream, object graph)
{
_jsonSerializer = new JavaScriptSerializer(stream);
DataContract contract = RootContract;
Type declaredType = contract.UnderlyingType;
Type graphType = (graph == null) ? declaredType : graph.GetType();
System.Runtime.Serialization.XmlWriterDelegator writer = null;
if (graph == null)
{
_jsonSerializer.SerializeObject(null);
}
else
{
if (declaredType == graphType)
{
if (contract.CanContainReferences)
{
XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, contract);
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
else
{
WriteObjectInternal(graph, contract, null, false, declaredType.TypeHandle);
}
}
else
{
XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract);
contract = DataContractSerializer.GetDataContract(contract, declaredType, graphType);
if (contract.CanContainReferences)
{
context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
}
else
{
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
}
}
}
internal void WriteObjectInternal(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle)
{
_jsonSerializer.SerializeObject(ConvertDataContractToObject(value, contract, context, writeServerType, declaredTypeHandle));
}
internal object ConvertDataContractToObject(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle)
{
if (context != null)
{
context.OnHandleReference(null /*XmlWriter*/, value, true); // canContainReferences
}
try
{
if (contract is ObjectDataContract)
{
Type valueType = value.GetType();
if (valueType != Globals.TypeOfObject)
return ConvertDataContractToObject(value, DataContract.GetDataContract(valueType), context, true, contract.UnderlyingType.TypeHandle);
else
return value;
}
else if (contract is TimeSpanDataContract)
{
return XmlConvert.ToString((TimeSpan)value);
}
else if (contract is QNameDataContract)
{
XmlQualifiedName qname = (XmlQualifiedName)value;
return (qname.IsEmpty) ? string.Empty : (qname.Name + ":" + qname.Namespace);
}
else if (contract is PrimitiveDataContract)
{
return value;
}
else if (contract is CollectionDataContract)
{
CollectionDataContract collectionContract = contract as CollectionDataContract;
switch (collectionContract.Kind)
{
case CollectionKind.GenericDictionary:
case CollectionKind.Dictionary:
return DataContractToObjectConverter.ConvertGenericDictionaryToArray(this, (IEnumerable)value, collectionContract, context, writeServerType);
default:
return DataContractToObjectConverter.ConvertGenericListToArray(this, (IEnumerable)value, collectionContract, context, writeServerType);
}
}
else if (contract is ClassDataContract)
{
ClassDataContract classContract = contract as ClassDataContract;
if (Globals.TypeOfScriptObject_IsAssignableFrom(classContract.UnderlyingType))
{
return ConvertScriptObjectToObject(value);
}
return DataContractToObjectConverter.ConvertClassDataContractToDictionary(this, (ClassDataContract)contract, value, context, writeServerType);
}
else if (contract is EnumDataContract)
{
if (((EnumDataContract)contract).IsULong)
return Convert.ToUInt64(value, null);
else
return Convert.ToInt64(value, null);
}
else if (contract is XmlDataContract)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList));
MemoryStream memoryStream = new MemoryStream();
dataContractSerializer.WriteObject(memoryStream, value);
memoryStream.Position = 0;
return new StreamReader(memoryStream, Encoding.UTF8).ReadToEnd();
}
}
finally
{
if (context != null)
{
context.OnEndHandleReference(null /*XmlWriter*/, value, true); // canContainReferences
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownDataContract, contract.Name)));
}
private object ConvertScriptObjectToObject(object value)
{
string jsonValue = Globals.ScriptObjectJsonSerialize(value);
using (MemoryStream jsonStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonValue)))
{
JavaScriptDeserializer jsDeserializer = new JavaScriptDeserializer(jsonStream);
return jsDeserializer.DeserializeObject();
}
}
public object ReadObject(Stream stream)
{
try
{
DataContract contract = RootContract;
AddCollectionItemContractsToKnownDataContracts(contract);
_jsonDeserializer = new JavaScriptDeserializer(stream);
XmlObjectSerializerReadContextComplexJson context = new XmlObjectSerializerReadContextComplexJson(this, RootContract);
object obj = ConvertObjectToDataContract(RootContract, _jsonDeserializer.DeserializeObject(), context);
return obj;
}
catch (Exception e)
{
if (e is TargetInvocationException || e is FormatException || e is OverflowException)
{
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.GetTypeInfoError(SR.ErrorDeserializing, _rootType, e), e);
}
throw;
}
}
private object ConvertObjectToPrimitiveDataContract(DataContract contract, object value, XmlObjectSerializerReadContextComplexJson context)
{
// Taking the right deserialized value for datetime string based on contract information
var tuple = value as Tuple<DateTime, string>;
if (tuple != null)
{
if (contract is StringDataContract || contract.UnderlyingType == typeof(object))
{
value = tuple.Item2;
}
else
{
value = tuple.Item1;
}
}
if (contract is TimeSpanDataContract)
{
return XmlConvert.ToTimeSpan(String.Format(CultureInfo.InvariantCulture, "{0}", value));
}
else if (contract is ByteArrayDataContract)
{
return ObjectToDataContractConverter.ConvertToArray(typeof(Byte), (IList)value);
}
else if (contract is GuidDataContract)
{
return new Guid(String.Format(CultureInfo.InvariantCulture, "{0}", value));
}
else if (contract is ObjectDataContract)
{
if (value is ICollection)
{
return ConvertObjectToDataContract(DataContract.GetDataContract(Globals.TypeOfObjectArray), value, context);
}
return TryParseJsonNumber(value);
}
else if (contract is QNameDataContract)
{
return XmlObjectSerializerReadContextComplexJson.ParseQualifiedName(value.ToString());
}
else if (contract is StringDataContract)
{
if (value is bool)
{
return ((bool)value) ? Globals.True : Globals.False;
}
return value.ToString();
}
else if (contract is UriDataContract)
{
return new Uri(value.ToString(), UriKind.RelativeOrAbsolute);
}
else if (contract is DoubleDataContract)
{
if (value is float)
{
return (double)(float)value;
}
if (value is double)
{
return (double)value;
}
return double.Parse(String.Format(CultureInfo.InvariantCulture, "{0}", value), NumberStyles.Float, CultureInfo.InvariantCulture);
}
else if (contract is DecimalDataContract)
{
return decimal.Parse(String.Format(CultureInfo.InvariantCulture, "{0}", value), NumberStyles.Float, CultureInfo.InvariantCulture);
}
return Convert.ChangeType(value, contract.UnderlyingType, CultureInfo.InvariantCulture);
}
internal object ConvertObjectToDataContract(DataContract contract, object value, XmlObjectSerializerReadContextComplexJson context)
{
if (value == null)
{
return value;
}
else if (contract is PrimitiveDataContract)
{
return ConvertObjectToPrimitiveDataContract(contract, value, context);
}
else if (contract is CollectionDataContract)
{
return ObjectToDataContractConverter.ConvertICollectionToCollectionDataContract(this, (CollectionDataContract)contract, value, context);
}
else if (contract is ClassDataContract)
{
ClassDataContract classContract = contract as ClassDataContract;
if (Globals.TypeOfScriptObject_IsAssignableFrom(classContract.UnderlyingType))
{
return ConvertObjectToScriptObject(value);
}
return ObjectToDataContractConverter.ConvertDictionaryToClassDataContract(this, classContract, (Dictionary<string, object>)value, context);
}
else if (contract is EnumDataContract)
{
return Enum.ToObject(contract.UnderlyingType, ((EnumDataContract)contract).IsULong ? ulong.Parse(String.Format(CultureInfo.InvariantCulture, "{0}", value), NumberStyles.Float, NumberFormatInfo.InvariantInfo) : value);
}
else if (contract is XmlDataContract)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(contract.UnderlyingType, GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes((string)value));
return dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(memoryStream, XmlDictionaryReaderQuotas.Max));
}
return value;
}
private object ConvertObjectToScriptObject(object deserialzedValue)
{
MemoryStream memStream = new MemoryStream();
JavaScriptSerializer jsSerializer = new JavaScriptSerializer(memStream);
jsSerializer.SerializeObject(deserialzedValue);
memStream.Flush();
memStream.Position = 0;
return Globals.ScriptObjectJsonDeserialize(new StreamReader(memStream).ReadToEnd());
}
private object TryParseJsonNumber(object value)
{
string input = value as string;
if (input != null && input.IndexOfAny(JsonGlobals.FloatingPointCharacters) >= 0)
{
return JavaScriptObjectDeserializer.ParseJsonNumberAsDoubleOrDecimal(input);
}
return value;
}
private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext context, IList<Type> serializerKnownTypeList)
{
List<Type> knownTypesList = new List<Type>();
if (context != null)
{
List<XmlQualifiedName> stableNames = new List<XmlQualifiedName>();
Dictionary<XmlQualifiedName, DataContract>[] entries = context.scopedKnownTypes.dataContractDictionaries;
if (entries != null)
{
for (int i = 0; i < entries.Length; i++)
{
Dictionary<XmlQualifiedName, DataContract> entry = entries[i];
if (entry != null)
{
foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in entry)
{
if (!stableNames.Contains(pair.Key))
{
stableNames.Add(pair.Key);
knownTypesList.Add(pair.Value.UnderlyingType);
}
}
}
}
}
if (serializerKnownTypeList != null)
{
knownTypesList.AddRange(serializerKnownTypeList);
}
}
return knownTypesList;
}
private void AddCollectionItemContractsToKnownDataContracts(DataContract traditionalDataContract)
{
if (traditionalDataContract.KnownDataContracts != null)
{
foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in traditionalDataContract.KnownDataContracts)
{
if (!object.ReferenceEquals(knownDataContract, null))
{
CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract;
while (collectionDataContract != null)
{
DataContract itemContract = collectionDataContract.ItemContract;
if (knownDataContracts == null)
{
knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
}
if (!knownDataContracts.ContainsKey(itemContract.StableName))
{
knownDataContracts.Add(itemContract.StableName, itemContract);
}
if (collectionDataContract.ItemType.GetTypeInfo().IsGenericType
&& collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
{
DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments()));
if (!knownDataContracts.ContainsKey(itemDataContract.StableName))
{
knownDataContracts.Add(itemDataContract.StableName, itemDataContract);
}
}
if (!(itemContract is CollectionDataContract))
{
break;
}
collectionDataContract = itemContract as CollectionDataContract;
}
}
}
}
}
static internal void InvokeOnSerializing(Object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context)
{
if (contract is ClassDataContract)
{
ClassDataContract classContract = contract as ClassDataContract;
if (classContract.BaseContract != null)
InvokeOnSerializing(value, classContract.BaseContract, context);
if (classContract.OnSerializing != null)
{
bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null, JsonGlobals.JsonSerializationPatterns);
try
{
classContract.OnSerializing.Invoke(value, new object[] { context.GetStreamingContext() });
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForWrite(securityException, JsonGlobals.JsonSerializationPatterns);
}
else
{
throw;
}
}
catch (TargetInvocationException targetInvocationException)
{
if (targetInvocationException.InnerException == null)
throw;
//We are catching the TIE here and throws the inner exception only,
//this is needed to have a consistent exception story in all serializers
throw targetInvocationException.InnerException;
}
}
}
}
static internal void InvokeOnSerialized(Object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context)
{
if (contract is ClassDataContract)
{
ClassDataContract classContract = contract as ClassDataContract;
if (classContract.BaseContract != null)
InvokeOnSerialized(value, classContract.BaseContract, context);
if (classContract.OnSerialized != null)
{
bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null, JsonGlobals.JsonSerializationPatterns);
try
{
classContract.OnSerialized.Invoke(value, new object[] { context.GetStreamingContext() });
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForWrite(securityException, JsonGlobals.JsonSerializationPatterns);
}
else
{
throw;
}
}
catch (TargetInvocationException targetInvocationException)
{
if (targetInvocationException.InnerException == null)
throw;
//We are catching the TIE here and throws the inner exception only,
//this is needed to have a consistent exception story in all serializers
throw targetInvocationException.InnerException;
}
}
}
}
static internal void InvokeOnDeserializing(Object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context)
{
if (contract is ClassDataContract)
{
ClassDataContract classContract = contract as ClassDataContract;
if (classContract.BaseContract != null)
InvokeOnDeserializing(value, classContract.BaseContract, context);
if (classContract.OnDeserializing != null)
{
bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null, JsonGlobals.JsonSerializationPatterns);
try
{
classContract.OnDeserializing.Invoke(value, new object[] { context.GetStreamingContext() });
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForRead(securityException, JsonGlobals.JsonSerializationPatterns);
}
else
{
throw;
}
}
catch (TargetInvocationException targetInvocationException)
{
if (targetInvocationException.InnerException == null)
throw;
//We are catching the TIE here and throws the inner exception only,
//this is needed to have a consistent exception story in all serializers
throw targetInvocationException.InnerException;
}
}
}
}
static internal void InvokeOnDeserialized(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context)
{
if (contract is ClassDataContract)
{
ClassDataContract classContract = contract as ClassDataContract;
if (classContract.BaseContract != null)
InvokeOnDeserialized(value, classContract.BaseContract, context);
if (classContract.OnDeserialized != null)
{
bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null, JsonGlobals.JsonSerializationPatterns);
try
{
classContract.OnDeserialized.Invoke(value, new object[] { context.GetStreamingContext() });
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForRead(securityException, JsonGlobals.JsonSerializationPatterns);
}
else
{
throw;
}
}
catch (TargetInvocationException targetInvocationException)
{
if (targetInvocationException.InnerException == null)
throw;
//We are catching the TIE here and throws the inner exception only,
//this is needed to have a consistent exception story in all serializers
throw targetInvocationException.InnerException;
}
}
}
}
internal static bool CharacterNeedsEscaping(char ch)
{
return (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar || ch < WHITESPACE || ch == BACK_SLASH
|| (ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR)));
}
internal static bool CheckIfJsonNameRequiresMapping(string jsonName)
{
if (jsonName != null)
{
if (!DataContract.IsValidNCName(jsonName))
{
return true;
}
for (int i = 0; i < jsonName.Length; i++)
{
if (CharacterNeedsEscaping(jsonName[i]))
{
return true;
}
}
}
return false;
}
internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName)
{
return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value);
}
internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract)
{
if (name == null)
return false;
if (contract.IsBuiltInDataContract || !contract.CanContainReferences)
return false;
string contractNs = XmlDictionaryString.GetString(contract.Namespace);
if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns))
return false;
return true;
}
internal static void CheckNull(object obj, string name)
{
if (obj == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(name));
}
internal static string ConvertXmlNameToJsonName(string xmlName)
{
return XmlConvert.DecodeName(xmlName);
}
internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName)
{
return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace InControl.iOS.Xcode
{
enum TokenType
{
EOF,
Invalid,
String,
QuotedString,
Comment,
Semicolon,
// ;
Comma,
// ,
Eq,
// =
LParen,
// (
RParen,
// )
LBrace,
// {
RBrace,
// }
}
class Token
{
public TokenType type;
// the line of the input stream the token starts in (0-based)
public int line;
// start and past-the-end positions of the token in the input stream
public int begin, end;
}
class TokenList : List<Token>
{
}
class Lexer
{
string text;
int pos;
int length;
int line;
public static TokenList Tokenize( string text )
{
var lexer = new Lexer();
lexer.SetText( text );
return lexer.ScanAll();
}
public void SetText( string text )
{
this.text = text + " "; // to prevent out-of-bounds access during look ahead
pos = 0;
length = text.Length;
line = 0;
}
public TokenList ScanAll()
{
var tokens = new TokenList();
while (true)
{
var tok = new Token();
ScanOne( tok );
tokens.Add( tok );
if (tok.type == TokenType.EOF)
break;
}
return tokens;
}
void UpdateNewlineStats( char ch )
{
if (ch == '\n')
line++;
}
// tokens list is modified in the case when we add BrokenLine token and need to remove already
// added tokens for the current line
void ScanOne( Token tok )
{
while (true)
{
while (pos < length && Char.IsWhiteSpace( text[pos] ))
{
UpdateNewlineStats( text[pos] );
pos++;
}
if (pos >= length)
{
tok.type = TokenType.EOF;
break;
}
char ch = text[pos];
char ch2 = text[pos + 1];
if (ch == '\"')
ScanQuotedString( tok );
else
if (ch == '/' && ch2 == '*')
ScanMultilineComment( tok );
else
if (ch == '/' && ch2 == '/')
ScanComment( tok );
else
if (IsOperator( ch ))
ScanOperator( tok );
else
ScanString( tok ); // be more robust and accept whatever is left
return;
}
}
void ScanString( Token tok )
{
tok.type = TokenType.String;
tok.begin = pos;
while (pos < length)
{
char ch = text[pos];
char ch2 = text[pos + 1];
if (Char.IsWhiteSpace( ch ))
break;
else
if (ch == '\"')
break;
else
if (ch == '/' && ch2 == '*')
break;
else
if (ch == '/' && ch2 == '/')
break;
else
if (IsOperator( ch ))
break;
pos++;
}
tok.end = pos;
tok.line = line;
}
void ScanQuotedString( Token tok )
{
tok.type = TokenType.QuotedString;
tok.begin = pos;
pos++;
while (pos < length)
{
// ignore escaped quotes
if (text[pos] == '\\' && text[pos + 1] == '\"')
{
pos += 2;
continue;
}
// note that we close unclosed quotes
if (text[pos] == '\"')
break;
UpdateNewlineStats( text[pos] );
pos++;
}
pos++;
tok.end = pos;
tok.line = line;
}
void ScanMultilineComment( Token tok )
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '*' && text[pos + 1] == '/')
break;
// we support multiline comments
UpdateNewlineStats( text[pos] );
pos++;
}
pos += 2;
tok.end = pos;
tok.line = line;
}
void ScanComment( Token tok )
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '\n')
break;
pos++;
}
UpdateNewlineStats( text[pos] );
pos++;
tok.end = pos;
tok.line = line;
}
bool IsOperator( char ch )
{
if (ch == ';' || ch == ',' || ch == '=' || ch == '(' || ch == ')' || ch == '{' || ch == '}')
return true;
return false;
}
void ScanOperator( Token tok )
{
switch (text[pos])
{
case ';':
ScanOperatorSpecific( tok, TokenType.Semicolon );
return;
case ',':
ScanOperatorSpecific( tok, TokenType.Comma );
return;
case '=':
ScanOperatorSpecific( tok, TokenType.Eq );
return;
case '(':
ScanOperatorSpecific( tok, TokenType.LParen );
return;
case ')':
ScanOperatorSpecific( tok, TokenType.RParen );
return;
case '{':
ScanOperatorSpecific( tok, TokenType.LBrace );
return;
case '}':
ScanOperatorSpecific( tok, TokenType.RBrace );
return;
default:
return;
}
}
void ScanOperatorSpecific( Token tok, TokenType type )
{
tok.type = type;
tok.begin = pos;
pos++;
tok.end = pos;
tok.line = line;
}
}
}
// namespace UnityEditor.iOS.Xcode
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using Belikov.Common.ThreadProcessing;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.Security;
namespace Belikov.GenuineChannels.TransportContext
{
/// <summary>
/// Keeps information regarding the specific host (not necessarily remote) and provides all the
/// necessary means for releasing this information after a connection to this host
/// is closed.
/// All properties and methods are thread-safe.
/// </summary>
public class HostInformation : MarshalByRefObject, ISetSecuritySession, ISessionSupport, ITransportContextProvider
{
/// <summary>
/// Constructs an instance of the HostInformation class.
/// Instances of the class HostInformation must be constructed only by objects implementing
/// the IKnownHosts interface.
/// </summary>
/// <param name="uriOrUrl">Uri or Url of the remote host.</param>
/// <param name="iTransportContext">Transport Context.</param>
internal HostInformation(string uriOrUrl, ITransportContext iTransportContext)
{
this._iTransportContext = iTransportContext;
if (uriOrUrl[0] == '_')
{
this._uri = uriOrUrl;
UriStorage.RegisterConnection(uriOrUrl, this.ITransportContext);
}
else
this._url = uriOrUrl;
}
/// <summary>
/// To guarantee atomic access to local members.
/// </summary>
private object _accessToLocalMembers = new object();
/// <summary>
/// Transport Context.
/// </summary>
public ITransportContext ITransportContext
{
get
{
return this._iTransportContext;
}
}
private ITransportContext _iTransportContext;
/// <summary>
/// Host's identifier.
/// </summary>
public string Uri
{
get
{
lock (this._uriLock)
return _uri;
}
}
private string _uri;
private object _uriLock = new object();
/// <summary>
/// The physical address of the remote host.
/// </summary>
public object PhysicalAddress
{
get
{
lock (this._accessToLocalMembers)
return this._physicalAddress;
}
set
{
lock (this._accessToLocalMembers)
this._physicalAddress = value;
}
}
private object _physicalAddress;
/// <summary>
/// Gets or sets an integer value that reflects the number of messages in the connection queue.
/// Please note that if you have several persistent and/or named connections leading to the same host, this
/// value will reflect the queue length of the last used connection.
/// </summary>
public int QueueLength
{
get
{
lock (this._accessToLocalMembers)
return this._queueLength;
}
set
{
lock (this._accessToLocalMembers)
this._queueLength = value;
}
}
private int _queueLength;
/// <summary>
/// Gets or sets a byte value indicating the protocol version supported by the remote host.
/// </summary>
public byte ProtocolVersion
{
get
{
lock (this._accessToLocalMembers)
return this._protocolVersion;
}
set
{
lock (this._accessToLocalMembers)
this._protocolVersion = value;
}
}
private byte _protocolVersion = MessageCoder.PROTOCOL_VERSION;
/// <summary>
/// The local end point being used to connect to the remote host.
/// Is set only by GTCP Connection Manager.
/// </summary>
public object LocalPhysicalAddress
{
get
{
lock (this._accessToLocalMembers)
return this._localPhysicalAddress;
}
set
{
lock (this._accessToLocalMembers)
this._localPhysicalAddress = value;
}
}
private object _localPhysicalAddress;
/// <summary>
/// Updates the value of the Uri member.
/// </summary>
/// <param name="uri">The uri of this host.</param>
/// <param name="remoteHostUniqueIdentifier">The unique identifier of the HostInformation used by the remote host.</param>
/// <returns>The exception explaining why the remote host has lost its state.</returns>
public Exception UpdateUri(string uri, int remoteHostUniqueIdentifier)
{
return this.UpdateUri(uri, remoteHostUniqueIdentifier, true);
}
/// <summary>
/// Updates the value of the Uri member.
/// </summary>
/// <param name="uri">The uri of this host.</param>
/// <param name="remoteHostUniqueIdentifier">The unique identifier of the HostInformation used by the remote host.</param>
/// <param name="checkHostInfoVersion">The boolean value that determines whether the host version should be checked.</param>
/// <returns>The exception explaining why the remote host has lost its state.</returns>
public Exception UpdateUri(string uri, int remoteHostUniqueIdentifier, bool checkHostInfoVersion)
{
Exception exception = null;
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
lock (this._uriLock)
{
if (this._uri != uri)
{
if (this._uri != null && this._uri != uri)
{
exception = GenuineExceptions.Get_Receive_ServerHasBeenRestared();
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
binaryLogWriter.WriteEvent(LogCategory.HostInformation, "HostInformation.UpdateUri",
LogMessageType.HostInformationUriUpdated, exception, null, this,
null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, this._uri, uri, null, null,
"The URI mismatch has been detected. The remote host has been restarted. Expected uri: \"{0}\". Provided uri: \"{1}\".", this._uri, uri);
// if (! (bool) this.ITransportContext.IParameterProvider[GenuineParameter.IgnoreRemoteHostUriChanges])
throw exception;
}
this._uri = uri;
UriStorage.RegisterConnection(uri, this.ITransportContext);
this.ITransportContext.KnownHosts.UpdateHost(uri, this);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
binaryLogWriter.WriteEvent(LogCategory.HostInformation, "HostInformation.UpdateUri",
LogMessageType.HostInformationUriUpdated, null, null, this,
null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, this._uri, uri, null, null,
"The URI of the HostInformation has been updated. Provided uri: \"{0}\".", this._uri);
}
if (checkHostInfoVersion && this.RemoteHostUniqueIdentifier != remoteHostUniqueIdentifier || (this._uri != null && this._uri != uri))
{
if (this.RemoteHostUniqueIdentifier != -1)
{
exception = GenuineExceptions.Get_Receive_NewSessionDetected();
// release all security sessions
lock(_securitySessions)
{
foreach (DictionaryEntry entry in this._securitySessions)
{
SecuritySession securitySession = (SecuritySession) entry.Value;
securitySession.DispatchException(exception);
}
this._securitySessions = new Hashtable();
}
this.ITransportContext.IIncomingStreamHandler.DispatchException(this, exception);
}
this._remoteHostUniqueIdentifier = remoteHostUniqueIdentifier;
this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GeneralNewSessionDetected, null, this, null));
}
}
return exception;
}
/// <summary>
/// Physical address of the remote host for establishing a network connection.
/// </summary>
public string Url
{
get
{
lock (_urlLock)
return _url;
}
}
private string _url;
private object _urlLock = new object();
/// <summary>
/// Updates the value of the url member.
/// </summary>
/// <param name="url">URL of the remote host.</param>
public void UpdateUrl(string url)
{
lock (this._urlLock)
{
if (this._url == url)
return ;
this._url = url;
this.ITransportContext.KnownHosts.UpdateHost(url, this);
}
}
/// <summary>
/// Gets the URL if the remote host is a server or the URI if it is a client.
/// </summary>
public string PrimaryUri
{
get
{
return this.GenuinePersistentConnectionState == GenuinePersistentConnectionState.Opened ? this.Url : this.Uri;
}
}
/// <summary>
/// Gets the time when all information regarding the remote host
/// becomes invalid and is a subject for disposing.
/// </summary>
public int ExpireTime
{
get
{
lock (this._accessToLocalMembers)
return this._expireTime;
}
}
private int _expireTime = GenuineUtility.FurthestFuture;
/// <summary>
/// Renews the Security Session life time.
/// The first call of this method is always reset the lifetime value to the specified value.
/// </summary>
/// <param name="timeSpan">A time period to renew all host-related information.</param>
/// <param name="canMakeShorter">Indicates whether this call may reduce the host expiration time.</param>
public void Renew(int timeSpan, bool canMakeShorter)
{
if (this._firstRenewing)
{
this._firstRenewing = false;
canMakeShorter = true;
}
lock (this.DisposeLock)
{
if (this.IsDisposed)
throw OperationException.WrapException(this.DisposeReason);
lock (this._accessToLocalMembers)
{
int proposedTime = GenuineUtility.GetTimeout(timeSpan);
if (canMakeShorter || GenuineUtility.IsTimeoutExpired(this._expireTime, proposedTime))
this._expireTime = proposedTime;
}
}
}
private bool _firstRenewing = true;
/// <summary>
/// Gets a Security Session.
/// </summary>
/// <param name="securitySessionName">The name of the Security Session.</param>
/// <param name="keyStore">The store of all keys.</param>
/// <returns>An object implementing ISecuritySession interface.</returns>
public SecuritySession GetSecuritySession(string securitySessionName, IKeyStore keyStore)
{
lock (this.DisposeLock)
{
if (this.IsDisposed)
throw OperationException.WrapException(this.DisposeReason);
lock(_securitySessions)
{
SecuritySession iSecuritySession = _securitySessions[securitySessionName] as SecuritySession;
if (iSecuritySession == null)
{
IKeyProvider iKeyProvider = keyStore.GetKey(securitySessionName);
if (iKeyProvider == null)
throw GenuineExceptions.Get_Security_ContextNotFound(securitySessionName);
iSecuritySession = iKeyProvider.CreateSecuritySession(securitySessionName, this);
_securitySessions[securitySessionName] = iSecuritySession;
}
return iSecuritySession;
}
}
}
private Hashtable _securitySessions = new Hashtable();
/// <summary>
/// Destroys the Security Session with the specified name.
/// Releases all Security Session resources.
/// </summary>
/// <param name="securitySessionName">The name of the Security Session.</param>
public void DestroySecuritySession(string securitySessionName)
{
lock (this.DisposeLock)
{
if (this.IsDisposed)
throw OperationException.WrapException(this.DisposeReason);
lock(_securitySessions)
{
SecuritySession iSecuritySession = _securitySessions[securitySessionName] as SecuritySession;
if (iSecuritySession != null)
{
IDisposable iDisposable = iSecuritySession as IDisposable;
if (iDisposable != null)
iDisposable.Dispose();
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if (binaryLogWriter != null && binaryLogWriter[LogCategory.Security] > 0 )
binaryLogWriter.WriteEvent(LogCategory.Security, "HostInformation.DestroySecuritySession",
LogMessageType.SecuritySessionDestroyed, null, null, iSecuritySession.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, iSecuritySession,
iSecuritySession.Name, -1,
0, 0, 0, iSecuritySession.GetType().Name, iSecuritySession.Name, null, null,
"Security Session has been destroyed manually.");
_securitySessions.Remove(securitySessionName);
}
}
}
}
/// <summary>
/// This indexer provides the ability to access a specific element in the collection of key-and-value pairs (Client Session).
/// </summary>
public object this[object key]
{
get
{
return this._clientSession[key];
}
set
{
if (value == null)
this._clientSession.Remove(key);
else
this._clientSession[key] = value;
}
}
private Hashtable _clientSession = Hashtable.Synchronized(new Hashtable());
#region -- Persistent connection information -----------------------------------------------
/// <summary>
/// Indicates the algorithm used for servicing persistent connection to this remote host.
/// </summary>
public GenuinePersistentConnectionState GenuinePersistentConnectionState
{
get
{
return this._genuinePersistentConnectionState;
}
set
{
this._genuinePersistentConnectionState = value;
}
}
private GenuinePersistentConnectionState _genuinePersistentConnectionState = GenuinePersistentConnectionState.NotEstablished;
/// <summary>
/// Connection manager locks this member while opening persistent connection to the remote host.
/// </summary>
internal object PersistentConnectionEstablishingLock = new object();
/// <summary>
/// Gets a value indicating the unique sequence number of this instance.
/// </summary>
/// <returns></returns>
public int RemoteHostUniqueIdentifier
{
get
{
lock (this._accessToLocalMembers)
return this._remoteHostUniqueIdentifier;
}
}
private int _remoteHostUniqueIdentifier = -1;
/// <summary>
/// Gets a value indicating the unique sequence number of this instance.
/// </summary>
/// <returns></returns>
public int LocalHostUniqueIdentifier
{
get
{
lock (this._accessToLocalMembers)
return this._localHostUniqueIdentifier;
}
}
private int _localHostUniqueIdentifier = Interlocked.Increment(ref _CurrentUniqueIdentifier);
private static int _CurrentUniqueIdentifier = 0;
#endregion
#region -- Disposing -----------------------------------------------------------------------
/// <summary>
/// Indicates whether this object was disposed.
/// </summary>
public bool IsDisposed
{
get
{
lock (this.DisposeLock)
return this._isDisposed;
}
}
private bool _isDisposed = false;
/// <summary>
/// Dispose lock.
/// </summary>
internal object DisposeLock = new object();
/// <summary>
/// The reason of the disposing.
/// </summary>
public Exception DisposeReason
{
get
{
lock (this.DisposeLock)
return this._disposeReason;
}
set
{
lock (this.DisposeLock)
this._disposeReason = value;
}
}
private Exception _disposeReason;
/// <summary>
/// Releases all acquired resources.
/// Warning: must be called only by the instance of the KnownHosts class.
/// </summary>
/// <param name="reason">The reason of resource releasing.</param>
/// <returns>False if host resources have already been released before this call.</returns>
internal bool Dispose(Exception reason)
{
if (this.IsDisposed)
return false;
lock (this.DisposeLock)
{
if (this.IsDisposed)
return false;
this._isDisposed = true;
this.DisposeReason = reason;
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if (binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
{
string stackTrace = String.Empty;
try
{
stackTrace = Environment.StackTrace;
}
catch
{
}
binaryLogWriter.WriteEvent(LogCategory.HostInformation, "HostInformation.Dispose",
LogMessageType.HostInformationReleased, reason, null, this, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null,
null, -1, 0, 0, 0, this.Uri, this.Url, null, null,
"The HostInformation is released. The caller: {0}.", stackTrace);
}
// release all Security Sessions that need this
lock (this._securitySessions)
{
foreach (DictionaryEntry entry in this._securitySessions)
{
IDisposable iDisposable = entry.Value as IDisposable;
if (iDisposable != null)
iDisposable.Dispose();
}
this._securitySessions.Clear();
}
}
return true;
}
#endregion
#region -- ISetSecuritySession Members -----------------------------------------------------
/// <summary>
/// Gets or sets the Security Session used in this context.
/// </summary>
public SecuritySessionParameters SecuritySessionParameters
{
get
{
lock (_securitySessionParametersLock)
return this._securitySessionParameters;
}
set
{
lock (_securitySessionParametersLock)
this._securitySessionParameters = value;
}
}
private SecuritySessionParameters _securitySessionParameters;
private object _securitySessionParametersLock = new object();
#endregion
#region -- Debugging -----------------------------------------------------------------------
#if DEBUG
/// <summary>
/// Constructs a fake instance of the HostInformation for debugging and diagnostic purposes.
/// </summary>
/// <returns>An instance of the HostInformation class filled with fake stuff.</returns>
public static HostInformation ConstructInstanceForDebugging()
{
HostInformation hostInformation = new HostInformation("gtcp://fakehost:8737/fake.rem", null);
hostInformation._uri = "gtcp://8089";
hostInformation._remoteHostUniqueIdentifier = 15;
return hostInformation;
}
#endif
#endregion
/// <summary>
/// Returns a string that represents the current Object.
/// </summary>
/// <returns>A string that represents the current Object.</returns>
public override string ToString()
{
return String.Format("HOST (URL: {0} URI: {1} LocalNo: {2} RemoteNo: {3})",
this.Url == null ? "<none>" : this.Url,
this.Uri == null ? "<none>" : this.Uri,
this.LocalHostUniqueIdentifier, this.RemoteHostUniqueIdentifier);
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace CocosSharp
{
/// <summary>
/// CCMultipleLayer is a CCLayer with the ability to multiplex it's children.
/// Features:
/// - It supports one or more children
/// - Only one children will be active a time
/// </summary>
public class CCLayerMultiplex : CCLayer
{
public const int NoLayer = -1;
/// Offset used to preserve uniqueness for the layer tags. This is necessary
/// to allow for SwitchTo(index) and SwitchTo(Layer.Tag) to work properly.
const int TagOffsetForUniqueness = 5000;
List<int> layersInOrder = new List<int>(); // The list of layers in their insertion order.
#region Properties
public bool ShowFirstLayerOnEnter { get; set; }
protected int EnabledLayer { get; set; } // Current index of the active layer.
public CCAction InAction { get; set; } // The action to play on the layer that becomes the active layer
public CCAction OutAction { get; set; } // The action to play on the active layer when it becomes inactive.
protected Dictionary<int, CCLayer> Layers { get; set; }
public virtual CCLayer ActiveLayer
{
get
{
if (Layers == null || EnabledLayer == NoLayer)
{
return null;
}
return Layers[EnabledLayer];
}
}
public override CCScene Scene
{
get { return base.Scene; }
internal set
{
base.Scene = value;
if (value != null && Layers != null)
{
foreach (CCLayer layer in Layers.Values)
{
layer.Scene = value;
}
}
}
}
#endregion Properties
#region Constructors
public CCLayerMultiplex() : base()
{
ShowFirstLayerOnEnter = true;
EnabledLayer = NoLayer;
Layers = new Dictionary<int, CCLayer>();
}
public CCLayerMultiplex (params CCLayer[] layers) : this(null, null, layers)
{
}
public CCLayerMultiplex(CCAction inAction, CCAction outAction) : this(inAction, outAction, null)
{
}
public CCLayerMultiplex(CCAction inAction, CCAction outAction, params CCLayer[] layers)
: this()
{
InAction = inAction;
OutAction = outAction;
foreach(CCLayer layer in layers)
{
AddLayer(layer);
}
}
#endregion Constructors
public override void OnEnter()
{
if (EnabledLayer == -1 && Layers.Count > 0 && ShowFirstLayerOnEnter)
{
SwitchTo(0);
}
base.OnEnter();
}
/// <summary>
/// Adds the given layer to the list of layers to multiplex. The CCNode.Tag is used
/// as thelayer tag, but is offset by the TagOffsetForUniqueness constant.
/// </summary>
/// <param name="layer"></param>
public void AddLayer(CCLayer layer)
{
int ix = Layers.Count;
Layers[ix] = layer;
layersInOrder.Add(ix);
if (layer.Tag != CCNode.TagInvalid)
{
Layers[layer.Tag + TagOffsetForUniqueness] = layer;
if(Window != null)
layer.Window = Window;
if (Camera != null)
layer.Camera = Camera;
}
}
#region Switching layers
public CCLayer SwitchToFirstLayer()
{
if (layersInOrder.Count == 0)
{
return null;
}
return SwitchTo(layersInOrder[0]);
}
// Calling this method will set ShowFirstLayerOnEnter to false.
public void SwitchToNone()
{
SwitchTo(NoLayer);
}
// Switches to the new layer and removes the old layer from management.
public CCLayer SwitchToAndRemovePreviousLayer(int n)
{
var prevLayer = EnabledLayer;
CCLayer l = SwitchTo(n);
Layers[prevLayer] = null;
return l;
}
public CCLayer SwitchToNextLayer()
{
if (layersInOrder.Count == 0)
{
return null;
}
int idx = NoLayer;
if (EnabledLayer != NoLayer)
{
for(int z = 0; z < layersInOrder.Count; z++)
{
int ix = layersInOrder[z];
if (Layers[ix] != null)
{
if ((EnabledLayer > TagOffsetForUniqueness)
&& Layers[ix].Tag == (EnabledLayer - TagOffsetForUniqueness))
{
idx = z;
break;
}
else if(ix == EnabledLayer)
{
idx = z;
break;
}
}
}
idx = (idx + 1) % layersInOrder.Count;
}
else
{
idx = 0;
}
if (idx == NoLayer)
{
idx = 0;
}
return SwitchTo(layersInOrder[idx]);
}
public CCLayer SwitchToPreviousLayer()
{
if (layersInOrder.Count == 0)
{
return null;
}
int idx = NoLayer;
if (EnabledLayer != NoLayer)
{
for (int z = 0; z < layersInOrder.Count; z++)
{
int ix = layersInOrder[z];
if (Layers[ix] != null)
{
if ((EnabledLayer > TagOffsetForUniqueness)
&& Layers[ix].Tag == (EnabledLayer - TagOffsetForUniqueness))
{
idx = z;
break;
}
else if (ix == EnabledLayer)
{
idx = z;
break;
}
}
}
idx -= 1;
if (idx < 0)
{
idx = layersInOrder.Count - 1;
}
}
else
{
idx = 0;
}
return SwitchTo(layersInOrder[idx]);
}
/// <summary>
/// Swtich to the given index layer and use the given action after the layer is
/// added to the parent. The parameter can be the index or it can be the tag of the layer.
/// </summary>
/// <param name="n">Send in NoLayer to hide all multiplexed layers. Otherwise, send in a tag or the logical index of the
/// layer to show.</param>
/// <returns>The layer that is going to be shown. This can return null if the SwitchTo layer is NoLayer</returns>
public CCLayer SwitchTo(int n)
{
if (n != NoLayer)
{
if (EnabledLayer == n || EnabledLayer == (n + TagOffsetForUniqueness))
{
if (EnabledLayer == NoLayer)
{
return null;
}
return Layers[EnabledLayer];
}
}
if (EnabledLayer != NoLayer)
{
CCLayer outLayer = null;
if (Layers.ContainsKey(EnabledLayer))
{
outLayer = Layers[EnabledLayer];
if (OutAction != null)
{
outLayer.RunAction(
new CCSequence(
(CCFiniteTimeAction)OutAction,
new CCCallFunc(() => RemoveChild(outLayer, true))
)
);
}
else
{
RemoveChild(outLayer, true);
}
}
// We have no enabled layer at this point
EnabledLayer = NoLayer;
}
// When NoLayer, the multiplexer shows nothing.
if (n == NoLayer)
{
ShowFirstLayerOnEnter = false;
return null;
}
if (!Layers.ContainsKey(n))
{
int f = n + TagOffsetForUniqueness;
if (Layers.ContainsKey(f))
{
n = f;
}
else
{
// Invalid index - layer not found
return null;
}
}
// Set the active layer
AddChild(Layers[n]);
EnabledLayer = n;
if (InAction != null)
{
Layers[n].RunAction(InAction);
}
return Layers[EnabledLayer];
}
#endregion Switching
}
}
| |
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 web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using ServiceStack.Text.Support;
#if WINDOWS_PHONE
using System.Linq.Expressions;
#endif
namespace ServiceStack.Text
{
public delegate EmptyCtorDelegate EmptyCtorFactoryDelegate(Type type);
public delegate object EmptyCtorDelegate();
public static class ReflectionExtensions
{
private static Dictionary<Type, object> DefaultValueTypes = new Dictionary<Type, object>();
public static object GetDefaultValue(this Type type)
{
if (!type.IsValueType()) return null;
object defaultValue;
if (DefaultValueTypes.TryGetValue(type, out defaultValue)) return defaultValue;
defaultValue = Activator.CreateInstance(type);
Dictionary<Type, object> snapshot, newCache;
do
{
snapshot = DefaultValueTypes;
newCache = new Dictionary<Type, object>(DefaultValueTypes);
newCache[type] = defaultValue;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref DefaultValueTypes, newCache, snapshot), snapshot));
return defaultValue;
}
public static bool IsInstanceOf(this Type type, Type thisOrBaseType)
{
while (type != null)
{
if (type == thisOrBaseType)
return true;
type = type.BaseType();
}
return false;
}
public static bool HasGenericType(this Type type)
{
while (type != null)
{
if (type.IsGeneric())
return true;
type = type.BaseType();
}
return false;
}
public static Type GetGenericType(this Type type)
{
while (type != null)
{
if (type.IsGeneric())
return type;
type = type.BaseType();
}
return null;
}
public static Type GetTypeWithGenericTypeDefinitionOfAny(this Type type, params Type[] genericTypeDefinitions)
{
foreach (var genericTypeDefinition in genericTypeDefinitions)
{
var genericType = type.GetTypeWithGenericTypeDefinitionOf(genericTypeDefinition);
if (genericType == null && type == genericTypeDefinition)
{
genericType = type;
}
if (genericType != null)
return genericType;
}
return null;
}
public static bool IsOrHasGenericInterfaceTypeOf(this Type type, Type genericTypeDefinition)
{
return (type.GetTypeWithGenericTypeDefinitionOf(genericTypeDefinition) != null)
|| (type == genericTypeDefinition);
}
public static Type GetTypeWithGenericTypeDefinitionOf(this Type type, Type genericTypeDefinition)
{
foreach (var t in type.GetTypeInterfaces())
{
if (t.IsGeneric() && t.GetGenericTypeDefinition() == genericTypeDefinition)
{
return t;
}
}
var genericType = type.GetGenericType();
if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition)
{
return genericType;
}
return null;
}
public static Type GetTypeWithInterfaceOf(this Type type, Type interfaceType)
{
if (type == interfaceType) return interfaceType;
foreach (var t in type.GetTypeInterfaces())
{
if (t == interfaceType)
return t;
}
return null;
}
public static bool HasInterface(this Type type, Type interfaceType)
{
foreach (var t in type.GetTypeInterfaces())
{
if (t == interfaceType)
return true;
}
return false;
}
public static bool AllHaveInterfacesOfType(
this Type assignableFromType, params Type[] types)
{
foreach (var type in types)
{
if (assignableFromType.GetTypeWithInterfaceOf(type) == null) return false;
}
return true;
}
public static bool IsNumericType(this Type type)
{
if (type == null) return false;
if (type.IsEnum) //TypeCode can be TypeCode.Int32
{
return JsConfig.TreatEnumAsInteger || type.IsEnumFlags();
}
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
case TypeCode.Object:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsNumericType(Nullable.GetUnderlyingType(type));
}
if (type.IsEnum)
{
return JsConfig.TreatEnumAsInteger || type.IsEnumFlags();
}
return false;
}
return false;
}
public static bool IsIntegerType(this Type type)
{
if (type == null) return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
case TypeCode.Object:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsNumericType(Nullable.GetUnderlyingType(type));
}
return false;
}
return false;
}
public static bool IsRealNumberType(this Type type)
{
if (type == null) return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
case TypeCode.Object:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsNumericType(Nullable.GetUnderlyingType(type));
}
return false;
}
return false;
}
public static Type GetTypeWithGenericInterfaceOf(this Type type, Type genericInterfaceType)
{
foreach (var t in type.GetTypeInterfaces())
{
if (t.IsGeneric() && t.GetGenericTypeDefinition() == genericInterfaceType)
return t;
}
if (!type.IsGeneric()) return null;
var genericType = type.GetGenericType();
return genericType.GetGenericTypeDefinition() == genericInterfaceType
? genericType
: null;
}
public static bool HasAnyTypeDefinitionsOf(this Type genericType, params Type[] theseGenericTypes)
{
if (!genericType.IsGeneric()) return false;
var genericTypeDefinition = genericType.GenericTypeDefinition();
foreach (var thisGenericType in theseGenericTypes)
{
if (genericTypeDefinition == thisGenericType)
return true;
}
return false;
}
public static Type[] GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments(
this Type assignableFromType, Type typeA, Type typeB)
{
var typeAInterface = typeA.GetTypeWithGenericInterfaceOf(assignableFromType);
if (typeAInterface == null) return null;
var typeBInterface = typeB.GetTypeWithGenericInterfaceOf(assignableFromType);
if (typeBInterface == null) return null;
var typeAGenericArgs = typeAInterface.GetTypeGenericArguments();
var typeBGenericArgs = typeBInterface.GetTypeGenericArguments();
if (typeAGenericArgs.Length != typeBGenericArgs.Length) return null;
for (var i = 0; i < typeBGenericArgs.Length; i++)
{
if (typeAGenericArgs[i] != typeBGenericArgs[i])
{
return null;
}
}
return typeAGenericArgs;
}
public static TypePair GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments(
this Type assignableFromType, Type typeA, Type typeB)
{
var typeAInterface = typeA.GetTypeWithGenericInterfaceOf(assignableFromType);
if (typeAInterface == null) return null;
var typeBInterface = typeB.GetTypeWithGenericInterfaceOf(assignableFromType);
if (typeBInterface == null) return null;
var typeAGenericArgs = typeAInterface.GetTypeGenericArguments();
var typeBGenericArgs = typeBInterface.GetTypeGenericArguments();
if (typeAGenericArgs.Length != typeBGenericArgs.Length) return null;
for (var i = 0; i < typeBGenericArgs.Length; i++)
{
if (!AreAllStringOrValueTypes(typeAGenericArgs[i], typeBGenericArgs[i]))
{
return null;
}
}
return new TypePair(typeAGenericArgs, typeBGenericArgs);
}
public static bool AreAllStringOrValueTypes(params Type[] types)
{
foreach (var type in types)
{
if (!(type == typeof(string) || type.IsValueType())) return false;
}
return true;
}
static Dictionary<Type, EmptyCtorDelegate> ConstructorMethods = new Dictionary<Type, EmptyCtorDelegate>();
public static EmptyCtorDelegate GetConstructorMethod(Type type)
{
EmptyCtorDelegate emptyCtorFn;
if (ConstructorMethods.TryGetValue(type, out emptyCtorFn)) return emptyCtorFn;
emptyCtorFn = GetConstructorMethodToCache(type);
Dictionary<Type, EmptyCtorDelegate> snapshot, newCache;
do
{
snapshot = ConstructorMethods;
newCache = new Dictionary<Type, EmptyCtorDelegate>(ConstructorMethods);
newCache[type] = emptyCtorFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ConstructorMethods, newCache, snapshot), snapshot));
return emptyCtorFn;
}
static Dictionary<string, EmptyCtorDelegate> TypeNamesMap = new Dictionary<string, EmptyCtorDelegate>();
public static EmptyCtorDelegate GetConstructorMethod(string typeName)
{
EmptyCtorDelegate emptyCtorFn;
if (TypeNamesMap.TryGetValue(typeName, out emptyCtorFn)) return emptyCtorFn;
var type = JsConfig.TypeFinder.Invoke(typeName);
if (type == null) return null;
emptyCtorFn = GetConstructorMethodToCache(type);
Dictionary<string, EmptyCtorDelegate> snapshot, newCache;
do
{
snapshot = TypeNamesMap;
newCache = new Dictionary<string, EmptyCtorDelegate>(TypeNamesMap);
newCache[typeName] = emptyCtorFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TypeNamesMap, newCache, snapshot), snapshot));
return emptyCtorFn;
}
public static EmptyCtorDelegate GetConstructorMethodToCache(Type type)
{
if (type.IsInterface)
{
if (type.HasGenericType())
{
var genericType = type.GetTypeWithGenericTypeDefinitionOfAny(
typeof(IDictionary<,>));
if (genericType != null)
{
var keyType = genericType.GenericTypeArguments()[0];
var valueType = genericType.GenericTypeArguments()[1];
return GetConstructorMethodToCache(typeof(Dictionary<,>).MakeGenericType(keyType, valueType));
}
genericType = type.GetTypeWithGenericTypeDefinitionOfAny(
typeof(IEnumerable<>),
typeof(ICollection<>),
typeof(IList<>));
if (genericType != null)
{
var elementType = genericType.GenericTypeArguments()[0];
return GetConstructorMethodToCache(typeof(List<>).MakeGenericType(elementType));
}
}
}
else if (type.IsArray)
{
return () => Array.CreateInstance(type.GetElementType(), 0);
}
var emptyCtor = type.GetEmptyConstructor();
if (emptyCtor != null)
{
#if MONOTOUCH || c|| XBOX || NETFX_CORE
return () => Activator.CreateInstance(type);
#elif WINDOWS_PHONE
return Expression.Lambda<EmptyCtorDelegate>(Expression.New(type)).Compile();
#else
#if SILVERLIGHT
var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes);
#else
var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(ReflectionExtensions).Module, true);
#endif
var ilgen = dm.GetILGenerator();
ilgen.Emit(System.Reflection.Emit.OpCodes.Nop);
ilgen.Emit(System.Reflection.Emit.OpCodes.Newobj, emptyCtor);
ilgen.Emit(System.Reflection.Emit.OpCodes.Ret);
return (EmptyCtorDelegate)dm.CreateDelegate(typeof(EmptyCtorDelegate));
#endif
}
#if (SILVERLIGHT && !WINDOWS_PHONE) || XBOX
return () => Activator.CreateInstance(type);
#elif WINDOWS_PHONE
return Expression.Lambda<EmptyCtorDelegate>(Expression.New(type)).Compile();
#else
if (type == typeof(string))
return () => String.Empty;
//Anonymous types don't have empty constructors
return () => FormatterServices.GetUninitializedObject(type);
#endif
}
private static class TypeMeta<T>
{
public static readonly EmptyCtorDelegate EmptyCtorFn;
static TypeMeta()
{
EmptyCtorFn = GetConstructorMethodToCache(typeof(T));
}
}
public static object CreateInstance<T>()
{
return TypeMeta<T>.EmptyCtorFn();
}
public static object CreateInstance(this Type type)
{
var ctorFn = GetConstructorMethod(type);
return ctorFn();
}
public static object CreateInstance(string typeName)
{
var ctorFn = GetConstructorMethod(typeName);
return ctorFn();
}
public static PropertyInfo[] GetPublicProperties(this Type type)
{
if (type.IsInterface())
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetTypeInterfaces())
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetTypesPublicProperties();
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return type.GetTypesPublicProperties()
.Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties
.ToArray();
}
const string DataContract = "DataContractAttribute";
const string DataMember = "DataMemberAttribute";
const string IgnoreDataMember = "IgnoreDataMemberAttribute";
public static PropertyInfo[] GetSerializableProperties(this Type type)
{
var publicProperties = GetPublicProperties(type);
var publicReadableProperties = publicProperties.Where(x => x.PropertyGetMethod() != null);
if (type.IsDto())
{
return !Env.IsMono
? publicReadableProperties.Where(attr =>
attr.IsDefined(typeof(DataMemberAttribute), false)).ToArray()
: publicReadableProperties.Where(attr =>
attr.CustomAttributes(false).Any(x => x.GetType().Name == DataMember)).ToArray();
}
// else return those properties that are not decorated with IgnoreDataMember
return publicReadableProperties.Where(prop => !prop.CustomAttributes(false).Any(attr => attr.GetType().Name == IgnoreDataMember)).ToArray();
}
public static FieldInfo[] GetSerializableFields(this Type type)
{
if (type.IsDto()) {
return new FieldInfo[0];
}
var publicFields = type.GetPublicFields();
// else return those properties that are not decorated with IgnoreDataMember
return publicFields.Where(prop => !prop.CustomAttributes(false).Any(attr => attr.GetType().Name == IgnoreDataMember)).ToArray();
}
public static bool HasAttr<T>(this Type type) where T : Attribute
{
return type.HasAttribute<T>();
}
#if !SILVERLIGHT && !MONOTOUCH
static readonly Dictionary<Type, FastMember.TypeAccessor> typeAccessorMap
= new Dictionary<Type, FastMember.TypeAccessor>();
#endif
public static DataContractAttribute GetDataContract(this Type type)
{
var dataContract = type.FirstAttribute<DataContractAttribute>();
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
if (dataContract == null && Env.IsMono)
return type.GetWeakDataContract();
#endif
return dataContract;
}
public static DataMemberAttribute GetDataMember(this PropertyInfo pi)
{
var dataMember = pi.CustomAttributes(typeof(DataMemberAttribute), false)
.FirstOrDefault() as DataMemberAttribute;
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
if (dataMember == null && Env.IsMono)
return pi.GetWeakDataMember();
#endif
return dataMember;
}
public static DataMemberAttribute GetDataMember(this FieldInfo pi)
{
var dataMember = pi.CustomAttributes(typeof(DataMemberAttribute), false)
.FirstOrDefault() as DataMemberAttribute;
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
if (dataMember == null && Env.IsMono)
return pi.GetWeakDataMember();
#endif
return dataMember;
}
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
public static DataContractAttribute GetWeakDataContract(this Type type)
{
var attr = type.CustomAttributes().FirstOrDefault(x => x.GetType().Name == DataContract);
if (attr != null)
{
var attrType = attr.GetType();
FastMember.TypeAccessor accessor;
lock (typeAccessorMap)
{
if (!typeAccessorMap.TryGetValue(attrType, out accessor))
typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType());
}
return new DataContractAttribute {
Name = (string)accessor[attr, "Name"],
Namespace = (string)accessor[attr, "Namespace"],
};
}
return null;
}
public static DataMemberAttribute GetWeakDataMember(this PropertyInfo pi)
{
var attr = pi.CustomAttributes().FirstOrDefault(x => x.GetType().Name == DataMember);
if (attr != null)
{
var attrType = attr.GetType();
FastMember.TypeAccessor accessor;
lock (typeAccessorMap)
{
if (!typeAccessorMap.TryGetValue(attrType, out accessor))
typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType());
}
var newAttr = new DataMemberAttribute {
Name = (string) accessor[attr, "Name"],
EmitDefaultValue = (bool)accessor[attr, "EmitDefaultValue"],
IsRequired = (bool)accessor[attr, "IsRequired"],
};
var order = (int)accessor[attr, "Order"];
if (order >= 0)
newAttr.Order = order; //Throws Exception if set to -1
return newAttr;
}
return null;
}
public static DataMemberAttribute GetWeakDataMember(this FieldInfo pi)
{
var attr = pi.CustomAttributes().FirstOrDefault(x => x.GetType().Name == DataMember);
if (attr != null)
{
var attrType = attr.GetType();
FastMember.TypeAccessor accessor;
lock (typeAccessorMap)
{
if (!typeAccessorMap.TryGetValue(attrType, out accessor))
typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType());
}
var newAttr = new DataMemberAttribute
{
Name = (string)accessor[attr, "Name"],
EmitDefaultValue = (bool)accessor[attr, "EmitDefaultValue"],
IsRequired = (bool)accessor[attr, "IsRequired"],
};
var order = (int)accessor[attr, "Order"];
if (order >= 0)
newAttr.Order = order; //Throws Exception if set to -1
return newAttr;
}
return null;
}
#endif
}
public static class PlatformExtensions //Because WinRT is a POS
{
public static bool IsInterface(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsInterface;
#else
return type.IsInterface;
#endif
}
public static bool IsArray(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsArray;
#else
return type.IsArray;
#endif
}
public static bool IsValueType(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsValueType;
#else
return type.IsValueType;
#endif
}
public static bool IsGeneric(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsGenericType;
#else
return type.IsGenericType;
#endif
}
public static Type BaseType(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().BaseType;
#else
return type.BaseType;
#endif
}
public static Type ReflectedType(this PropertyInfo pi)
{
#if NETFX_CORE
return pi.PropertyType;
#else
return pi.ReflectedType;
#endif
}
public static Type ReflectedType(this FieldInfo fi)
{
#if NETFX_CORE
return fi.FieldType;
#else
return fi.ReflectedType;
#endif
}
public static Type GenericTypeDefinition(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().GetGenericTypeDefinition();
#else
return type.GetGenericTypeDefinition();
#endif
}
public static Type[] GetTypeInterfaces(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().ImplementedInterfaces.ToArray();
#else
return type.GetInterfaces();
#endif
}
public static Type[] GetTypeGenericArguments(this Type type)
{
#if NETFX_CORE
return type.GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static ConstructorInfo GetEmptyConstructor(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Count() == 0);
#else
var j = type.GetConstructor(Type.EmptyTypes);
#if MONOTOUCH || ANDROID
if (j == null){
Console.WriteLine ("Linker took out a constructor for {0}", type);
}
#endif
return j;
#endif
}
internal static PropertyInfo[] GetTypesPublicProperties(this Type subType)
{
#if NETFX_CORE
return subType.GetRuntimeProperties().ToArray();
#else
return subType.GetProperties(
BindingFlags.FlattenHierarchy |
BindingFlags.Public |
BindingFlags.Instance);
#endif
}
public static PropertyInfo[] Properties(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeProperties().ToArray();
#else
return type.GetProperties();
#endif
}
public static FieldInfo[] GetPublicFields(this Type type)
{
if (type.IsInterface())
{
return new FieldInfo[0];
}
#if NETFX_CORE
return type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic).ToArray();
#else
return type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance)
.ToArray();
#endif
}
public static MemberInfo[] GetPublicMembers(this Type type)
{
#if NETFX_CORE
var members = new List<MemberInfo>();
members.AddRange(type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic));
members.AddRange(type.GetPublicProperties());
return members.ToArray();
#else
return type.GetMembers(BindingFlags.Public | BindingFlags.Instance);
#endif
}
public static MemberInfo[] GetAllPublicMembers(this Type type)
{
#if NETFX_CORE
var members = new List<MemberInfo>();
members.AddRange(type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic));
members.AddRange(type.GetPublicProperties());
return members.ToArray();
#else
return type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
#endif
}
public static bool HasAttribute<T>(this Type type, bool inherit = true) where T : Attribute
{
return type.CustomAttributes(inherit).Any(x => x.GetType() == typeof(T));
}
public static IEnumerable<T> AttributesOfType<T>(this Type type, bool inherit = true) where T : Attribute
{
#if NETFX_CORE
return type.GetTypeInfo().GetCustomAttributes<T>(inherit);
#else
return type.GetCustomAttributes(inherit).OfType<T>();
#endif
}
const string DataContract = "DataContractAttribute";
public static bool IsDto(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsDefined(typeof(DataContractAttribute), false);
#else
return !Env.IsMono
? type.IsDefined(typeof(DataContractAttribute), false)
: type.GetCustomAttributes(true).Any(x => x.GetType().Name == DataContract);
#endif
}
public static MethodInfo PropertyGetMethod(this PropertyInfo pi, bool nonPublic = false)
{
#if NETFX_CORE
return pi.GetMethod;
#else
return pi.GetGetMethod(false);
#endif
}
public static Type[] Interfaces(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().ImplementedInterfaces.ToArray();
//return type.GetTypeInfo().ImplementedInterfaces
// .FirstOrDefault(x => !x.GetTypeInfo().ImplementedInterfaces
// .Any(y => y.GetTypeInfo().ImplementedInterfaces.Contains(y)));
#else
return type.GetInterfaces();
#endif
}
public static PropertyInfo[] AllProperties(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeProperties().ToArray();
#else
return type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
#endif
}
public static object[] CustomAttributes(this PropertyInfo propertyInfo, bool inherit = true)
{
#if NETFX_CORE
return propertyInfo.GetCustomAttributes(inherit).ToArray();
#else
return propertyInfo.GetCustomAttributes(inherit);
#endif
}
public static object[] CustomAttributes(this PropertyInfo propertyInfo, Type attrType, bool inherit = true)
{
#if NETFX_CORE
return propertyInfo.GetCustomAttributes(inherit).Where(x => x.GetType() == attrType).ToArray();
#else
return propertyInfo.GetCustomAttributes(attrType, inherit);
#endif
}
public static object[] CustomAttributes(this FieldInfo fieldInfo, bool inherit = true)
{
#if NETFX_CORE
return fieldInfo.GetCustomAttributes(inherit).ToArray();
#else
return fieldInfo.GetCustomAttributes(inherit);
#endif
}
public static object[] CustomAttributes(this FieldInfo fieldInfo, Type attrType, bool inherit = true)
{
#if NETFX_CORE
return fieldInfo.GetCustomAttributes(inherit).Where(x => x.GetType() == attrType).ToArray();
#else
return fieldInfo.GetCustomAttributes(attrType, inherit);
#endif
}
public static object[] CustomAttributes(this Type type, bool inherit = true)
{
#if NETFX_CORE
return type.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
#else
return type.GetCustomAttributes(inherit);
#endif
}
public static object[] CustomAttributes(this Type type, Type attrType, bool inherit = true)
{
#if NETFX_CORE
return type.GetTypeInfo().GetCustomAttributes(inherit).Where(x => x.GetType() == attrType).ToArray();
#else
return type.GetCustomAttributes(attrType, inherit);
#endif
}
public static TAttr FirstAttribute<TAttr>(this Type type, bool inherit = true) where TAttr : Attribute
{
#if NETFX_CORE
return type.GetTypeInfo().GetCustomAttributes(typeof(TAttr), inherit)
.FirstOrDefault() as TAttr;
#else
return type.GetCustomAttributes(typeof(TAttr), inherit)
.FirstOrDefault() as TAttr;
#endif
}
public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo)
where TAttribute : Attribute
{
return propertyInfo.FirstAttribute<TAttribute>(true);
}
public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo, bool inherit)
where TAttribute : Attribute
{
#if NETFX_CORE
var attrs = propertyInfo.GetCustomAttributes<TAttribute>(inherit);
return (TAttribute)(attrs.Count() > 0 ? attrs.ElementAt(0) : null);
#else
var attrs = propertyInfo.GetCustomAttributes(typeof(TAttribute), inherit);
return (TAttribute)(attrs.Length > 0 ? attrs[0] : null);
#endif
}
public static Type FirstGenericTypeDefinition(this Type type)
{
while (type != null)
{
if (type.HasGenericType())
return type.GenericTypeDefinition();
type = type.BaseType();
}
return null;
}
public static bool IsDynamic(this Assembly assembly)
{
#if MONOTOUCH || WINDOWS_PHONE || NETFX_CORE
return false;
#else
try
{
var isDyanmic = assembly is System.Reflection.Emit.AssemblyBuilder
|| string.IsNullOrEmpty(assembly.Location);
return isDyanmic;
}
catch (NotSupportedException)
{
//Ignore assembly.Location not supported in a dynamic assembly.
return true;
}
#endif
}
public static MethodInfo GetPublicStaticMethod(this Type type, string methodName, Type[] types = null)
{
#if NETFX_CORE
return type.GetRuntimeMethod(methodName, types);
#else
return types == null
? type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static)
: type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, types, null);
#endif
}
public static MethodInfo GetMethodInfo(this Type type, string methodName, Type[] types = null)
{
#if NETFX_CORE
return type.GetRuntimeMethods().First(p => p.Name.Equals(methodName));
#else
return types == null
? type.GetMethod(methodName)
: type.GetMethod(methodName, types);
#endif
}
public static object InvokeMethod(this Delegate fn, object instance, object[] parameters = null)
{
#if NETFX_CORE
return fn.GetMethodInfo().Invoke(instance, parameters ?? new object[] { });
#else
return fn.Method.Invoke(instance, parameters ?? new object[] { });
#endif
}
public static FieldInfo GetPublicStaticField(this Type type, string fieldName)
{
#if NETFX_CORE
return type.GetRuntimeField(fieldName);
#else
return type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static);
#endif
}
public static Delegate MakeDelegate(this MethodInfo mi, Type delegateType, bool throwOnBindFailure=true)
{
#if NETFX_CORE
return mi.CreateDelegate(delegateType);
#else
return Delegate.CreateDelegate(delegateType, mi, throwOnBindFailure);
#endif
}
public static Type[] GenericTypeArguments(this Type type)
{
#if NETFX_CORE
return type.GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static ConstructorInfo[] DeclaredConstructors(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredConstructors.ToArray();
#else
return type.GetConstructors();
#endif
}
public static bool AssignableFrom(this Type type, Type fromType)
{
#if NETFX_CORE
return type.GetTypeInfo().IsAssignableFrom(fromType.GetTypeInfo());
#else
return type.IsAssignableFrom(fromType);
#endif
}
public static bool IsStandardClass(this Type type)
{
#if NETFX_CORE
var typeInfo = type.GetTypeInfo();
return typeInfo.IsClass && !typeInfo.IsAbstract && !typeInfo.IsInterface;
#else
return type.IsClass && !type.IsAbstract && !type.IsInterface;
#endif
}
public static bool IsAbstract(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsAbstract;
#else
return type.IsAbstract;
#endif
}
public static PropertyInfo GetPropertyInfo(this Type type, string propertyName)
{
#if NETFX_CORE
return type.GetRuntimeProperty(propertyName);
#else
return type.GetProperty(propertyName);
#endif
}
public static FieldInfo GetFieldInfo(this Type type, string fieldName)
{
#if NETFX_CORE
return type.GetRuntimeField(fieldName);
#else
return type.GetField(fieldName);
#endif
}
public static FieldInfo[] GetWritableFields(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeFields().Where(p => !p.IsPublic && !p.IsStatic).ToArray();
#else
return type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
#endif
}
public static MethodInfo SetMethod(this PropertyInfo pi, bool nonPublic = true)
{
#if NETFX_CORE
return pi.SetMethod;
#else
return pi.GetSetMethod(nonPublic);
#endif
}
public static MethodInfo GetMethodInfo(this PropertyInfo pi, bool nonPublic = true)
{
#if NETFX_CORE
return pi.GetMethod;
#else
return pi.GetGetMethod(nonPublic);
#endif
}
public static bool InstanceOfType(this Type type, object instance)
{
#if NETFX_CORE
return type.IsInstanceOf(instance.GetType());
#else
return type.IsInstanceOfType(instance);
#endif
}
public static bool IsClass(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsClass;
#else
return type.IsClass;
#endif
}
public static bool IsEnum(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsEnum;
#else
return type.IsEnum;
#endif
}
public static bool IsEnumFlags(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsEnum && type.FirstAttribute<FlagsAttribute>(false) != null;
#else
return type.IsEnum && type.FirstAttribute<FlagsAttribute>(false) != null;
#endif
}
public static bool IsUnderlyingEnum(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsEnum;
#else
return type.IsEnum || type.UnderlyingSystemType.IsEnum;
#endif
}
public static MethodInfo[] GetMethodInfos(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeMethods().ToArray();
#else
return type.GetMethods();
#endif
}
public static PropertyInfo[] GetPropertyInfos(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeProperties().ToArray();
#else
return type.GetProperties();
#endif
}
#if SILVERLIGHT || NETFX_CORE
public static List<U> ConvertAll<T, U>(this List<T> list, Func<T, U> converter)
{
var result = new List<U>();
foreach (var element in list)
{
result.Add(converter(element));
}
return result;
}
#endif
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#if __UNIFIED__
using Foundation;
using AVFoundation;
using CoreFoundation;
using CoreGraphics;
using CoreMedia;
using CoreVideo;
using ObjCRuntime;
using UIKit;
#else
using MonoTouch.AVFoundation;
using MonoTouch.CoreFoundation;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreMedia;
using MonoTouch.CoreVideo;
using MonoTouch.Foundation;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using System.Drawing;
using CGRect = global::System.Drawing.RectangleF;
using CGPoint = global::System.Drawing.PointF;
#endif
using ZXing.Common;
using ZXing.Mobile;
namespace ZXing.Mobile
{
public class AVCaptureScannerView : UIView, IZXingScanner<UIView>
{
public AVCaptureScannerView()
{
}
public AVCaptureScannerView(IntPtr handle) : base(handle)
{
}
public AVCaptureScannerView (CGRect frame) : base(frame)
{
}
AVCaptureSession session;
AVCaptureVideoPreviewLayer previewLayer;
//AVCaptureVideoDataOutput output;
//OutputRecorder outputRecorder;
//DispatchQueue queue;
Action<ZXing.Result> resultCallback;
volatile bool stopped = true;
//BarcodeReader barcodeReader;
volatile bool foundResult = false;
CaptureDelegate captureDelegate;
UIView layerView;
UIView overlayView = null;
public event Action OnCancelButtonPressed;
public string CancelButtonText { get;set; }
public string FlashButtonText { get;set; }
MobileBarcodeScanningOptions options = new MobileBarcodeScanningOptions();
void Setup()
{
if (overlayView != null)
overlayView.RemoveFromSuperview ();
if (UseCustomOverlayView && CustomOverlayView != null)
overlayView = CustomOverlayView;
else {
overlayView = new ZXingDefaultOverlayView (new CGRect (0, 0, this.Frame.Width, this.Frame.Height),
TopText, BottomText, CancelButtonText, FlashButtonText,
() => {
var evt = OnCancelButtonPressed;
if (evt != null)
evt();
}, ToggleTorch);
}
if (overlayView != null)
{
/* UITapGestureRecognizer tapGestureRecognizer = new UITapGestureRecognizer ();
tapGestureRecognizer.AddTarget (() => {
var pt = tapGestureRecognizer.LocationInView(overlayView);
Focus(pt);
Console.WriteLine("OVERLAY TOUCH: " + pt.X + ", " + pt.Y);
});
tapGestureRecognizer.CancelsTouchesInView = false;
tapGestureRecognizer.NumberOfTapsRequired = 1;
tapGestureRecognizer.NumberOfTouchesRequired = 1;
overlayView.AddGestureRecognizer (tapGestureRecognizer);*/
overlayView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
overlayView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
}
}
bool torch = false;
bool analyzing = true;
DateTime lastAnalysis = DateTime.UtcNow.AddYears (-99);
bool wasScanned = false;
bool working = false;
bool SetupCaptureSession ()
{
var availableResolutions = new List<CameraResolution> ();
var consideredResolutions = new Dictionary<NSString, CameraResolution> {
{ AVCaptureSession.Preset352x288, new CameraResolution { Width = 352, Height = 288 } },
{ AVCaptureSession.PresetMedium, new CameraResolution { Width = 480, Height = 360 } }, //480x360
{ AVCaptureSession.Preset640x480, new CameraResolution { Width = 640, Height = 480 } },
{ AVCaptureSession.Preset1280x720, new CameraResolution { Width = 1280, Height = 720 } },
{ AVCaptureSession.Preset1920x1080, new CameraResolution { Width = 1920, Height = 1080 } }
};
// configure the capture session for low resolution, change this if your code
// can cope with more data or volume
session = new AVCaptureSession () {
SessionPreset = AVCaptureSession.Preset640x480
};
// create a device input and attach it to the session
// var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
AVCaptureDevice captureDevice = null;
var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
foreach (var device in devices)
{
captureDevice = device;
if (options.UseFrontCameraIfAvailable.HasValue &&
options.UseFrontCameraIfAvailable.Value &&
device.Position == AVCaptureDevicePosition.Front)
break; //Front camera successfully set
else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value))
break; //Back camera succesfully set
}
if (captureDevice == null){
Console.WriteLine ("No captureDevice - this won't work on the simulator, try a physical device");
if (overlayView != null)
{
this.AddSubview (overlayView);
this.BringSubviewToFront (overlayView);
}
return false;
}
CameraResolution resolution = null;
// Find resolution
// Go through the resolutions we can even consider
foreach (var cr in consideredResolutions) {
// Now check to make sure our selected device supports the resolution
// so we can add it to the list to pick from
if (captureDevice.SupportsAVCaptureSessionPreset (cr.Key))
availableResolutions.Add (cr.Value);
}
resolution = options.GetResolution (availableResolutions);
// See if the user selected a resolution
if (resolution != null) {
// Now get the preset string from the resolution chosen
var preset = (from c in consideredResolutions
where c.Value.Width == resolution.Width
&& c.Value.Height == resolution.Height
select c.Key).FirstOrDefault ();
// If we found a matching preset, let's set it on the session
if (!string.IsNullOrEmpty(preset))
session.SessionPreset = preset;
}
var input = AVCaptureDeviceInput.FromDevice (captureDevice);
if (input == null){
Console.WriteLine ("No input - this won't work on the simulator, try a physical device");
if (overlayView != null)
{
this.AddSubview (overlayView);
this.BringSubviewToFront (overlayView);
}
return false;
}
else
session.AddInput (input);
foundResult = false;
//Detect barcodes with built in avcapture stuff
AVCaptureMetadataOutput metadataOutput = new AVCaptureMetadataOutput();
captureDelegate = new CaptureDelegate (metaDataObjects =>
{
if (!analyzing)
return;
//Console.WriteLine("Found MetaData Objects");
var msSinceLastPreview = (DateTime.UtcNow - lastAnalysis).TotalMilliseconds;
if (msSinceLastPreview < options.DelayBetweenAnalyzingFrames
|| (wasScanned && msSinceLastPreview < options.DelayBetweenContinuousScans)
|| working)
//|| CancelTokenSource.IsCancellationRequested)
{
return;
}
working = true;
wasScanned = false;
lastAnalysis = DateTime.UtcNow;
var mdo = metaDataObjects.FirstOrDefault();
if (mdo == null)
return;
var readableObj = mdo as AVMetadataMachineReadableCodeObject;
if (readableObj == null)
return;
wasScanned = true;
var zxingFormat = ZXingBarcodeFormatFromAVCaptureBarcodeFormat(readableObj.Type.ToString());
var rs = new ZXing.Result(readableObj.StringValue, null, null, zxingFormat);
resultCallback(rs);
working = false;
});
metadataOutput.SetDelegate (captureDelegate, DispatchQueue.MainQueue);
session.AddOutput (metadataOutput);
//Setup barcode formats
if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0)
{
#if __UNIFIED__
var formats = AVMetadataObjectType.None;
foreach (var f in ScanningOptions.PossibleFormats)
formats |= AVCaptureBarcodeFormatFromZXingBarcodeFormat (f);
formats &= ~AVMetadataObjectType.None;
metadataOutput.MetadataObjectTypes = formats;
#else
var formats = new List<string> ();
foreach (var f in ScanningOptions.PossibleFormats)
formats.AddRange (AVCaptureBarcodeFormatFromZXingBarcodeFormat (f));
metadataOutput.MetadataObjectTypes = (from f in formats.Distinct () select new NSString(f)).ToArray();
#endif
}
else
metadataOutput.MetadataObjectTypes = metadataOutput.AvailableMetadataObjectTypes;
previewLayer = new AVCaptureVideoPreviewLayer(session);
//Framerate set here (15 fps)
if (previewLayer.RespondsToSelector(new Selector("connection")))
{
if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
{
var perf1 = PerformanceCounter.Start ();
NSError lockForConfigErr = null;
captureDevice.LockForConfiguration (out lockForConfigErr);
if (lockForConfigErr == null)
{
captureDevice.ActiveVideoMinFrameDuration = new CMTime (1, 10);
captureDevice.UnlockForConfiguration ();
}
PerformanceCounter.Stop (perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms");
}
else
previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);
}
#if __UNIFIED__
previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#else
previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#endif
previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));
layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
layerView.Layer.AddSublayer(previewLayer);
this.AddSubview(layerView);
ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);
if (overlayView != null)
{
this.AddSubview (overlayView);
this.BringSubviewToFront (overlayView);
//overlayView.LayoutSubviews ();
}
session.StartRunning ();
Console.WriteLine ("RUNNING!!!");
//output.AlwaysDiscardsLateVideoFrames = true;
Console.WriteLine("SetupCamera Finished");
//session.AddOutput (output);
//session.StartRunning ();
if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
{
NSError err = null;
if (captureDevice.LockForConfiguration(out err))
{
if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
if (captureDevice.IsExposureModeSupported (AVCaptureExposureMode.ContinuousAutoExposure))
captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
if (captureDevice.IsWhiteBalanceModeSupported (AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
else if (captureDevice.IsWhiteBalanceModeSupported (AVCaptureWhiteBalanceMode.AutoWhiteBalance))
captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
if (captureDevice.FocusPointOfInterestSupported)
captureDevice.FocusPointOfInterest = new CGPoint(0.5f, 0.5f);
if (captureDevice.ExposurePointOfInterestSupported)
captureDevice.ExposurePointOfInterest = new CGPoint (0.5f, 0.5f);
captureDevice.UnlockForConfiguration();
}
else
Console.WriteLine("Failed to Lock for Config: " + err.Description);
}
return true;
}
public void DidRotate(UIInterfaceOrientation orientation)
{
ResizePreview (orientation);
this.LayoutSubviews ();
// if (overlayView != null)
// overlayView.LayoutSubviews ();
}
public void ResizePreview (UIInterfaceOrientation orientation)
{
if (previewLayer == null)
return;
previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
if (previewLayer.RespondsToSelector (new Selector ("connection")) && previewLayer.Connection != null)
{
switch (orientation)
{
case UIInterfaceOrientation.LandscapeLeft:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
break;
case UIInterfaceOrientation.LandscapeRight:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
break;
case UIInterfaceOrientation.Portrait:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
break;
case UIInterfaceOrientation.PortraitUpsideDown:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown;
break;
}
}
}
public void Focus(CGPoint pointOfInterest)
{
//Get the device
if (AVMediaType.Video == null)
return;
var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
if (device == null)
return;
//See if it supports focusing on a point
if (device.FocusPointOfInterestSupported && !device.AdjustingFocus)
{
NSError err = null;
//Lock device to config
if (device.LockForConfiguration(out err))
{
Console.WriteLine("Focusing at point: " + pointOfInterest.X + ", " + pointOfInterest.Y);
//Focus at the point touched
device.FocusPointOfInterest = pointOfInterest;
device.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
device.UnlockForConfiguration();
}
}
}
#region IZXingScanner implementation
public void StartScanning (Action<Result> scanResultHandler, MobileBarcodeScanningOptions options = null)
{
if (!analyzing)
analyzing = true;
if (!stopped)
return;
Setup ();
this.options = options;
this.resultCallback = scanResultHandler;
Console.WriteLine("StartScanning");
this.InvokeOnMainThread(() => {
if (!SetupCaptureSession())
{
//Setup 'simulated' view:
Console.WriteLine("Capture Session FAILED");
}
if (Runtime.Arch == Arch.SIMULATOR)
{
var simView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
simView.BackgroundColor = UIColor.LightGray;
simView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
this.InsertSubview(simView, 0);
}
});
stopped = false;
}
public void StopScanning()
{
if (stopped)
return;
Console.WriteLine("Stopping...");
//Try removing all existing outputs prior to closing the session
try
{
while (session.Outputs.Length > 0)
session.RemoveOutput (session.Outputs [0]);
}
catch { }
//Try to remove all existing inputs prior to closing the session
try
{
while (session.Inputs.Length > 0)
session.RemoveInput (session.Inputs [0]);
}
catch { }
if (session.Running)
session.StopRunning();
stopped = true;
}
public void PauseAnalysis ()
{
analyzing = false;
}
public void ResumeAnalysis ()
{
analyzing = true;
}
public void Torch (bool on)
{
try
{
NSError err;
var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
if (device.HasFlash || device.HasTorch) {
device.LockForConfiguration(out err);
if (on)
{
if (device.HasTorch)
device.TorchMode = AVCaptureTorchMode.On;
if (device.HasFlash)
device.FlashMode = AVCaptureFlashMode.On;
}
else
{
if (device.HasTorch)
device.TorchMode = AVCaptureTorchMode.Off;
if (device.HasFlash)
device.FlashMode = AVCaptureFlashMode.Off;
}
device.UnlockForConfiguration();
}
device = null;
torch = on;
}
catch { }
}
public void ToggleTorch()
{
Torch(!IsTorchOn);
}
public void AutoFocus ()
{
//Doesn't do much on iOS :(
}
public void AutoFocus (int x, int y)
{
//Doesn't do much on iOS :(
}
public string TopText { get;set; }
public string BottomText { get;set; }
public UIView CustomOverlayView { get; set; }
public bool UseCustomOverlayView { get; set; }
public MobileBarcodeScanningOptions ScanningOptions { get { return options; } }
public bool IsAnalyzing { get { return analyzing; } }
public bool IsTorchOn { get { return torch; } }
bool? hasTorch = null;
public bool HasTorch {
get {
if (hasTorch.HasValue)
return hasTorch.Value;
var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
hasTorch = device.HasFlash || device.HasTorch;
return hasTorch.Value;
}
}
#endregion
public static bool SupportsAllRequestedBarcodeFormats(IEnumerable<BarcodeFormat> formats)
{
var supported = new List<BarcodeFormat> () {
BarcodeFormat.AZTEC, BarcodeFormat.CODE_128, BarcodeFormat.CODE_39,
BarcodeFormat.CODE_93, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8,
BarcodeFormat.PDF_417, BarcodeFormat.QR_CODE, BarcodeFormat.UPC_E,
BarcodeFormat.DATA_MATRIX, BarcodeFormat.ITF,
BarcodeFormat.All_1D
};
return !formats.Any (f => !supported.Contains (f));
}
BarcodeFormat ZXingBarcodeFormatFromAVCaptureBarcodeFormat(string avMetadataObjectType)
{
if (avMetadataObjectType == AVMetadataObject.TypeAztecCode)
return BarcodeFormat.AZTEC;
if (avMetadataObjectType == AVMetadataObject.TypeCode128Code)
return BarcodeFormat.CODE_128;
if (avMetadataObjectType == AVMetadataObject.TypeCode39Code)
return BarcodeFormat.CODE_39;
if (avMetadataObjectType == AVMetadataObject.TypeCode39Mod43Code)
return BarcodeFormat.CODE_39;
if (avMetadataObjectType == AVMetadataObject.TypeCode93Code)
return BarcodeFormat.CODE_93;
if (avMetadataObjectType == AVMetadataObject.TypeEAN13Code)
return BarcodeFormat.EAN_13;
if (avMetadataObjectType == AVMetadataObject.TypeEAN8Code)
return BarcodeFormat.EAN_8;
if (avMetadataObjectType == AVMetadataObject.TypePDF417Code)
return BarcodeFormat.PDF_417;
if (avMetadataObjectType == AVMetadataObject.TypeQRCode)
return BarcodeFormat.QR_CODE;
if (avMetadataObjectType == AVMetadataObject.TypeUPCECode)
return BarcodeFormat.UPC_E;
return BarcodeFormat.QR_CODE;
}
#if __UNIFIED__
AVMetadataObjectType AVCaptureBarcodeFormatFromZXingBarcodeFormat(BarcodeFormat zxingBarcodeFormat)
{
AVMetadataObjectType formats = AVMetadataObjectType.None;
switch (zxingBarcodeFormat)
{
case BarcodeFormat.AZTEC:
formats |= AVMetadataObjectType.AztecCode;
break;
case BarcodeFormat.CODE_128:
formats |= AVMetadataObjectType.Code128Code;
break;
case BarcodeFormat.CODE_39:
formats |= AVMetadataObjectType.Code39Code;
formats |= AVMetadataObjectType.Code39Mod43Code;
break;
case BarcodeFormat.CODE_93:
formats |= AVMetadataObjectType.Code93Code;
break;
case BarcodeFormat.EAN_13:
formats |= AVMetadataObjectType.EAN13Code;
break;
case BarcodeFormat.EAN_8:
formats |= AVMetadataObjectType.EAN8Code;
break;
case BarcodeFormat.PDF_417:
formats |= AVMetadataObjectType.PDF417Code;
break;
case BarcodeFormat.QR_CODE:
formats |= AVMetadataObjectType.QRCode;
break;
case BarcodeFormat.UPC_E:
formats |= AVMetadataObjectType.UPCECode;
break;
case BarcodeFormat.All_1D:
formats |= AVMetadataObjectType.UPCECode;
formats |= AVMetadataObjectType.EAN13Code;
formats |= AVMetadataObjectType.EAN8Code;
formats |= AVMetadataObjectType.Code39Code;
formats |= AVMetadataObjectType.Code39Mod43Code;
formats |= AVMetadataObjectType.Code93Code;
break;
case BarcodeFormat.DATA_MATRIX:
formats |= AVMetadataObjectType.DataMatrixCode;
break;
case BarcodeFormat.ITF:
formats |= AVMetadataObjectType.ITF14Code;
break;
case BarcodeFormat.CODABAR:
case BarcodeFormat.MAXICODE:
case BarcodeFormat.MSI:
case BarcodeFormat.PLESSEY:
case BarcodeFormat.RSS_14:
case BarcodeFormat.RSS_EXPANDED:
case BarcodeFormat.UPC_A:
//TODO: Throw exception?
break;
}
return formats;
}
#else
string[] AVCaptureBarcodeFormatFromZXingBarcodeFormat(BarcodeFormat zxingBarcodeFormat)
{
List<string> formats = new List<string> ();
switch (zxingBarcodeFormat)
{
case BarcodeFormat.AZTEC:
formats.Add (AVMetadataObject.TypeAztecCode);
break;
case BarcodeFormat.CODE_128:
formats.Add (AVMetadataObject.TypeCode128Code);
break;
case BarcodeFormat.CODE_39:
formats.Add (AVMetadataObject.TypeCode39Code);
formats.Add (AVMetadataObject.TypeCode39Mod43Code);
break;
case BarcodeFormat.CODE_93:
formats.Add (AVMetadataObject.TypeCode93Code);
break;
case BarcodeFormat.EAN_13:
formats.Add (AVMetadataObject.TypeEAN13Code);
break;
case BarcodeFormat.EAN_8:
formats.Add (AVMetadataObject.TypeEAN8Code);
break;
case BarcodeFormat.PDF_417:
formats.Add (AVMetadataObject.TypePDF417Code);
break;
case BarcodeFormat.QR_CODE:
formats.Add (AVMetadataObject.TypeQRCode);
break;
case BarcodeFormat.UPC_E:
formats.Add (AVMetadataObject.TypeUPCECode);
break;
case BarcodeFormat.All_1D:
formats.Add (AVMetadataObject.TypeUPCECode);
formats.Add (AVMetadataObject.TypeEAN13Code);
formats.Add (AVMetadataObject.TypeEAN8Code);
formats.Add (AVMetadataObject.TypeCode39Code);
formats.Add (AVMetadataObject.TypeCode39Mod43Code);
formats.Add (AVMetadataObject.TypeCode93Code);
break;
case BarcodeFormat.DATA_MATRIX:
formats.Add (AVMetadataObject.TypeDataMatrixCode);
break;
case BarcodeFormat.ITF:
formats.Add (AVMetadataObject.TypeITF14Code);
break;
case BarcodeFormat.CODABAR:
case BarcodeFormat.MAXICODE:
case BarcodeFormat.MSI:
case BarcodeFormat.PLESSEY:
case BarcodeFormat.RSS_14:
case BarcodeFormat.RSS_EXPANDED:
case BarcodeFormat.UPC_A:
//TODO: Throw exception?
break;
}
return formats.ToArray();
}
#endif
}
class CaptureDelegate : AVCaptureMetadataOutputObjectsDelegate
{
public CaptureDelegate (Action<IEnumerable<AVMetadataObject>> onCapture)
{
OnCapture = onCapture;
}
public Action<IEnumerable<AVMetadataObject>> OnCapture { get;set; }
public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection)
{
if (OnCapture != null && metadataObjects != null)
OnCapture (metadataObjects);
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
namespace MtgDb.Info
{
public class RenderHtml
{
public static string Name(string text)
{
string html = HttpUtility.HtmlEncode(text);
html = html.Replace ("(R)","®");
return html;
}
/// <summary>
/// Text the specified text.
/// </summary>
/// <param name="text">Text.</param>
public static string Text(string text)
{
string html = HttpUtility.HtmlEncode(text);
html = html.Replace("{Tap}", "<i class='symbol symbol_T'></i>");
html = html.Replace("ocT", "<i class='symbol symbol_T'></i>");
html = html.Replace("{Untap}", "<i class='symbol symbol_UT'></i>");
html = html.Replace("{White}", "<i class='symbol symbol_W'></i>");
html = html.Replace("{Blue}", "<i class='symbol symbol_U'></i>");
html = html.Replace("{Black}", "<i class='symbol symbol_B'></i>");
html = html.Replace("{Red}", "<i class='symbol symbol_R'></i>");
html = html.Replace("{Green}", "<i class='symbol symbol_G'></i>");
html = html.Replace("{W}", "<i class='symbol symbol_W'></i>");
html = html.Replace("{U}", "<i class='symbol symbol_U'></i>");
html = html.Replace("{B}", "<i class='symbol symbol_B'></i>");
html = html.Replace("{R}", "<i class='symbol symbol_R'></i>");
html = html.Replace("{G}", "<i class='symbol symbol_G'></i>");
html = html.Replace("oW", "<i class='symbol symbol_W'></i>");
html = html.Replace("oU", "<i class='symbol symbol_U'></i>");
html = html.Replace("oB", "<i class='symbol symbol_B'></i>");
html = html.Replace("oR", "<i class='symbol symbol_R'></i>");
html = html.Replace("oG", "<i class='symbol symbol_G'></i>");
html = html.Replace("{Red or White}", "<i class='symbol symbol_RW'></i>");
html = html.Replace("{Black or Green}", "<i class='symbol symbol_BG'></i>");
html = html.Replace("{Blue or Black}", "<i class='symbol symbol_UB'></i>");
html = html.Replace("{Green or White}", "<i class='symbol symbol_GW'></i>");
html = html.Replace("{Phyrexian White}", "<i class='symbol symbol_WP'></i>");
html = html.Replace("{Phyrexian Blue}", "<i class='symbol symbol_UP'></i>");
html = html.Replace("{Phyrexian Black}", "<i class='symbol symbol_BP'></i>");
html = html.Replace("{Phyrexian Red}", "<i class='symbol symbol_RP'></i>");
html = html.Replace("{Phyrexian Green}", "<i class='symbol symbol_GP'></i>");
html = html.Replace("{Two or White}", "<i class='symbol symbol_2W'></i>");
html = html.Replace("{Two or Blue}", "<i class='symbol symbol_2U'></i>");
html = html.Replace("{Two or Black}", "<i class='symbol symbol_2B'></i>");
html = html.Replace("{Two or Red}", "<i class='symbol symbol_2R'></i>");
html = html.Replace("{Two or Green}", "<i class='symbol symbol_2G'></i>");
html = html.Replace("{Snow}", "<i class='symbol symbol_S'></i>");
html = html.Replace("{1}", "<i class='symbol symbol_1'></i>");
html = html.Replace("{2}", "<i class='symbol symbol_2'></i>");
html = html.Replace("{3}", "<i class='symbol symbol_3'></i>");
html = html.Replace("{4}", "<i class='symbol symbol_4'></i>");
html = html.Replace("{5}", "<i class='symbol symbol_5'></i>");
html = html.Replace("{6}", "<i class='symbol symbol_6'></i>");
html = html.Replace("{7}", "<i class='symbol symbol_7'></i>");
html = html.Replace("{8}", "<i class='symbol symbol_8'></i>");
html = html.Replace("{9}", "<i class='symbol symbol_9'></i>");
html = html.Replace("{10}", "<i class='symbol symbol_10'></i>");
html = html.Replace("{11}", "<i class='symbol symbol_11'></i>");
html = html.Replace("{12}", "<i class='symbol symbol_12'></i>");
html = html.Replace("{13}", "<i class='symbol symbol_13'></i>");
html = html.Replace("{14}", "<i class='symbol symbol_14'></i>");
html = html.Replace("{15}", "<i class='symbol symbol_15'></i>");
html = html.Replace("{16}", "<i class='symbol symbol_16'></i>");
html = html.Replace("{17}", "<i class='symbol symbol_17'></i>");
html = html.Replace("{18}", "<i class='symbol symbol_18'></i>");
html = html.Replace("{19}", "<i class='symbol symbol_19'></i>");
html = html.Replace("{20}", "<i class='symbol symbol_20'></i>");
html = html.Replace("{100}", "<i class='symbol symbol_100'></i>");
html = html.Replace("{Infinite}", "<i class='symbol symbol_Infinite'></i>");
html = html.Replace("{1/2}", "<i class='symbol symbol_Half'></i>");
html = html.Replace("o1", "<i class='symbol symbol_1'></i>");
html = html.Replace("o2", "<i class='symbol symbol_2'></i>");
html = html.Replace("o3", "<i class='symbol symbol_3'></i>");
html = html.Replace("o4", "<i class='symbol symbol_4'></i>");
html = html.Replace("o5", "<i class='symbol symbol_5'></i>");
html = html.Replace("{Variable Colorless}", "<i class='symbol symbol_X'></i>");
html = html.Replace("oX", "<i class='symbol symbol_X'></i>");
html = html.Replace("{Half a Red}", "<i class='symbol symbol_HR'></i>");
html = html.Replace ("\n","<br/>");
html = html.Replace ("(R)","®");
html = html.Replace ("1/2","½");
html = html.Replace ("(","<em>(");
html = html.Replace (")",")</em>");
return html;
}
/// <summary>
/// Color the specified text.
/// </summary>
/// <param name="text">Text.</param>
public static string Color(string text)
{
string html = text.ToLower();
html = html.Replace ("none", "<span class='label label-color color-n'>Colorless</span>");
html = html.Replace ("white", "<span class='label label-color color-w'>White</span>");
html = html.Replace ("blue", "<span class='label label-color color-u'>Blue</span>");
html = html.Replace ("black", "<span class='label label-color color-b'>Black</span>");
html = html.Replace ("red", "<span class='label label-color color-r'>Red</span>");
html = html.Replace ("green", "<span class='label label-color color-g'>Green</span>");
return html;
}
/// <summary>
/// Mana the specified text.
/// </summary>
/// <param name="text">Text.</param>
public static string Mana(string text)
{
if (text == null || text == "")
return text;
text = HttpUtility.HtmlEncode(text.ToLower ());
StringBuilder html = new StringBuilder ();
Dictionary<string, string> syntax = new Dictionary<string, string> ();
syntax.Add ("#", "<i class='symbol symbol_{0}'></i>");
syntax.Add ("x", "<i class='symbol symbol_X'></i>");
syntax.Add ("y", "<i class='symbol symbol_Y'></i>");
syntax.Add ("z", "<i class='symbol symbol_Z'></i>");
syntax.Add ("w", "<i class='symbol symbol_W'></i>");
syntax.Add ("u", "<i class='symbol symbol_U'></i>");
syntax.Add ("b", "<i class='symbol symbol_B'></i>");
syntax.Add ("r", "<i class='symbol symbol_R'></i>");
syntax.Add ("g", "<i class='symbol symbol_G'></i>");
syntax.Add ("{r/w}", "<i class='symbol symbol_RW'></i>");
syntax.Add ("{g/r}", "<i class='symbol symbol_GR'></i>");
syntax.Add ("{b/r}", "<i class='symbol symbol_BR'></i>");
syntax.Add ("{u/w}", "<i class='symbol symbol_UW'></i>");
syntax.Add ("{u/r}", "<i class='symbol symbol_UR'></i>");
syntax.Add ("{b/g}", "<i class='symbol symbol_BG'></i>");
syntax.Add ("{g/w}", "<i class='symbol symbol_GW'></i>");
syntax.Add("{b/u}", "<i class='symbol symbol_BU'></i>");
syntax.Add ("{wp}", "<i class='symbol symbol_WP'></i>");
syntax.Add ("{up}", "<i class='symbol symbol_UP'></i>");
syntax.Add ("{bp}", "<i class='symbol symbol_BP'></i>");
syntax.Add ("{rp}", "<i class='symbol symbol_RP'></i>");
syntax.Add ("{gp}", "<i class='symbol symbol_GP'></i>");
syntax.Add ("{2/w}", "<i class='symbol symbol_2W'></i>");
syntax.Add ("{2/u}", "<i class='symbol symbol_2U'></i>");
syntax.Add ("{2/b}", "<i class='symbol symbol_2B'></i>");
syntax.Add ("{2/r}", "<i class='symbol symbol_2R'></i>");
syntax.Add ("{2/g}", "<i class='symbol symbol_2G'></i>");
string key = "";
string number = "";
Stack<string> stack = new Stack<string> ();
foreach (char c in text)
{
if (stack.Count == 0)
{
if (Char.IsNumber (c))
{
//done: 89096 double digit mana cost
number += c.ToString ();
continue;
}
else if(number != "")
{
html.Append (string.Format (syntax ["#"], number));
number = "";
}
if(syntax.ContainsKey(c.ToString()))
{
html.Append (syntax [c.ToString()]);
continue;
}
}
if (c == '{') {
stack.Push ("{");
key = "{";
}
else if (c == '}')
{
key += "}";
stack.Pop ();
if(syntax.ContainsKey(key))
{
html.Append (syntax[key]);
key = "";
}
else
{
html.Append (key);
key = "";
}
}
else if(stack.Count > 0)
{
key += c.ToString ();
}
else
{
html.Append (c.ToString());
}
}
if (html.Length < 1) {
html.Append (string.Format("<i class='symbol symbol_{0}'></i>",text));
}
html.Append (key);
return html.ToString();
}
}
}
| |
using System;
using System.Net.Mime;
using System.Text;
using System.Net;
using System.IO;
namespace WDK.API.CouchDb
{
public class ConnectionBase
{
#region " Variables and Properties "
private string _host = "localhost";
public string host
{
get
{
return _host;
}
set
{
_host = value;
}
}
private int _port = 5984;
public int port
{
get
{
return _port;
}
set
{
_port = value;
}
}
public string username
{
get;
set;
}
public string password
{
get;
set;
}
public bool useSsl
{
get;
set;
}
#endregion
#region " GetUrl "
public string getUrl()
{
var url = "http://";
if (useSsl)
{
url = "https://";
}
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
{
url += username + ":" + password + "@";
}
if (useSsl)
{
url += host;
}
else
{
url += host + ":" + port;
}
return url;
}
#endregion
#region " DoRequest "
/// <summary>
/// Internal helper to make an HTTP request and return the response.
/// Throws an exception in the event of any kind of failure.
/// Overloaded - use the other version if you need to post data with the request.
/// </summary>
/// <param name="url">The URL</param>
/// <param name="method">The method, e.g. "GET"</param>
/// <param name="isBinaryResult"> </param>
/// <returns>The server's response</returns>
protected ServerResponse doRequest(string url, string method, bool isBinaryResult)
{
return doRequest(url, method, null, null, isBinaryResult);
}
/// <summary>
/// Internal helper to make an HTTP request and return the response.
/// Throws an exception in the event of any kind of failure.
/// Overloaded - use the other version if no post data is required.
/// </summary>
/// <param name="url">The URL</param>
/// <param name="method">The method, e.g. "GET"</param>
/// <param name="postdata">Data to be posted with the request, or null if not required.</param>
/// <param name="contenttype">The content type to send, or null if not required.</param>
/// <param name="isBinaryResult"> </param>
/// <returns>The server's response</returns>
protected ServerResponse doRequest(string url, string method, string postdata, string contenttype, bool isBinaryResult)
{
var request = WebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = method;
// Set an infinite timeout on this for now, because executing a temporary view (for example) can take a very long time
request.Timeout = System.Threading.Timeout.Infinite;
// Set authorization header
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
{
if (request.Headers == null)
{
request.Headers = new WebHeaderCollection();
}
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
}
if (contenttype != null)
{
request.ContentType = contenttype;
}
if (postdata != null)
{
var bytes = Encoding.UTF8.GetBytes(postdata);
request.ContentLength = bytes.Length;
using (var ps = request.GetRequestStream())
{
ps.Write(bytes, 0, bytes.Length);
}
}
}
HttpWebResponse response = null;
try
{
if (request != null)
{
response = request.GetResponse() as HttpWebResponse;
}
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
var result = new ServerResponse();
if (response == null) return result;
result.contentType = response.ContentType;
if (isBinaryResult)
{
result.isBinaryResult = true;
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var responseStream = response.GetResponseStream();
if (responseStream == null) continue;
var read = responseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
result.contentBytes = ms.ToArray();
break;
}
ms.Write(buffer, 0, read);
}
}
result.contentString = Convert.ToBase64String(result.contentBytes);
}
else
{
result.isBinaryResult = false;
result.contentBytes = null;
var encode = Encoding.GetEncoding("utf-8");
using (var reader = new StreamReader(response.GetResponseStream(), encode))
{
result.contentString = reader.ReadToEnd();
}
}
return result;
}
protected ServerResponse doRequest(string url, string method, WebHeaderCollection headers, string postdata, string contenttype, bool isBinaryResult)
{
var request = WebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = method;
// Set an infinite timeout on this for now, because executing a temporary view (for example) can take a very long time
request.Timeout = System.Threading.Timeout.Infinite;
request.Headers = headers;
// Set authorization header
if ((request.Headers != null) && (request.Headers[HttpRequestHeader.Authorization] != null))
{
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
{
if (request.Headers == null)
{
request.Headers = new WebHeaderCollection();
}
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
}
}
if (contenttype != null)
{
request.ContentType = contenttype;
}
if (postdata != null)
{
var bytes = Encoding.UTF8.GetBytes(postdata);
request.ContentLength = bytes.Length;
using (var ps = request.GetRequestStream())
{
ps.Write(bytes, 0, bytes.Length);
}
}
}
HttpWebResponse response = null;
try
{
if (request != null)
{
response = request.GetResponse() as HttpWebResponse;
}
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
var result = new ServerResponse();
if (response == null) return result;
result.contentType = response.ContentType;
if (isBinaryResult)
{
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var responseStream = response.GetResponseStream();
if (responseStream == null) continue;
var read = responseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
result.contentBytes = ms.ToArray();
break;
}
ms.Write(buffer, 0, read);
}
}
result.contentString = Convert.ToBase64String(result.contentBytes);
}
else
{
result.isBinaryResult = false;
result.contentBytes = null;
using (var reader = new StreamReader(response.GetResponseStream()))
{
result.contentString = reader.ReadToEnd();
}
}
return result;
}
#endregion
#region " SanitizeOutput "
protected string sanitizeInOutput(string content)
{
var result = content;
result = result.Replace(@"\\r\\n", "THIS_IS_NOT_A_RETURN_NEWLINE");
result = result.Replace(@"\\n", "THIS_IS_NOT_A_NEWLINE");
result = result.Replace(@"\\t", "THIS_IS_NOT_A_TAB");
return result;
}
protected string sanitizeOutOutput(string content)
{
var result = content;
result = result.Trim('"');
result = result.Replace(@"\r\n", Environment.NewLine);
result = result.Replace(@"\n", Environment.NewLine);
result = result.Replace(@"\t", "\t");
result = result.Replace("THIS_IS_NOT_A_NEWLINE", @"\n");
result = result.Replace("THIS_IS_NOT_A_RETURN_NEWLINE", @"\r\n");
result = result.Replace("THIS_IS_NOT_A_TAB", @"\t");
return result;
}
#endregion
}
}
| |
// 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>KeywordPlanCampaignKeyword</c> resource.</summary>
public sealed partial class KeywordPlanCampaignKeywordName : gax::IResourceName, sys::IEquatable<KeywordPlanCampaignKeywordName>
{
/// <summary>The possible contents of <see cref="KeywordPlanCampaignKeywordName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
CustomerKeywordPlanCampaignKeyword = 1,
}
private static gax::PathTemplate s_customerKeywordPlanCampaignKeyword = new gax::PathTemplate("customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}");
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignKeywordName"/> 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="KeywordPlanCampaignKeywordName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KeywordPlanCampaignKeywordName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KeywordPlanCampaignKeywordName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignKeywordName"/> with the pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="KeywordPlanCampaignKeywordName"/> constructed from the provided ids.
/// </returns>
public static KeywordPlanCampaignKeywordName FromCustomerKeywordPlanCampaignKeyword(string customerId, string keywordPlanCampaignKeywordId) =>
new KeywordPlanCampaignKeywordName(ResourceNameType.CustomerKeywordPlanCampaignKeyword, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanCampaignKeywordId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignKeywordId, nameof(keywordPlanCampaignKeywordId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with
/// pattern <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </returns>
public static string Format(string customerId, string keywordPlanCampaignKeywordId) =>
FormatCustomerKeywordPlanCampaignKeyword(customerId, keywordPlanCampaignKeywordId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with
/// pattern <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </returns>
public static string FormatCustomerKeywordPlanCampaignKeyword(string customerId, string keywordPlanCampaignKeywordId) =>
s_customerKeywordPlanCampaignKeyword.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignKeywordId, nameof(keywordPlanCampaignKeywordId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/> 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}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="KeywordPlanCampaignKeywordName"/> if successful.</returns>
public static KeywordPlanCampaignKeywordName Parse(string keywordPlanCampaignKeywordName) =>
Parse(keywordPlanCampaignKeywordName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/> 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}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// 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="KeywordPlanCampaignKeywordName"/> if successful.</returns>
public static KeywordPlanCampaignKeywordName Parse(string keywordPlanCampaignKeywordName, bool allowUnparsed) =>
TryParse(keywordPlanCampaignKeywordName, allowUnparsed, out KeywordPlanCampaignKeywordName 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="KeywordPlanCampaignKeywordName"/>
/// 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}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanCampaignKeywordName"/>, 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 keywordPlanCampaignKeywordName, out KeywordPlanCampaignKeywordName result) =>
TryParse(keywordPlanCampaignKeywordName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/>
/// 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}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// 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="KeywordPlanCampaignKeywordName"/>, 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 keywordPlanCampaignKeywordName, bool allowUnparsed, out KeywordPlanCampaignKeywordName result)
{
gax::GaxPreconditions.CheckNotNull(keywordPlanCampaignKeywordName, nameof(keywordPlanCampaignKeywordName));
gax::TemplatedResourceName resourceName;
if (s_customerKeywordPlanCampaignKeyword.TryParseName(keywordPlanCampaignKeywordName, out resourceName))
{
result = FromCustomerKeywordPlanCampaignKeyword(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(keywordPlanCampaignKeywordName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private KeywordPlanCampaignKeywordName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string keywordPlanCampaignKeywordId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
KeywordPlanCampaignKeywordId = keywordPlanCampaignKeywordId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KeywordPlanCampaignKeywordName"/> class from the component parts
/// of pattern <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
public KeywordPlanCampaignKeywordName(string customerId, string keywordPlanCampaignKeywordId) : this(ResourceNameType.CustomerKeywordPlanCampaignKeyword, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanCampaignKeywordId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignKeywordId, nameof(keywordPlanCampaignKeywordId)))
{
}
/// <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>KeywordPlanCampaignKeyword</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string KeywordPlanCampaignKeywordId { 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.CustomerKeywordPlanCampaignKeyword: return s_customerKeywordPlanCampaignKeyword.Expand(CustomerId, KeywordPlanCampaignKeywordId);
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 KeywordPlanCampaignKeywordName);
/// <inheritdoc/>
public bool Equals(KeywordPlanCampaignKeywordName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KeywordPlanCampaignKeywordName a, KeywordPlanCampaignKeywordName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KeywordPlanCampaignKeywordName a, KeywordPlanCampaignKeywordName b) => !(a == b);
}
public partial class KeywordPlanCampaignKeyword
{
/// <summary>
/// <see cref="KeywordPlanCampaignKeywordName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal KeywordPlanCampaignKeywordName ResourceNameAsKeywordPlanCampaignKeywordName
{
get => string.IsNullOrEmpty(ResourceName) ? null : KeywordPlanCampaignKeywordName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="KeywordPlanCampaignName"/>-typed view over the <see cref="KeywordPlanCampaign"/> resource name
/// property.
/// </summary>
internal KeywordPlanCampaignName KeywordPlanCampaignAsKeywordPlanCampaignName
{
get => string.IsNullOrEmpty(KeywordPlanCampaign) ? null : KeywordPlanCampaignName.Parse(KeywordPlanCampaign, allowUnparsed: true);
set => KeywordPlanCampaign = value?.ToString() ?? "";
}
}
}
| |
// 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: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System;
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.IO
{
[Serializable]
public abstract class Stream : MarshalByRefObject, IDisposable
{
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int _DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
[NonSerialized]
private ReadWriteTask _activeReadWriteTask;
[NonSerialized]
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
[Pure]
get;
}
public virtual bool CanTimeout
{
[Pure]
get
{
return false;
}
}
public abstract bool CanWrite
{
[Pure]
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public virtual int WriteTimeout
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// If we go down this branch, it means there are
// no bytes left in this stream.
// Ideally we would just return Task.CompletedTask here,
// but CopyToAsync(Stream, int, CancellationToken) was already
// virtual at the time this optimization was introduced. So
// if it does things like argument validation (checking if destination
// is null and throwing an exception), then await fooStream.CopyToAsync(null)
// would no longer throw if there were no bytes left. On the other hand,
// we also can't roll our own argument validation and return Task.CompletedTask,
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(destination != null);
Contract.Requires(bufferSize > 0);
Contract.Requires(CanRead);
Contract.Requires(destination.CanWrite);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
try
{
while (true)
{
int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
if (bytesRead > bufferSize) bufferSize = bytesRead;
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
finally
{
Array.Clear(buffer, 0, bufferSize); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// No bytes left in stream
// Call the other overload with a bufferSize of 1,
// in case it's made virtual in the future
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
int highwaterMark = 0;
try
{
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
if (read > highwaterMark) highwaterMark = read;
destination.Write(buffer, 0, read);
}
}
finally
{
Array.Clear(buffer, 0, highwaterMark); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup starting in V2.
public virtual void Close()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
Contract.Ensures(Contract.Result<WaitHandle>() != null);
return new ManualResetEvent(false);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanRead) __Error.ReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
var readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (!readTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<Int32>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
// preconditions in async methods that await.
Debug.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) =>
{
Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Contract.Requires(readWriteTask != null);
Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
internal byte[] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
private ExecutionContext _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
public ReadWriteTask(
bool isRead,
bool apm,
Func<object, int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Contract.Requires(function != null);
Contract.Requires(stream != null);
Contract.Requires(buffer != null);
Contract.EndContractBlock();
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture();
base.AddCompletionAction(this);
}
}
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
var callback = rwc._callback;
rwc._callback = null;
callback(rwc);
}
private static ContextCallback s_invokeAsyncCallback;
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
else
{
_context = null;
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
ExecutionContext.Run(context, invokeAsyncCallback, this);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < 256);
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
if (callback != null)
{
callback(asyncResult);
}
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
if (callback != null)
{
callback(asyncResult);
}
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
[Serializable]
private sealed class NullStream : Stream
{
internal NullStream() { }
public override bool CanRead
{
[Pure]
get { return true; }
}
public override bool CanWrite
{
[Pure]
get { return true; }
}
public override bool CanSeek
{
[Pure]
get { return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return 0; }
set { }
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanRead) __Error.ReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
return BlockingEndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
BlockingEndWrite(asyncResult);
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
return 0;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
if (nullReadTask == null)
s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
return nullReadTask;
}
private static Task<int> s_nullReadTask;
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
internal sealed class SynchronousAsyncResult : IAsyncResult
{
private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
private bool _endXxxCalled;
private Int32 _bytesRead;
internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject)
{
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
internal SynchronousAsyncResult(Object asyncStateObject)
{
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite)
{
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted
{
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
public WaitHandle AsyncWaitHandle
{
get
{
return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
public Object AsyncState
{
get { return _stateObject; }
}
public bool CompletedSynchronously
{
get { return true; }
}
internal void ThrowIfError()
{
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static Int32 EndRead(IAsyncResult asyncResult)
{
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndReadCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndWriteCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
[Serializable]
internal sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
Contract.EndContractBlock();
_stream = stream;
}
public override bool CanRead
{
[Pure]
get { return _stream.CanRead; }
}
public override bool CanWrite
{
[Pure]
get { return _stream.CanWrite; }
}
public override bool CanSeek
{
[Pure]
get { return _stream.CanSeek; }
}
public override bool CanTimeout
{
[Pure]
get
{
return _stream.CanTimeout;
}
}
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
}
}
}
public override int ReadTimeout
{
get
{
return _stream.ReadTimeout;
}
set
{
_stream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _stream.WriteTimeout;
}
set
{
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock (_stream)
{
try
{
_stream.Close();
}
finally
{
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock (_stream)
{
try
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock (_stream)
_stream.Flush();
}
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
lock (_stream)
return _stream.Read(bytes, offset, count);
}
public override int ReadByte()
{
lock (_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
lock (_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock (_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock (_stream)
_stream.Write(bytes, offset, count);
}
public override void WriteByte(byte b)
{
lock (_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
lock (_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using Tester;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace UnitTests.ActivationsLifeCycleTests
{
public class ActivationCollectorTests : OrleansTestingBase, IDisposable
{
private static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromSeconds(10);
private static readonly TimeSpan DEFAULT_IDLE_TIMEOUT = DEFAULT_COLLECTION_QUANTUM + TimeSpan.FromSeconds(1);
private static readonly TimeSpan WAIT_TIME = DEFAULT_IDLE_TIMEOUT.Multiply(3.0);
private TestCluster testCluster;
private ILogger logger;
private void Initialize(TimeSpan collectionAgeLimit, TimeSpan quantum)
{
GlobalConfiguration.ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT = false;
var builder = new TestClusterBuilder(1);
builder.ConfigureLegacyConfiguration(legacy =>
{
var config = legacy.ClusterConfiguration;
config.Globals.CollectionQuantum = quantum;
config.Globals.Application.SetDefaultCollectionAgeLimit(collectionAgeLimit);
config.Globals.Application.SetCollectionAgeLimit(typeof(IdleActivationGcTestGrain2), DEFAULT_IDLE_TIMEOUT);
config.Globals.Application.SetCollectionAgeLimit(typeof(BusyActivationGcTestGrain2), DEFAULT_IDLE_TIMEOUT);
config.Globals.Application.SetCollectionAgeLimit(typeof(CollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain), TimeSpan.FromSeconds(12));
});
testCluster = builder.Build();
testCluster.Deploy();
this.logger = this.testCluster.Client.ServiceProvider.GetRequiredService<ILogger<ActivationCollectorTests>>();
}
private void Initialize(TimeSpan collectionAgeLimit)
{
Initialize(collectionAgeLimit, DEFAULT_COLLECTION_QUANTUM);
}
private void Initialize()
{
Initialize(TimeSpan.Zero, DEFAULT_COLLECTION_QUANTUM);
}
public void Dispose()
{
GlobalConfiguration.ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT = true;
testCluster?.StopAllSilos();
testCluster = null;
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorForceCollection()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int grainCount = 1000;
var fullGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
List<Task> tasks = new List<Task>();
logger.Info("ActivationCollectorForceCollection: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
await Task.Delay(TimeSpan.FromSeconds(5));
var grain = this.testCluster.GrainFactory.GetGrain<IManagementGrain>(0);
await grain.ForceActivationCollection(TimeSpan.FromSeconds(4));
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
await grain.ForceActivationCollection(TimeSpan.FromSeconds(4));
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldCollectIdleActivations()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int grainCount = 1000;
var fullGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
List<Task> tasks = new List<Task>();
logger.Info("IdleActivationCollectorShouldCollectIdleActivations: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(grainCount, activationsCreated);
logger.Info("IdleActivationCollectorShouldCollectIdleActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldNotCollectBusyActivations()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int idleGrainCount = 500;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain1).FullName;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>();
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
bool[] quit = new bool[]{ false };
Func<Task> busyWorker =
async () =>
{
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
foreach (var g in busyGrains)
tasks1.Add(g.Nop());
await Task.WhenAll(tasks1);
}
};
Task.Run(busyWorker).Ignore();
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain1).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
quit[0] = true;
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ManualCollectionShouldNotCollectBusyActivations()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
TimeSpan shortIdleTimeout = TimeSpan.FromSeconds(1);
const int idleGrainCount = 500;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain1).FullName;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>();
logger.Info("ManualCollectionShouldNotCollectBusyActivations: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
bool[] quit = new bool[]{ false };
Func<Task> busyWorker =
async () =>
{
logger.Info("ManualCollectionShouldNotCollectBusyActivations: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
foreach (var g in busyGrains)
tasks1.Add(g.Nop());
await Task.WhenAll(tasks1);
}
};
Task.Run(busyWorker).Ignore();
logger.Info("ManualCollectionShouldNotCollectBusyActivations: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("ManualCollectionShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", shortIdleTimeout.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(shortIdleTimeout);
TimeSpan everything = TimeSpan.FromMinutes(10);
logger.Info("ManualCollectionShouldNotCollectBusyActivations: triggering manual collection (timespan is {0} sec).", everything.TotalSeconds);
IManagementGrain mgmtGrain = this.testCluster.GrainFactory.GetGrain<IManagementGrain>(0);
await mgmtGrain.ForceActivationCollection(everything);
logger.Info("ManualCollectionShouldNotCollectBusyActivations: waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
quit[0] = true;
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration()
{
//make sure default value won't cause activation collection during wait time
var defaultCollectionAgeLimit = WAIT_TIME.Multiply(2);
Initialize(defaultCollectionAgeLimit);
const int grainCount = 1000;
var fullGrainTypeName = typeof(IdleActivationGcTestGrain2).FullName;
List<Task> tasks = new List<Task>();
logger.Info("ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
IIdleActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain2>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(grainCount, activationsCreated);
logger.Info("ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration()
{
//make sure default value won't cause activation collection during wait time
var defaultCollectionAgeLimit = WAIT_TIME.Multiply(2);
Initialize(defaultCollectionAgeLimit);
const int idleGrainCount = 500;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain2).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain2).FullName;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain2> busyGrains = new List<IBusyActivationGcTestGrain2>();
logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain2>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
bool[] quit = new bool[]{ false };
Func<Task> busyWorker =
async () =>
{
logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
foreach (var g in busyGrains)
tasks1.Add(g.Nop());
await Task.WhenAll(tasks1);
}
};
Task.Run(busyWorker).Ignore();
logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain2>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("IdleActivationCollectorShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain2).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
quit[0] = true;
}
[Fact(Skip = "Flaky test. Needs to be investigated."), TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldNotCollectBusyStatelessWorkers()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
// the purpose of this test is to determine whether idle stateless worker activations are properly identified by the activation collector.
// in this test, we:
//
// 1. setup the test.
// 2. activate a set of grains by sending a burst of messages to each one. the purpose of the burst is to ensure that multiple activations are used.
// 3. verify that multiple activations for each grain have been created.
// 4. periodically send a message to each grain, ensuring that only one activation remains busy. each time we check the activation id and compare it against the activation id returned by the previous grain call. initially, these may not be identical but as the other activations become idle and are collected, there will be only one activation servicing these calls.
// 5. wait long enough for idle activations to be collected.
// 6. verify that only one activation is still active per grain.
// 7. ensure that test steps 2-6 are repeatable.
const int grainCount = 1;
var grainTypeName = typeof(StatelessWorkerActivationCollectorTestGrain1).FullName;
const int burstLength = 1000;
List<Task> tasks0 = new List<Task>();
List<IStatelessWorkerActivationCollectorTestGrain1> grains = new List<IStatelessWorkerActivationCollectorTestGrain1>();
for (var i = 0; i < grainCount; ++i)
{
IStatelessWorkerActivationCollectorTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IStatelessWorkerActivationCollectorTestGrain1>(Guid.NewGuid());
grains.Add(g);
}
bool[] quit = new bool[] { false };
bool[] matched = new bool[grainCount];
string[] activationIds = new string[grainCount];
Func<int, Task> workFunc =
async index =>
{
// (part of) 4. periodically send a message to each grain...
// take a grain and call Delay to keep it busy.
IStatelessWorkerActivationCollectorTestGrain1 g = grains[index];
await g.Delay(DEFAULT_IDLE_TIMEOUT.Divide(2));
// identify the activation and record whether it matches the activation ID last reported. it probably won't match in the beginning but should always converge on a match as other activations get collected.
string aid = await g.IdentifyActivation();
logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: identified {0}", aid);
matched[index] = aid == activationIds[index];
activationIds[index] = aid;
};
Func<Task> workerFunc =
async () =>
{
// (part of) 4. periodically send a message to each grain...
logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
for (int index = 0; index < grains.Count; ++index)
{
if (quit[0])
{
break;
}
tasks1.Add(workFunc(index));
}
await Task.WhenAll(tasks1);
}
};
// setup (1) ends here.
for (int i = 0; i < 2; ++i)
{
// 2. activate a set of grains...
this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: activating {0} stateless worker grains (run #{1}).", grainCount, i);
foreach (var g in grains)
{
for (int j = 0; j < burstLength; ++j)
{
// having the activation delay will ensure that one activation cannot serve all requests that we send to it, making it so that additional activations will be created.
tasks0.Add(g.Delay(TimeSpan.FromMilliseconds(10)));
}
}
await Task.WhenAll(tasks0);
// 3. verify that multiple activations for each grain have been created.
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, grainTypeName);
Assert.True(activationsCreated > grainCount, string.Format("more than {0} activations should have been created; got {1} instead", grainCount, activationsCreated));
// 4. periodically send a message to each grain...
this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: grains activated; sending heartbeat to {0} stateless worker grains.", grainCount);
Task workerTask = Task.Run(workerFunc);
// 5. wait long enough for idle activations to be collected.
this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// 6. verify that only one activation is still active per grain.
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, grainTypeName);
// signal that the worker task should stop and wait for it to finish.
quit[0] = true;
await workerTask;
quit[0] = false;
Assert.Equal(grainCount, busyActivationsNotCollected);
// verify that we matched activation ids in the final iteration of step 4's loop.
for (int index = 0; index < grains.Count; ++index)
{
Assert.True(matched[index], string.Format("activation ID of final subsequent heartbeats did not match for grain {0}", grains[index]));
}
}
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Performance"), TestCategory("CorePerf")]
public async Task ActivationCollectorShouldNotCauseMessageLoss()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int idleGrainCount = 0;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain1).FullName;
const int burstCount = 100;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>();
logger.Info("ActivationCollectorShouldNotCauseMessageLoss: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await busyGrains[0].EnableBurstOnCollection(burstCount);
logger.Info("ActivationCollectorShouldNotCauseMessageLoss: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("ActivationCollectorShouldNotCauseMessageLoss: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain1).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldCollectByCollectionSpecificAgeLimitForTwelveSeconds()
{
var waitTime = TimeSpan.FromSeconds(30);
var defaultCollectionAge = waitTime.Multiply(2);
//make sure defaultCollectionAge value won't cause activation collection in wait time
Initialize(defaultCollectionAge);
const int grainCount = 1000;
// CollectionAgeLimit = 12 seconds
var fullGrainTypeName = typeof(CollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain).FullName;
List<Task> tasks = new List<Task>();
logger.Info("ActivationCollectorShouldCollectByCollectionSpecificAgeLimit: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
ICollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain g = this.testCluster.GrainFactory.GetGrain<ICollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(grainCount, activationsCreated);
logger.Info("ActivationCollectorShouldCollectByCollectionSpecificAgeLimit: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
// Some time is required for GC to collect all of the Grains)
await Task.Delay(waitTime);
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Search.Models
{
using Common;
public partial class DataSource : IResourceWithETag
{
/// <summary>
/// Creates a new DataSource to connect to an Azure SQL database.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the Azure SQL database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureSql(
string name,
string sqlConnectionString,
string tableOrViewName,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
return CreateSqlDataSource(name, sqlConnectionString, tableOrViewName, description, null, deletionDetectionPolicy);
}
/// <summary>
/// Creates a new DataSource to connect to an Azure SQL database with change detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the Azure SQL database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureSql(
string name,
string sqlConnectionString,
string tableOrViewName,
DataChangeDetectionPolicy changeDetectionPolicy,
string description = null)
{
Throw.IfArgumentNull(changeDetectionPolicy, nameof(changeDetectionPolicy));
return CreateSqlDataSource(name, sqlConnectionString, tableOrViewName, description, changeDetectionPolicy);
}
/// <summary>
/// Creates a new DataSource to connect to an Azure SQL database with change detection and deletion detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the Azure SQL database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource. Note that only high watermark change detection is
/// allowed for Azure SQL when deletion detection is enabled.</param>
/// <param name="deletionDetectionPolicy">The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureSql(
string name,
string sqlConnectionString,
string tableOrViewName,
HighWaterMarkChangeDetectionPolicy changeDetectionPolicy,
DataDeletionDetectionPolicy deletionDetectionPolicy,
string description = null)
{
Throw.IfArgumentNull(changeDetectionPolicy, nameof(changeDetectionPolicy));
Throw.IfArgumentNull(deletionDetectionPolicy, nameof(deletionDetectionPolicy));
return CreateSqlDataSource(name, sqlConnectionString, tableOrViewName, description, changeDetectionPolicy, deletionDetectionPolicy);
}
/// <summary>
/// Creates a new DataSource to connect to a VM-hosted SQL Server database.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the SQL Server database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource SqlServerOnAzureVM(
string name,
string sqlConnectionString,
string tableOrViewName,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
return AzureSql(name, sqlConnectionString, tableOrViewName, deletionDetectionPolicy, description);
}
/// <summary>
/// Creates a new DataSource to connect to a VM-hosted SQL Server database with change detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the SQL Server database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource SqlServerOnAzureVM(
string name,
string sqlConnectionString,
string tableOrViewName,
DataChangeDetectionPolicy changeDetectionPolicy,
string description = null)
{
return AzureSql(name, sqlConnectionString, tableOrViewName, changeDetectionPolicy, description);
}
/// <summary>
/// Creates a new DataSource to connect to a VM-hosted SQL Server database with change detection and deletion detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the SQL Server database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource. Note that only high watermark change detection is
/// allowed for SQL Server when deletion detection is enabled.</param>
/// <param name="deletionDetectionPolicy">The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource SqlServerOnAzureVM(
string name,
string sqlConnectionString,
string tableOrViewName,
HighWaterMarkChangeDetectionPolicy changeDetectionPolicy,
DataDeletionDetectionPolicy deletionDetectionPolicy,
string description = null)
{
return AzureSql(name, sqlConnectionString, tableOrViewName, changeDetectionPolicy, deletionDetectionPolicy, description);
}
/// <summary>
/// Creates a new DataSource to connect to a DocumentDb database.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="documentDbConnectionString">The connection string for the DocumentDb database. It must follow this format:
/// "AccountName|AccountEndpoint=[your account name or endpoint];AccountKey=[your account key];Database=[your database name]"</param>
/// <param name="collectionName">The name of the collection from which to read documents.</param>
/// <param name="query">Optional. A query that is applied to the collection when reading documents.</param>
/// <param name="useChangeDetection">Optional. Indicates whether to use change detection when indexing. Default is true.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource DocumentDb(
string name,
string documentDbConnectionString,
string collectionName,
string query = null,
bool useChangeDetection = true,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(collectionName, nameof(collectionName));
Throw.IfArgumentNullOrEmpty(documentDbConnectionString, nameof(documentDbConnectionString));
return new DataSource()
{
Type = DataSourceType.DocumentDb,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = collectionName,
Query = query
},
Credentials = new DataSourceCredentials(documentDbConnectionString),
DataChangeDetectionPolicy = useChangeDetection ? new HighWaterMarkChangeDetectionPolicy("_ts") : null,
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
/// <summary>
/// Creates a new DataSource to connect to an Azure Blob container.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="storageConnectionString">The connection string for the Azure Storage account. It must follow this format:
/// "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key];" Note that HTTPS is required.</param>
/// <param name="containerName">The name of the container from which to read blobs.</param>
/// <param name="pathPrefix">Optional. If specified, the datasource will include only blobs with names starting with this prefix. This is
/// useful when blobs are organized into "virtual folders", for example.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureBlobStorage(
string name,
string storageConnectionString,
string containerName,
string pathPrefix = null,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(containerName, nameof(containerName));
Throw.IfArgumentNullOrEmpty(storageConnectionString, nameof(storageConnectionString));
return new DataSource()
{
Type = DataSourceType.AzureBlob,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = containerName,
Query = pathPrefix
},
Credentials = new DataSourceCredentials(storageConnectionString),
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
/// <summary>
/// Creates a new DataSource to connect to an Azure Table.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="storageConnectionString">The connection string for the Azure Storage account. It must follow this format:
/// "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key];" Note that HTTPS is required.</param>
/// <param name="tableName">The name of the table from which to read rows.</param>
/// <param name="query">Optional. A query that is applied to the table when reading rows.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureTableStorage(
string name,
string storageConnectionString,
string tableName,
string query = null,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(tableName, nameof(tableName));
Throw.IfArgumentNullOrEmpty(storageConnectionString, nameof(storageConnectionString));
return new DataSource()
{
Type = DataSourceType.AzureTable,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = tableName,
Query = query
},
Credentials = new DataSourceCredentials(storageConnectionString),
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
private static DataSource CreateSqlDataSource(
string name,
string sqlConnectionString,
string tableOrViewName,
string description,
DataChangeDetectionPolicy changeDetectionPolicy = null,
DataDeletionDetectionPolicy deletionDetectionPolicy = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(tableOrViewName, nameof(tableOrViewName));
Throw.IfArgumentNullOrEmpty(sqlConnectionString, nameof(sqlConnectionString));
return new DataSource()
{
Type = DataSourceType.AzureSql,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = tableOrViewName
},
Credentials = new DataSourceCredentials(sqlConnectionString),
DataChangeDetectionPolicy = changeDetectionPolicy,
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Twoclass.overload.errorverifier.errorverifier
{
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Twoclass.overload.overload023.overload023
{
// <Title>Overloaded methods in 2 classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Base
{
public int this[string x]
{
set
{
Test.Status = 2;
}
}
}
public class Derived : Base
{
public int this[int x]
{
set
{
Test.Status = 4;
}
}
}
public class FurtherDerived : Derived
{
public int this[dynamic x]
{
set
{
Test.Status = 3;
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new FurtherDerived();
dynamic d = int.MaxValue;
try
{
b[d] = 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Twoclass.overload.overload037.overload037
{
// <Title>Overloaded methods in 2 classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Base
{
public int this[string x]
{
set
{
Test.Status = 2;
}
}
}
public class Derived : Base
{
public int this[int x]
{
set
{
Test.Status = 4;
}
}
}
public class FurtherDerived : Derived
{
public int this[object x]
{
set
{
Test.Status = 3;
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new FurtherDerived();
dynamic d = int.MaxValue;
try
{
b[d] = 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
| |
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 SmartLMS.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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
var expected = PlatformDetection.IsWindowsNanoServer ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Normal; // For some reason we're BelowNormal initially on Nano
Assert.Equal(expected, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
// Try twice, since it's possible that the system clock could be adjusted backwards between when we snapshot it
// and when the process ends, but vanishingly unlikely that would happen twice.
DateTime timeBeforeProcessStart = DateTime.MaxValue;
Process p = null;
for (int i = 0; i <= 1; i++)
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
// we subtract ms from the begin time to account for it.
timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25);
p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
if (p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart)
break;
}
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart,
$@"TestExitTime is incorrect. " +
$@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " +
$@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " +
$@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " +
$@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}");
}
[Fact]
public void StartTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StartTime);
}
[Fact]
public void TestId()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HasExited);
}
[Fact]
public void Kill_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Kill());
}
[Fact]
public void TestMachineName()
{
CreateDefaultProcess();
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void MachineName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MachineName);
}
[Fact]
public void TestMainModule()
{
Process p = Process.GetCurrentProcess();
// On UAP casing may not match - we use Path.GetFileName(exePath) instead of kernel32!GetModuleFileNameEx which is not available on UAP
Func<string, string> normalize = PlatformDetection.IsUap ?
(Func<string, string>)((s) => s.ToLowerInvariant()) :
(s) => s;
Assert.True(p.Modules.Count > 0);
Assert.Equal(normalize(HostRunnerName), normalize(p.MainModule.ModuleName));
Assert.EndsWith(normalize(HostRunnerName), normalize(p.MainModule.FileName));
Assert.Equal(normalize(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName)), normalize(p.MainModule.ToString()));
}
[Fact]
public void TestMaxWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX.
public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet);
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1);
}
[Fact]
public void TestMinWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX.
public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet);
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr baseAddr = pModule.BaseAddress;
IntPtr entryAddr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestNonpagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakVirtualMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakWorkingSet64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPrivateMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestVirtualMemorySize64()
{
CreateDefaultProcess();
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestWorkingSet64()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WorkingSet64);
}
[Fact]
public void TestProcessorTime()
{
CreateDefaultProcess();
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime);
}
[Fact]
public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime);
}
[Fact]
public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime);
}
[Fact]
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(1);
for (int i = 0; i < 2; i++)
{
Process p = CreateProcessPortable(RemotelyInvokable.ReadLine);
Assert.Throws<InvalidOperationException>(() => p.StartTime);
DateTime testStartTime = DateTime.Now;
p.StartInfo.RedirectStandardInput = true;
p.Start();
Assert.Equal(p.StartTime, p.StartTime);
DateTime processStartTime = p.StartTime;
using (StreamWriter writer = p.StandardInput)
{
writer.WriteLine("start");
}
Assert.True(p.WaitForExit(WaitInMS));
DateTime testEndTime = DateTime.Now;
bool hasTimeChanged = testEndTime < testStartTime;
if (i != 0 || !hasTimeChanged)
{
Assert.InRange(processStartTime, testStartTime - allowedWindow, testEndTime + allowedWindow);
break;
}
}
}
[Fact]
public void ExitTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ExitTime);
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
CreateDefaultProcess();
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
CreateDefaultProcess();
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix.
public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled);
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true);
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestPriorityClassWindows()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Theory]
[InlineData((ProcessPriorityClass)0)]
[InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)]
public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass)
{
var process = new Process();
Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass);
}
[Fact]
public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityClass);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestProcessName()
{
CreateDefaultProcess();
string expected = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner;
Assert.Equal(Path.GetFileNameWithoutExtension(expected), Path.GetFileNameWithoutExtension(_process.ProcessName), StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void ProcessName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ProcessName);
}
[Fact]
public void TestSafeHandle()
{
CreateDefaultProcess();
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SafeHandle);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestSessionId()
{
CreateDefaultProcess();
uint sessionId;
#if TargetsWindows
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
#else
sessionId = (uint)Interop.getsid(_process.Id);
#endif
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void SessionId_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId =
#if TargetsWindows
Interop.GetCurrentProcessId();
#else
Interop.getpid();
#endif
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestGetProcessById()
{
CreateDefaultProcess();
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void GetProcesseses_NullMachineName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null));
}
[Fact]
public void GetProcesses_EmptyMachineName_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcesses(""));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(".", process.MachineName));
}
public static IEnumerable<object[]> MachineName_TestData()
{
string currentProcessName = Process.GetCurrentProcess().MachineName;
yield return new object[] { currentProcessName };
yield return new object[] { "." };
yield return new object[] { Dns.GetHostName() };
}
public static IEnumerable<object[]> MachineName_Remote_TestData()
{
yield return new object[] { Guid.NewGuid().ToString("N") };
yield return new object[] { "\\" + Guid.NewGuid().ToString("N") };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(machineName, process.MachineName));
}
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows.
public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName)
{
try
{
GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName);
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
Assert.Empty(Process.GetProcessesByName(processName));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, ""));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[ActiveIssue("https://github.com/dotnet/corefx/issues/18212", TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Retrieving information about local processes is not supported on uap")]
public void TestProcessOnRemoteMachineWindows()
{
Process currentProccess = Process.GetCurrentProcess();
void TestRemoteProccess(Process remoteProcess)
{
Assert.Equal(currentProccess.Id, remoteProcess.Id);
Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
try
{
TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1"));
TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single());
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
public void StartInfo_GetFileName_ReturnsExpected()
{
Process process = CreateProcessLong();
process.Start();
// Processes are not hosted by dotnet in the full .NET Framework.
string expectedFileName = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : RunnerName;
Assert.Equal(expectedFileName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = CreateProcessLong();
process.Start();
// .NET Core fixes a bug where Process.StartInfo for a unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
var startInfo = new ProcessStartInfo();
process.StartInfo = startInfo;
Assert.Equal(startInfo, process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo());
}
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetGet_ReturnsExpected()
{
var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) };
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
[Fact]
public void StartInfo_SetNull_ThrowsArgumentNullException()
{
var process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
[Fact]
public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = Process.GetCurrentProcess();
// .NET Core fixes a bug where Process.StartInfo for an unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Non applicable for uap - RemoteInvoke works differently")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
[InlineData("\"\" b \"\"", ",b,")]
[InlineData("\"\"\"\" b c", "\",b,c")]
[InlineData("c\"\"\"\" b \"\"\\", "c\",b,\\")]
[InlineData("\"\"c \"\"b\"\" d\"\\", "c,b,d\\")]
[InlineData("\"\"a\"\" b d", "a,b,d")]
[InlineData("b d \"\"a\"\" ", "b,d,a")]
[InlineData("\\\"\\\"a\\\"\\\" b d", "\"\"a\"\",b,d")]
[InlineData("b d \\\"\\\"a\\\"\\\"", "b,d,\"\"a\"\"")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
var options = new RemoteInvokeOptions
{
Start = true,
StartInfo = new ProcessStartInfo { RedirectStandardOutput = true }
};
using (RemoteInvokeHandle handle = RemoteInvokeRaw((Func<string, string, string, int>)RemotelyInvokable.ConcatThreeArguments, inputArguments, options))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
[Fact]
public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StandardInput);
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestStartWithMissingFile(bool fullPath)
{
string path = Guid.NewGuid().ToString("N");
if (fullPath)
{
path = Path.GetFullPath(path);
Assert.True(Path.IsPathRooted(path));
}
else
{
Assert.False(Path.IsPathRooted(path));
}
Assert.False(File.Exists(path));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void Start_NullStartInfo_ThrowsArgumentNullExceptionException()
{
AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null));
}
[Fact]
public void Start_EmptyFileName_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardOutput = false,
StandardOutputEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardError = false,
StandardErrorEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var process = new Process();
process.StartInfo.FileName = "Nothing";
process.Dispose();
Assert.Throws<ObjectDisposedException>(() => process.Start());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.HandleCount > 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX
public void TestHandleCount_OSX()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.Equal(0, p.HandleCount);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void HandleCountChanges()
{
RemoteInvoke(() =>
{
Process p = Process.GetCurrentProcess();
int handleCount = p.HandleCount;
using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
{
p.Refresh();
int secondHandleCount = p.HandleCount;
Assert.True(handleCount < secondHandleCount);
handleCount = secondHandleCount;
}
p.Refresh();
int thirdHandleCount = p.HandleCount;
Assert.True(thirdHandleCount < handleCount);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HandleCount_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HandleCount);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
CreateDefaultProcess();
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}
[Fact]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
CreateDefaultProcess();
Assert.Empty(_process.MainWindowTitle);
Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle);
}
[Fact]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
CreateDefaultProcess();
Assert.False(_process.CloseMainWindow());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException_WindowsNonUap()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow());
}
[Fact]
// CloseMainWindow is a no-op and always returns false on Unix or Uap.
public void CloseMainWindow_NotStarted_ReturnsFalse_UapOrNonWindows()
{
if (PlatformDetection.IsWindows && !PlatformDetection.IsUap)
return;
var process = new Process();
Assert.False(process.CloseMainWindow());
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS
[Fact]
public void TestRespondingWindows()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void Responding_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Responding);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestNonpagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakWorkingSet()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPrivateMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestWorkingSet()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
#pragma warning disable 0618
Assert.True(_process.WorkingSet >= 0);
#pragma warning restore 0618
return;
}
#pragma warning disable 0618
Assert.True(_process.WorkingSet > 0);
#pragma warning restore 0618
}
[Fact]
public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.WorkingSet);
#pragma warning restore 0618
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartInvalidNamesTest()
{
Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain"));
Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = "thisDomain";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, userName, password, domain); // This writes junk to the Console but with this overload, we can't prevent that.
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
Assert.True(p.WaitForExit(WaitInMS));
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = Environment.UserDomainName;
string arguments = "-xml testResults.xml";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, arguments, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(arguments, p.StartInfo.Arguments);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithDuplicatePassword()
{
var startInfo = new ProcessStartInfo()
{
FileName = "exe",
UserName = "dummyUser",
PasswordInClearText = "Value",
Password = AsSecureString("Value"),
UseShellExecute = false
};
var process = new Process() { StartInfo = startInfo };
AssertExtensions.Throws<ArgumentException>(null, () => process.Start());
}
[Fact]
public void TestLongProcessIsWorking()
{
// Sanity check for CreateProcessLong
Process p = CreateProcessLong();
p.Start();
Thread.Sleep(500);
Assert.False(p.HasExited);
p.Kill();
p.WaitForExit();
Assert.True(p.HasExited);
}
private string GetCurrentProcessName()
{
return $"{Process.GetCurrentProcess().ProcessName}.exe";
}
private SecureString AsSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (var ch in str)
{
secureString.AppendChar(ch);
}
return secureString;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// </summary>
internal enum DataPriorityType : int
{
/// <summary>
/// This indicate that the data will be sent without priority consideration.
/// Large data objects will be fragmented so that each fragmented piece can
/// fit into one message.
/// </summary>
Default = 0,
/// <summary>
/// PromptResponse may be sent with or without priority considerations.
/// Large data objects will be fragmented so that each fragmented piece can
/// fit into one message.
/// </summary>
PromptResponse = 1,
}
#region Sending Data
/// <summary>
/// DataStructure used by different remoting protocol /
/// DataStructures to pass data to transport manager.
/// This class holds the responsibility of fragmenting.
/// This allows to fragment an object only once and
/// send the fragments to various machines thus saving
/// fragmentation time.
/// </summary>
internal class PrioritySendDataCollection
{
#region Private Data
// actual data store(s) to store priority based data and its
// corresponding sync objects to provide thread safety.
private SerializedDataStream[] _dataToBeSent;
// array of sync objects, one for each element in _dataToBeSent
private object[] _dataSyncObjects;
// fragmentor used to serialize & fragment objects added to this collection.
private Fragmentor _fragmentor;
// callbacks used if no data is available at any time.
// these callbacks are used to notify when data becomes available under
// suc circumstances.
private OnDataAvailableCallback _onDataAvailableCallback;
private readonly SerializedDataStream.OnDataAvailableCallback _onSendCollectionDataAvailable;
private bool _isHandlingCallback;
private readonly object _readSyncObject = new object();
/// <summary>
/// Callback that is called once a fragmented data is available to send.
/// </summary>
/// <param name="data">
/// Fragmented object that can be sent to the remote end.
/// </param>
/// <param name="priorityType">
/// Priority stream to which <paramref name="data"/> belongs to.
/// </param>
internal delegate void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType);
#endregion
#region Constructor
/// <summary>
/// Constructs a PrioritySendDataCollection object.
/// </summary>
internal PrioritySendDataCollection()
{
_onSendCollectionDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable);
}
#endregion
#region Internal Methods / Properties
internal Fragmentor Fragmentor
{
get
{
return _fragmentor;
}
set
{
Dbg.Assert(value != null, "Fragmentor cannot be null.");
_fragmentor = value;
// create serialized streams using fragment size.
string[] names = Enum.GetNames(typeof(DataPriorityType));
_dataToBeSent = new SerializedDataStream[names.Length];
_dataSyncObjects = new object[names.Length];
for (int i = 0; i < names.Length; i++)
{
_dataToBeSent[i] = new SerializedDataStream(_fragmentor.FragmentSize);
_dataSyncObjects[i] = new object();
}
}
}
/// <summary>
/// Adds data to this collection. The data is fragmented in this method
/// before being stored into the collection. So the calling thread
/// will get affected, if it tries to add a huge object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">
/// data to be added to the collection. Caller should make sure this is not
/// null.
/// </param>
/// <param name="priority">
/// Priority of the data.
/// </param>
internal void Add<T>(RemoteDataObject<T> data, DataPriorityType priority)
{
Dbg.Assert(data != null, "Cannot send null data object");
Dbg.Assert(_fragmentor != null, "Fragmentor cannot be null while adding objects");
Dbg.Assert(_dataToBeSent != null, "Serialized streams are not initialized");
// make sure the only one object is fragmented and added to the collection
// at any give time. This way the order of fragment is maintained
// in the SendDataCollection(s).
lock (_dataSyncObjects[(int)priority])
{
_fragmentor.Fragment<T>(data, _dataToBeSent[(int)priority]);
}
}
/// <summary>
/// Adds data to this collection. The data is fragmented in this method
/// before being stored into the collection. So the calling thread
/// will get affected, if it tries to add a huge object.
///
/// The data is added with Default priority.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">
/// data to be added to the collection. Caller should make sure this is not
/// null.
/// </param>
internal void Add<T>(RemoteDataObject<T> data)
{
Add<T>(data, DataPriorityType.Default);
}
/// <summary>
/// Clears fragmented objects stored so far in this collection.
/// </summary>
internal void Clear()
{
/*
NOTE: Error paths during initialization can cause _dataSyncObjects to be null
causing an unhandled exception in finalize and a process crash.
Verify arrays and dataToBeSent objects before referencing.
*/
if (_dataSyncObjects != null && _dataToBeSent != null)
{
const int promptResponseIndex = (int)DataPriorityType.PromptResponse;
const int defaultIndex = (int)DataPriorityType.Default;
lock (_dataSyncObjects[promptResponseIndex])
{
if (_dataToBeSent[promptResponseIndex] != null)
{
_dataToBeSent[promptResponseIndex].Dispose();
_dataToBeSent[promptResponseIndex] = null;
}
}
lock (_dataSyncObjects[defaultIndex])
{
if (_dataToBeSent[defaultIndex] != null)
{
_dataToBeSent[defaultIndex].Dispose();
_dataToBeSent[defaultIndex] = null;
}
}
}
}
/// <summary>
/// Gets the fragment or if no fragment is available registers the callback which
/// gets called once a fragment is available. These 2 steps are performed in a
/// synchronized way.
///
/// While getting a fragment the following algorithm is used:
/// 1. If this is the first time or if the last fragment read is an EndFragment,
/// then a new set of fragments is chosen based on the implicit priority.
/// PromptResponse is higher in priority order than default.
/// 2. If last fragment read is not an EndFragment, then next fragment is chosen from
/// the priority collection as the last fragment. This will ensure fragments
/// are sent in order.
/// </summary>
/// <param name="callback">
/// Callback to call once data is available. (This will be used if no data is currently
/// available).
/// </param>
/// <param name="priorityType">
/// Priority stream to which the returned object belongs to, if any.
/// If the call does not return any data, the value of this "out" parameter
/// is undefined.
/// </param>
/// <returns>
/// A FragmentRemoteObject if available, otherwise null.
/// </returns>
internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback,
out DataPriorityType priorityType)
{
lock (_readSyncObject)
{
priorityType = DataPriorityType.Default;
// send data from which ever stream that has data directly.
byte[] result = null;
result = _dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(_onSendCollectionDataAvailable);
priorityType = DataPriorityType.PromptResponse;
if (result == null)
{
result = _dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(_onSendCollectionDataAvailable);
priorityType = DataPriorityType.Default;
}
// no data to return..so register the callback.
if (result == null)
{
// register callback.
_onDataAvailableCallback = callback;
}
return result;
}
}
private void OnDataAvailable(byte[] data, bool isEndFragment)
{
lock (_readSyncObject)
{
// PromptResponse and Default priority collection can both raise at the
// same time. This will take care of the situation.
if (_isHandlingCallback)
{
return;
}
_isHandlingCallback = true;
}
if (_onDataAvailableCallback != null)
{
DataPriorityType prType;
// now get the fragment and call the callback..
byte[] result = ReadOrRegisterCallback(_onDataAvailableCallback, out prType);
if (result != null)
{
// reset the onDataAvailableCallback so that we dont notify
// multiple times. we are resetting before actually calling
// the callback to make sure the caller calls ReadOrRegisterCallback
// at a later point and we dont loose the callback handle.
OnDataAvailableCallback realCallback = _onDataAvailableCallback;
_onDataAvailableCallback = null;
realCallback(result, prType);
}
}
_isHandlingCallback = false;
}
#endregion
}
#endregion
#region Receiving Data
/// <summary>
/// DataStructure used by remoting transport layer to store
/// data being received from the wire for a particular priority
/// stream.
/// </summary>
internal class ReceiveDataCollection : IDisposable
{
#region tracer
[TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")]
private static readonly PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager");
#endregion
#region Private Data
// fragmentor used to defragment objects added to this collection.
private readonly Fragmentor _defragmentor;
// this stream holds incoming data..this stream doesn't know anything
// about fragment boundaries.
private MemoryStream _pendingDataStream;
// the idea is to maintain 1 whole object.
// 1 whole object may contain any number of fragments. blob from
// each fragment is written to this stream.
private MemoryStream _dataToProcessStream;
private long _currentObjectId;
private long _currentFrgId;
// max deserialized object size in bytes
private int? _maxReceivedObjectSize;
private int _totalReceivedObjectSizeSoFar;
private readonly bool _isCreateByClientTM;
// this indicates if any off sync fragments can be ignored
// this gets reset (to false) upon receiving the next "start" fragment along the stream
private bool _canIgnoreOffSyncFragments = false;
// objects need to cleanly release resources without
// locking entire processing logic.
private readonly object _syncObject;
private bool _isDisposed;
// holds the number of threads that are currently in
// ProcessRawData method. This might happen only for
// ServerCommandTransportManager case where the command
// is run in the same thread that runs ProcessRawData (to avoid
// thread context switch).
private int _numberOfThreadsProcessing;
// limits the numberOfThreadsProcessing variable.
private int _maxNumberOfThreadsToAllowForProcessing = 1;
#endregion
#region Delegates
/// <summary>
/// Callback that is called once a deserialized object is available.
/// </summary>
/// <param name="data">
/// Deserialized object that can be processed.
/// </param>
internal delegate void OnDataAvailableCallback(RemoteDataObject<PSObject> data);
#endregion
#region Constructor
/// <summary>
/// </summary>
/// <param name="defragmentor">
/// Defragmentor used to deserialize an object.
/// </param>
/// <param name="createdByClientTM">
/// True if a client transport manager created this collection.
/// This is used to generate custom messages for server and client.
/// </param>
internal ReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM)
{
Dbg.Assert(defragmentor != null, "ReceiveDataCollection needs a defragmentor to work with");
// Memory streams created with an unsigned byte array provide a non-resizable stream view
// of the data, and can only be written to. When using a byte array, you can neither append
// to nor shrink the stream, although you might be able to modify the existing contents
// depending on the parameters passed into the constructor. Empty memory streams are
// resizable, and can be written to and read from.
_pendingDataStream = new MemoryStream();
_syncObject = new object();
_defragmentor = defragmentor;
_isCreateByClientTM = createdByClientTM;
}
#endregion
#region Internal Methods / Properties
/// <summary>
/// Limits the deserialized object size received from a remote machine.
/// </summary>
internal int? MaximumReceivedObjectSize
{
set { _maxReceivedObjectSize = value; }
}
/// <summary>
/// This might be needed only for ServerCommandTransportManager case
/// where the command is run in the same thread that runs ProcessRawData
/// (to avoid thread context switch). By default this class supports
/// only one thread in ProcessRawData.
/// </summary>
internal void AllowTwoThreadsToProcessRawData()
{
_maxNumberOfThreadsToAllowForProcessing = 2;
}
/// <summary>
/// Prepares the collection for a stream connect
/// When reconnecting from same client, its possible that fragment stream get interrupted if server is dropping data
/// When connecting from a new client, its possible to get trailing fragments of a previously partially transmitted object
/// Logic based on this flag, ensures such offsync/trailing fragments get ignored until the next full object starts flowing.
/// </summary>
internal void PrepareForStreamConnect()
{
_canIgnoreOffSyncFragments = true;
}
/// <summary>
/// Process data coming from the transport. This method analyses the data
/// and if an object can be created, it creates one and calls the
/// <paramref name="callback"/> with the deserialized object. This method
/// does not assume all fragments to be available. So if not enough fragments are
/// available it will simply return..
/// </summary>
/// <param name="data">
/// Data to process.
/// </param>
/// <param name="callback">
/// Callback to call once a complete deserialized object is available.
/// </param>
/// <returns>
/// Defragmented Object if any, otherwise null.
/// </returns>
/// <exception cref="PSRemotingTransportException">
/// 1. Fragment Ids not in sequence
/// 2. Object Ids does not match
/// 3. The current deserialized object size of the received data exceeded
/// allowed maximum object size. The current deserialized object size is {0}.
/// Allowed maximum object size is {1}.
/// </exception>
/// <remarks>
/// Might throw other exceptions as the deserialized object is handled here.
/// </remarks>
internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback)
{
Dbg.Assert(data != null, "Cannot process null data");
Dbg.Assert(callback != null, "Callback cannot be null");
lock (_syncObject)
{
if (_isDisposed)
{
return;
}
_numberOfThreadsProcessing++;
if (_numberOfThreadsProcessing > _maxNumberOfThreadsToAllowForProcessing)
{
Dbg.Assert(false, "Multiple threads are not allowed in ProcessRawData.");
}
}
try
{
_pendingDataStream.Write(data, 0, data.Length);
// this do loop will process one deserialized object.
// using a loop allows to process multiple objects within
// the same packet
while (true)
{
if (_pendingDataStream.Length <= FragmentedRemoteObject.HeaderLength)
{
// there is not enough data to be processed.
s_baseTracer.WriteLine("Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.",
_pendingDataStream.Length, FragmentedRemoteObject.HeaderLength);
return;
}
byte[] dataRead = _pendingDataStream.ToArray();
// there is enough data to process here. get the fragment header
long objectId = FragmentedRemoteObject.GetObjectId(dataRead, 0);
if (objectId <= 0)
{
throw new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdCannotBeLessThanZero);
}
long fragmentId = FragmentedRemoteObject.GetFragmentId(dataRead, 0);
bool sFlag = FragmentedRemoteObject.GetIsStartFragment(dataRead, 0);
bool eFlag = FragmentedRemoteObject.GetIsEndFragment(dataRead, 0);
int blobLength = FragmentedRemoteObject.GetBlobLength(dataRead, 0);
if ((s_baseTracer.Options & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None)
{
s_baseTracer.WriteLine("Object Id: {0}", objectId);
s_baseTracer.WriteLine("Fragment Id: {0}", fragmentId);
s_baseTracer.WriteLine("Start Flag: {0}", sFlag);
s_baseTracer.WriteLine("End Flag: {0}", eFlag);
s_baseTracer.WriteLine("Blob Length: {0}", blobLength);
}
int totalLengthOfFragment = 0;
try
{
totalLengthOfFragment = checked(FragmentedRemoteObject.HeaderLength + blobLength);
}
catch (System.OverflowException)
{
s_baseTracer.WriteLine("Fragment too big.");
ResetReceiveData();
PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig);
throw e;
}
if (_pendingDataStream.Length < totalLengthOfFragment)
{
s_baseTracer.WriteLine("Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.",
_pendingDataStream.Length, totalLengthOfFragment);
return;
}
// ensure object size limit is not reached
if (_maxReceivedObjectSize.HasValue)
{
_totalReceivedObjectSizeSoFar = unchecked(_totalReceivedObjectSizeSoFar + totalLengthOfFragment);
if ((_totalReceivedObjectSizeSoFar < 0) || (_totalReceivedObjectSizeSoFar > _maxReceivedObjectSize.Value))
{
s_baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}",
_totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
PSRemotingTransportException e = null;
if (_isCreateByClientTM)
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient,
RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient,
_totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
}
else
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer,
RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer,
_totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
}
ResetReceiveData();
throw e;
}
}
// appears like stream doesn't have individual position marker for read and write
// since we are going to read from now...
_pendingDataStream.Seek(0, SeekOrigin.Begin);
// we have enough data to process..so read the data from the stream and process.
byte[] oneFragment = new byte[totalLengthOfFragment];
// this will change position back to totalLengthOfFragment
int dataCount = _pendingDataStream.Read(oneFragment, 0, totalLengthOfFragment);
Dbg.Assert(dataCount == totalLengthOfFragment, "Unable to read enough data from the stream. Read failed");
PSEtwLog.LogAnalyticVerbose(
PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
(Int64)objectId,
(Int64)fragmentId,
sFlag ? 1 : 0,
eFlag ? 1 : 0,
(UInt32)blobLength,
new PSETWBinaryBlob(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength));
byte[] extraData = null;
if (totalLengthOfFragment < _pendingDataStream.Length)
{
// there is more data in the stream than fragment size..so save that data
extraData = new byte[_pendingDataStream.Length - totalLengthOfFragment];
_pendingDataStream.Read(extraData, 0, (int)(_pendingDataStream.Length - totalLengthOfFragment));
}
// reset incoming stream.
_pendingDataStream.Dispose();
_pendingDataStream = new MemoryStream();
if (extraData != null)
{
_pendingDataStream.Write(extraData, 0, extraData.Length);
}
if (sFlag)
{
_canIgnoreOffSyncFragments = false; // reset this upon receiving a start fragment of a fresh object
_currentObjectId = objectId;
// Memory streams created with an unsigned byte array provide a non-resizable stream view
// of the data, and can only be written to. When using a byte array, you can neither append
// to nor shrink the stream, although you might be able to modify the existing contents
// depending on the parameters passed into the constructor. Empty memory streams are
// resizable, and can be written to and read from.
_dataToProcessStream = new MemoryStream();
}
else
{
// check if the data belongs to the same object as the start fragment
if (objectId != _currentObjectId)
{
s_baseTracer.WriteLine("ObjectId != CurrentObjectId");
// TODO - drop an ETW event
ResetReceiveData();
if (!_canIgnoreOffSyncFragments)
{
PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching);
throw e;
}
else
{
s_baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId");
continue;
}
}
if (fragmentId != (_currentFrgId + 1))
{
s_baseTracer.WriteLine("Fragment Id is not in sequence.");
// TODO - drop an ETW event
ResetReceiveData();
if (!_canIgnoreOffSyncFragments)
{
PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.FragmentIdsNotInSequence);
throw e;
}
else
{
s_baseTracer.WriteLine("Ignoring Fragment Id is not in sequence.");
continue;
}
}
}
// make fragment id from this packet as the current fragment id
_currentFrgId = fragmentId;
// store the blob in a separate stream
_dataToProcessStream.Write(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength);
if (eFlag)
{
try
{
// appears like stream doesn't individual position marker for read and write
// since we are going to read from now..i am resetting position to 0.
_dataToProcessStream.Seek(0, SeekOrigin.Begin);
RemoteDataObject<PSObject> remoteObject = RemoteDataObject<PSObject>.CreateFrom(_dataToProcessStream, _defragmentor);
s_baseTracer.WriteLine("Runspace Id: {0}", remoteObject.RunspacePoolId);
s_baseTracer.WriteLine("PowerShell Id: {0}", remoteObject.PowerShellId);
// notify the caller that a deserialized object is available.
callback(remoteObject);
}
finally
{
// Reset the receive data buffers and start the process again.
ResetReceiveData();
}
if (_isDisposed)
{
break;
}
}
}
}
finally
{
lock (_syncObject)
{
if (_isDisposed && (_numberOfThreadsProcessing == 1))
{
ReleaseResources();
}
_numberOfThreadsProcessing--;
}
}
}
/// <summary>
/// Resets the store(s) holding received data.
/// </summary>
private void ResetReceiveData()
{
// reset resources used to store incoming data (for a single object)
if (_dataToProcessStream != null)
{
_dataToProcessStream.Dispose();
}
_currentObjectId = 0;
_currentFrgId = 0;
_totalReceivedObjectSizeSoFar = 0;
}
private void ReleaseResources()
{
if (_pendingDataStream != null)
{
_pendingDataStream.Dispose();
_pendingDataStream = null;
}
if (_dataToProcessStream != null)
{
_dataToProcessStream.Dispose();
_dataToProcessStream = null;
}
}
#endregion
#region IDisposable implementation
/// <summary>
/// Dispose and release resources.
/// </summary>
public void Dispose()
{
Dispose(true);
// if already disposing..no need to let finalizer thread
// put resources to clean this object.
System.GC.SuppressFinalize(this);
}
internal virtual void Dispose(bool isDisposing)
{
lock (_syncObject)
{
_isDisposed = true;
if (_numberOfThreadsProcessing == 0)
{
ReleaseResources();
}
}
}
#endregion
}
/// <summary>
/// DataStructure used by different remoting protocol /
/// DataStructures to receive data from transport manager.
/// This class holds the responsibility of defragmenting and
/// deserializing.
/// </summary>
internal class PriorityReceiveDataCollection : IDisposable
{
#region Private Data
private readonly Fragmentor _defragmentor;
private readonly ReceiveDataCollection[] _recvdData;
private readonly bool _isCreateByClientTM;
#endregion
#region Constructor
/// <summary>
/// Construct a priority receive data collection.
/// </summary>
/// <param name="defragmentor">Defragmentor used to deserialize an object.</param>
/// <param name="createdByClientTM">
/// True if a client transport manager created this collection.
/// This is used to generate custom messages for server and client.
/// </param>
internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM)
{
_defragmentor = defragmentor;
string[] names = Enum.GetNames(typeof(DataPriorityType));
_recvdData = new ReceiveDataCollection[names.Length];
for (int index = 0; index < names.Length; index++)
{
_recvdData[index] = new ReceiveDataCollection(defragmentor, createdByClientTM);
}
_isCreateByClientTM = createdByClientTM;
}
#endregion
#region Internal Methods / Properties
/// <summary>
/// Limits the total data received from a remote machine.
/// </summary>
internal int? MaximumReceivedDataSize
{
set
{
_defragmentor.DeserializationContext.MaximumAllowedMemory = value;
}
}
/// <summary>
/// Limits the deserialized object size received from a remote machine.
/// </summary>
internal int? MaximumReceivedObjectSize
{
set
{
foreach (ReceiveDataCollection recvdDataBuffer in _recvdData)
{
recvdDataBuffer.MaximumReceivedObjectSize = value;
}
}
}
/// <summary>
/// Prepares receive data streams for a reconnection.
/// </summary>
internal void PrepareForStreamConnect()
{
for (int index = 0; index < _recvdData.Length; index++)
{
_recvdData[index].PrepareForStreamConnect();
}
}
/// <summary>
/// This might be needed only for ServerCommandTransportManager case
/// where the command is run in the same thread that runs ProcessRawData
/// (to avoid thread context switch). By default this class supports
/// only one thread in ProcessRawData.
/// </summary>
internal void AllowTwoThreadsToProcessRawData()
{
for (int index = 0; index < _recvdData.Length; index++)
{
_recvdData[index].AllowTwoThreadsToProcessRawData();
}
}
/// <summary>
/// Process data coming from the transport. This method analyses the data
/// and if an object can be created, it creates one and calls the
/// <paramref name="callback"/> with the deserialized object. This method
/// does not assume all fragments to be available. So if not enough fragments are
/// available it will simply return..
/// </summary>
/// <param name="data">
/// Data to process.
/// </param>
/// <param name="priorityType">
/// Priority stream this data belongs to.
/// </param>
/// <param name="callback">
/// Callback to call once a complete deserialized object is available.
/// </param>
/// <returns>
/// Defragmented Object if any, otherwise null.
/// </returns>
/// <exception cref="PSRemotingTransportException">
/// 1. Fragment Ids not in sequence
/// 2. Object Ids does not match
/// 3. The current deserialized object size of the received data exceeded
/// allowed maximum object size. The current deserialized object size is {0}.
/// Allowed maximum object size is {1}.
/// 4.The total data received from the remote machine exceeded allowed maximum.
/// The total data received from remote machine is {0}. Allowed maximum is {1}.
/// </exception>
/// <remarks>
/// Might throw other exceptions as the deserialized object is handled here.
/// </remarks>
internal void ProcessRawData(byte[] data,
DataPriorityType priorityType,
ReceiveDataCollection.OnDataAvailableCallback callback)
{
Dbg.Assert(data != null, "Cannot process null data");
try
{
_defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length);
}
catch (System.Xml.XmlException)
{
PSRemotingTransportException e = null;
if (_isCreateByClientTM)
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient,
RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient,
_defragmentor.DeserializationContext.MaximumAllowedMemory.Value);
}
else
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer,
RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer,
_defragmentor.DeserializationContext.MaximumAllowedMemory.Value);
}
throw e;
}
_recvdData[(int)priorityType].ProcessRawData(data, callback);
}
#endregion
#region IDisposable implementation
/// <summary>
/// Dispose and release resources.
/// </summary>
public void Dispose()
{
Dispose(true);
// if already disposing..no need to let finalizer thread
// put resources to clean this object.
System.GC.SuppressFinalize(this);
}
internal virtual void Dispose(bool isDisposing)
{
if (_recvdData != null)
{
for (int index = 0; index < _recvdData.Length; index++)
{
_recvdData[index].Dispose();
}
}
}
#endregion
}
#endregion
}
| |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if UNITY_ANDROID
using UnityEngine;
using System;
using System.Collections.Generic;
using GoogleMobileAds.Api;
using GoogleMobileAds.Api.Mediation;
using GoogleMobileAds.Common;
namespace GoogleMobileAds.Android
{
internal class Utils
{
#region Fully-qualified class names
#region Google Mobile Ads SDK class names
public const string AdListenerClassName = "com.google.android.gms.ads.AdListener";
public const string AdRequestClassName = "com.google.android.gms.ads.AdRequest";
public const string AdRequestBuilderClassName =
"com.google.android.gms.ads.AdRequest$Builder";
public const string AdSizeClassName = "com.google.android.gms.ads.AdSize";
public const string AdMobExtrasClassName =
"com.google.android.gms.ads.mediation.admob.AdMobExtras";
public const string PlayStorePurchaseListenerClassName =
"com.google.android.gms.ads.purchase.PlayStorePurchaseListener";
public const string MobileAdsClassName = "com.google.android.gms.ads.MobileAds";
#endregion
#region Google Mobile Ads Unity Plugin class names
public const string BannerViewClassName = "com.google.unity.ads.Banner";
public const string InterstitialClassName = "com.google.unity.ads.Interstitial";
public const string RewardBasedVideoClassName = "com.google.unity.ads.RewardBasedVideo";
public const string NativeAdLoaderClassName = "com.google.unity.ads.NativeAdLoader";
public const string UnityAdListenerClassName = "com.google.unity.ads.UnityAdListener";
public const string UnityRewardBasedVideoAdListenerClassName =
"com.google.unity.ads.UnityRewardBasedVideoAdListener";
public const string UnityAdLoaderListenerClassName =
"com.google.unity.ads.UnityAdLoaderListener";
public const string PluginUtilsClassName = "com.google.unity.ads.PluginUtils";
#endregion
#region Unity class names
public const string UnityActivityClassName = "com.unity3d.player.UnityPlayer";
#endregion
#region Android SDK class names
public const string BundleClassName = "android.os.Bundle";
public const string DateClassName = "java.util.Date";
#endregion
#endregion
#region JavaObject creators
public static AndroidJavaObject GetAdSizeJavaObject(AdSize adSize)
{
if (adSize.IsSmartBanner)
{
return new AndroidJavaClass(AdSizeClassName)
.GetStatic<AndroidJavaObject>("SMART_BANNER");
}
else
{
return new AndroidJavaObject(AdSizeClassName, adSize.Width, adSize.Height);
}
}
public static AndroidJavaObject GetAdRequestJavaObject(AdRequest request)
{
AndroidJavaObject adRequestBuilder = new AndroidJavaObject(AdRequestBuilderClassName);
foreach (string keyword in request.Keywords)
{
adRequestBuilder.Call<AndroidJavaObject>("addKeyword", keyword);
}
foreach (string deviceId in request.TestDevices)
{
if (deviceId == AdRequest.TestDeviceSimulator)
{
string emulatorDeviceId = new AndroidJavaClass(AdRequestClassName)
.GetStatic<string>("DEVICE_ID_EMULATOR");
adRequestBuilder.Call<AndroidJavaObject>("addTestDevice", emulatorDeviceId);
}
else
{
adRequestBuilder.Call<AndroidJavaObject>("addTestDevice", deviceId);
}
}
if (request.Birthday.HasValue)
{
DateTime birthday = request.Birthday.GetValueOrDefault();
AndroidJavaObject birthdayObject = new AndroidJavaObject(
DateClassName, birthday.Year, birthday.Month, birthday.Day);
adRequestBuilder.Call<AndroidJavaObject>("setBirthday", birthdayObject);
}
if (request.Gender.HasValue)
{
int? genderCode = null;
switch (request.Gender.GetValueOrDefault())
{
case Gender.Unknown:
genderCode = new AndroidJavaClass(AdRequestClassName)
.GetStatic<int>("GENDER_UNKNOWN");
break;
case Gender.Male:
genderCode = new AndroidJavaClass(AdRequestClassName)
.GetStatic<int>("GENDER_MALE");
break;
case Gender.Female:
genderCode = new AndroidJavaClass(AdRequestClassName)
.GetStatic<int>("GENDER_FEMALE");
break;
}
if (genderCode.HasValue)
{
adRequestBuilder.Call<AndroidJavaObject>("setGender", genderCode);
}
}
if (request.TagForChildDirectedTreatment.HasValue)
{
adRequestBuilder.Call<AndroidJavaObject>(
"tagForChildDirectedTreatment",
request.TagForChildDirectedTreatment.GetValueOrDefault());
}
// Denote that the request is coming from this Unity plugin.
adRequestBuilder.Call<AndroidJavaObject>(
"setRequestAgent",
"unity-" + AdRequest.Version);
AndroidJavaObject bundle = new AndroidJavaObject(BundleClassName);
foreach (KeyValuePair<string, string> entry in request.Extras)
{
bundle.Call("putString", entry.Key, entry.Value);
}
bundle.Call("putString", "is_unity", "1");
AndroidJavaObject extras = new AndroidJavaObject(AdMobExtrasClassName, bundle);
adRequestBuilder.Call<AndroidJavaObject>("addNetworkExtras", extras);
foreach (MediationExtras mediationExtra in request.MediationExtras)
{
AndroidJavaObject mediationExtrasBundleBuilder =
new AndroidJavaObject(mediationExtra.AndroidMediationExtraBuilderClassName);
AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap");
foreach (KeyValuePair<string, string> entry in mediationExtra.Extras)
{
map.Call<string>("put", entry.Key, entry.Value);
}
AndroidJavaObject mediationExtras =
mediationExtrasBundleBuilder.Call<AndroidJavaObject>("buildExtras", map);
if (mediationExtras != null)
{
adRequestBuilder.Call<AndroidJavaObject>(
"addNetworkExtrasBundle",
mediationExtrasBundleBuilder.Call<AndroidJavaClass>("getAdapterClass"),
mediationExtras);
}
}
return adRequestBuilder.Call<AndroidJavaObject>("build");
}
#endregion
}
}
#endif
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
namespace Platform.Presentation.Forms
{
public class CultureHelper
{
public static bool GdiPlusLineCenteringBroken
{
get
{
return _gdiPlusLineCenteringBroken;
}
}
private static bool _gdiPlusLineCenteringBroken = false;
/// <summary>
/// Applies the given culture name to the current thread.
/// </summary>
/// <param name="cultureName"></param>
public static void ApplyUICulture(string cultureName)
{
if (cultureName == null)
{
throw new ArgumentNullException("cultureName");
}
CultureInfo culture = GetBestCulture(cultureName);
Thread.CurrentThread.CurrentUICulture = culture;
_gdiPlusLineCenteringBroken = CultureInfo.CurrentUICulture.ThreeLetterWindowsLanguageName == "CHT";
FixupDateTimeFormat();
}
private static void FixupDateTimeFormat()
{
if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.ToUpperInvariant() == "AR")
{
// Ensure that no spaces, slashes, or dashes will make the date not formmatted correctly by forcing all chars RTL
CultureInfo ci = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
ci.DateTimeFormat.ShortDatePattern = Regex.Replace(ci.DateTimeFormat.ShortDatePattern, "[Mdy]+", "\u200F$0");
Thread.CurrentThread.CurrentCulture = ci;
}
}
public static CultureInfo GetBestCulture(string cultureName)
{
try
{
// Dotnet won't load 'ml'
switch (cultureName.ToUpperInvariant())
{
case ("ML"):
return CultureInfo.CreateSpecificCulture("ml-in");
case ("PT"):
return CultureInfo.CreateSpecificCulture("pt-pt");
case ("SR-CYRL"):
return CultureInfo.CreateSpecificCulture("sr-cyrl-CS");
case ("SR-LATN-CS"):
try
{
return CultureInfo.CreateSpecificCulture(cultureName);
}
catch (ArgumentException)
{
return CultureInfo.CreateSpecificCulture("sr-sp-latn");
}
default:
return CultureInfo.CreateSpecificCulture(cultureName);
}
}
catch (ArgumentException)
{
// Specific culture didn't succeed, see if we can make
// a culture-neutral language identifier
int dashAt = cultureName.IndexOf('-');
if (dashAt >= 0)
{
try
{
return CultureInfo.CreateSpecificCulture(cultureName.Substring(0, dashAt));
}
catch (ArgumentException)
{
}
}
throw;
}
}
public static void FixupTextboxForNumber(TextBox textBox)
{
if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.ToUpperInvariant() == "HE")
{
textBox.RightToLeft = RightToLeft.No;
textBox.TextAlign = HorizontalAlignment.Right;
}
}
public static string GetDateTimeCombinedPattern(string date, string time)
{
// Simple way to control what comes first, date or time when displaying to the user
if (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpperInvariant() == "AR"
&& Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.ToUpperInvariant() == "AR")
{
return "\u200F" + time + " " + date;
}
else
{
return date + " " + time;
}
}
public static string GetShortDateTimePatternForDateTimePicker()
{
// DateTimPicker controls have a problem with RTL and custom formats. To get around this we hardcore the time in the reverse order.
if (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpperInvariant() == "AR"
&& Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.ToUpperInvariant() == "AR")
{
return "mm:hh";
}
else
{
return CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern;
}
}
[Obsolete("NOT FULLY TESTED")]
public static bool IsImeActive(IntPtr windowHandle)
{
bool isActive = false;
try
{
IntPtr handle = Imm32.ImmGetContext(windowHandle);
if (handle == IntPtr.Zero)
return false;
try
{
isActive = Imm32.ImmGetOpenStatus(handle);
}
finally
{
Imm32.ImmReleaseContext(windowHandle, handle);
}
return isActive;
}
catch (Exception ex)
{
Trace.Fail("Failed to check if IME is active: " + ex);
return isActive;
}
}
[Obsolete("NOT FULLY TESTED")]
public static class Imm32
{
[DllImport("imm32.dll")]
public static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("imm32.dll")]
public static extern bool ImmGetOpenStatus(IntPtr hIMC);
[DllImport("imm32.dll")]
public static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);
}
public static bool IsRtlCodepage(uint codepage)
{
switch (codepage)
{
case 708:
case 720:
case 864:
case 1256:
case 10004:
case 20420:
case 28596:
case 862:
case 1255:
case 10005:
case 20424:
case 28598:
case 38598:
return true;
}
return false;
}
public static bool IsRtlLcid(int lcid)
{
return new CultureInfo(lcid).TextInfo.IsRightToLeft;
}
public static bool IsRtlCulture(string bcp47Code)
{
try
{
return new CultureInfo(bcp47Code).TextInfo.IsRightToLeft;
}
catch
{
return false;
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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.
//
#if !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Writes log message to the Event Log.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/EventLog_target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" />
/// </example>
[Target("EventLog")]
public class EventLogTarget : TargetWithLayout, IInstallable
{
private EventLog eventLogInstance;
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget() : this(AppDomainWrapper.CurrentDomain)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget(IAppDomain appDomain)
{
this.Source = appDomain.FriendlyName;
this.Log = "Application";
this.MachineName = ".";
}
/// <summary>
/// Gets or sets the name of the machine on which Event Log service is running.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue(".")]
public string MachineName { get; set; }
/// <summary>
/// Gets or sets the layout that renders event ID.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout EventId { get; set; }
/// <summary>
/// Gets or sets the layout that renders event Category.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout Category { get; set; }
/// <summary>
/// Gets or sets the value to be used as the event Source.
/// </summary>
/// <remarks>
/// By default this is the friendly name of the current AppDomain.
/// </remarks>
/// <docgen category='Event Log Options' order='10' />
public string Source { get; set; }
/// <summary>
/// Gets or sets the name of the Event Log to write to. This can be System, Application or
/// any user-defined name.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue("Application")]
public string Log { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
if (EventLog.SourceExists(this.Source, this.MachineName))
{
string currentLogName = EventLog.LogNameFromSourceName(this.Source, this.MachineName);
if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(this.Source, this.MachineName);
var escd = new EventSourceCreationData(this.Source, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(escd);
}
}
else
{
var escd = new EventSourceCreationData(this.Source, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(escd);
}
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
EventLog.DeleteEventSource(this.Source, this.MachineName);
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
return EventLog.SourceExists(this.Source, this.MachineName);
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
var s = EventLog.LogNameFromSourceName(this.Source, this.MachineName);
if (!s.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
this.CreateEventSourceIfNeeded();
}
}
/// <summary>
/// Writes the specified logging event to the event log.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
string message = this.Layout.Render(logEvent);
if (message.Length > 16384)
{
// limitation of EventLog API
message = message.Substring(0, 16384);
}
EventLogEntryType entryType;
if (logEvent.Level >= LogLevel.Error)
{
entryType = EventLogEntryType.Error;
}
else if (logEvent.Level >= LogLevel.Warn)
{
entryType = EventLogEntryType.Warning;
}
else
{
entryType = EventLogEntryType.Information;
}
int eventId = 0;
if (this.EventId != null)
{
eventId = Convert.ToInt32(this.EventId.Render(logEvent), CultureInfo.InvariantCulture);
}
short category = 0;
if (this.Category != null)
{
category = Convert.ToInt16(this.Category.Render(logEvent), CultureInfo.InvariantCulture);
}
var eventLog = GetEventLog();
eventLog.WriteEntry(message, entryType, eventId, category);
}
private EventLog GetEventLog()
{
return eventLogInstance ?? (eventLogInstance = new EventLog(this.Log, this.MachineName, this.Source));
}
private void CreateEventSourceIfNeeded()
{
// if we throw anywhere, we remain non-operational
try
{
if (EventLog.SourceExists(this.Source, this.MachineName))
{
string currentLogName = EventLog.LogNameFromSourceName(this.Source, this.MachineName);
if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(this.Source, this.MachineName);
var escd = new EventSourceCreationData(this.Source, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(escd);
}
}
else
{
var escd = new EventSourceCreationData(this.Source, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(escd);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when connecting to EventLog: {0}", exception);
throw;
}
}
}
}
#endif
| |
namespace JSLint
{
partial class OptionsForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.chkIntegrateWithBuild = new System.Windows.Forms.CheckBox();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.treeSolution = new System.Windows.Forms.TreeView();
this.groupIntegrateWithBuild = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.groupCheckingScope = new System.Windows.Forms.GroupBox();
this.chkScheckingScope = new System.Windows.Forms.CheckBox();
this.chkStopBuildOnErrors = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.numJSLintProcessWaitTime = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.groupJSLintOptions = new System.Windows.Forms.GroupBox();
this.chkListJSLintOptions = new System.Windows.Forms.CheckedListBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.btnClearJSLintOptions = new System.Windows.Forms.Button();
this.btnRecommendedJSLintOptions = new System.Windows.Forms.Button();
this.btnGoodJavaScriptParts = new System.Windows.Forms.Button();
this.groupIntegrateWithBuild.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.groupCheckingScope.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numJSLintProcessWaitTime)).BeginInit();
this.groupJSLintOptions.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// chkIntegrateWithBuild
//
this.chkIntegrateWithBuild.AutoSize = true;
this.chkIntegrateWithBuild.Location = new System.Drawing.Point(9, 232);
this.chkIntegrateWithBuild.Name = "chkIntegrateWithBuild";
this.chkIntegrateWithBuild.Size = new System.Drawing.Size(116, 17);
this.chkIntegrateWithBuild.TabIndex = 0;
this.chkIntegrateWithBuild.Text = "Integrate with Build";
this.chkIntegrateWithBuild.UseVisualStyleBackColor = true;
//
// treeSolution
//
this.treeSolution.CheckBoxes = true;
this.treeSolution.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeSolution.Location = new System.Drawing.Point(3, 16);
this.treeSolution.Name = "treeSolution";
this.treeSolution.Size = new System.Drawing.Size(750, 216);
this.treeSolution.TabIndex = 1;
//
// groupIntegrateWithBuild
//
this.groupIntegrateWithBuild.Controls.Add(this.tableLayoutPanel1);
this.groupIntegrateWithBuild.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupIntegrateWithBuild.Location = new System.Drawing.Point(0, 233);
this.groupIntegrateWithBuild.Name = "groupIntegrateWithBuild";
this.groupIntegrateWithBuild.Size = new System.Drawing.Size(768, 286);
this.groupIntegrateWithBuild.TabIndex = 2;
this.groupIntegrateWithBuild.TabStop = false;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 5;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Controls.Add(this.groupCheckingScope, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.chkStopBuildOnErrors, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.label1, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.numJSLintProcessWaitTime, 3, 0);
this.tableLayoutPanel1.Controls.Add(this.label2, 4, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.Size = new System.Drawing.Size(762, 267);
this.tableLayoutPanel1.TabIndex = 2;
//
// groupCheckingScope
//
this.tableLayoutPanel1.SetColumnSpan(this.groupCheckingScope, 5);
this.groupCheckingScope.Controls.Add(this.chkScheckingScope);
this.groupCheckingScope.Controls.Add(this.treeSolution);
this.groupCheckingScope.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupCheckingScope.Location = new System.Drawing.Point(3, 29);
this.groupCheckingScope.Name = "groupCheckingScope";
this.groupCheckingScope.Size = new System.Drawing.Size(756, 235);
this.groupCheckingScope.TabIndex = 3;
this.groupCheckingScope.TabStop = false;
//
// chkScheckingScope
//
this.chkScheckingScope.AutoSize = true;
this.chkScheckingScope.Location = new System.Drawing.Point(11, 0);
this.chkScheckingScope.Name = "chkScheckingScope";
this.chkScheckingScope.Size = new System.Drawing.Size(160, 17);
this.chkScheckingScope.TabIndex = 0;
this.chkScheckingScope.Text = "Don\'t Check Whole Solution";
this.chkScheckingScope.UseVisualStyleBackColor = true;
//
// chkStopBuildOnErrors
//
this.chkStopBuildOnErrors.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.chkStopBuildOnErrors.AutoSize = true;
this.chkStopBuildOnErrors.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkStopBuildOnErrors.Location = new System.Drawing.Point(3, 4);
this.chkStopBuildOnErrors.Name = "chkStopBuildOnErrors";
this.chkStopBuildOnErrors.Size = new System.Drawing.Size(121, 17);
this.chkStopBuildOnErrors.TabIndex = 1;
this.chkStopBuildOnErrors.Text = "Stop Build On Errors";
this.chkStopBuildOnErrors.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(150, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(84, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Kill process after";
//
// numJSLintProcessWaitTime
//
this.numJSLintProcessWaitTime.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.numJSLintProcessWaitTime.Location = new System.Drawing.Point(240, 3);
this.numJSLintProcessWaitTime.Minimum = new decimal(new int[] {
10,
0,
0,
0});
this.numJSLintProcessWaitTime.Name = "numJSLintProcessWaitTime";
this.numJSLintProcessWaitTime.Size = new System.Drawing.Size(38, 20);
this.numJSLintProcessWaitTime.TabIndex = 3;
this.numJSLintProcessWaitTime.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(284, 6);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(475, 13);
this.label2.TabIndex = 4;
this.label2.Text = "seconds";
//
// groupJSLintOptions
//
this.groupJSLintOptions.Controls.Add(this.chkListJSLintOptions);
this.groupJSLintOptions.Controls.Add(this.flowLayoutPanel1);
this.groupJSLintOptions.Dock = System.Windows.Forms.DockStyle.Top;
this.groupJSLintOptions.Location = new System.Drawing.Point(0, 0);
this.groupJSLintOptions.Name = "groupJSLintOptions";
this.groupJSLintOptions.Size = new System.Drawing.Size(768, 233);
this.groupJSLintOptions.TabIndex = 2;
this.groupJSLintOptions.TabStop = false;
this.groupJSLintOptions.Text = "JSLint Options";
//
// chkListJSLintOptions
//
this.chkListJSLintOptions.CheckOnClick = true;
this.chkListJSLintOptions.ColumnWidth = 250;
this.chkListJSLintOptions.Dock = System.Windows.Forms.DockStyle.Fill;
this.chkListJSLintOptions.FormattingEnabled = true;
this.chkListJSLintOptions.Items.AddRange(new object[] {
"Stop on first error",
"Strict white space",
"Assume a browser",
"Assume console, alert, ...",
"Assume a Yahoo Widget",
"Assume Windows",
"Assume Rhino",
"Safe Subset",
"ADsafe",
"Tolerate debugger statements",
"Tolerate eval",
"Tolerate sloppy line breaking",
"Tolerate unfiltered for in",
"Tolerate inefficient subscripting",
"Tolerate CSS workarounds",
"Tolerate HTML case",
"Tolerate HTML event handlers",
"Tolerate HTML fragments",
"Tolerate ES5 syntax",
"Allow one var statement per function",
"Disallow undefined variables",
"Disallow dangling _ in identifiers",
"Disallow == and !=",
"Disallow ++ and --",
"Disallow bitwise operators",
"Disallow insecure . and [^...] in /RegExp/",
"Require \"use strict\";",
"Require Initial Caps for constructors",
"Require parens around immediate invocations "});
this.chkListJSLintOptions.Location = new System.Drawing.Point(3, 16);
this.chkListJSLintOptions.MultiColumn = true;
this.chkListJSLintOptions.Name = "chkListJSLintOptions";
this.chkListJSLintOptions.Size = new System.Drawing.Size(762, 184);
this.chkListJSLintOptions.TabIndex = 0;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel1.Controls.Add(this.btnClearJSLintOptions);
this.flowLayoutPanel1.Controls.Add(this.btnRecommendedJSLintOptions);
this.flowLayoutPanel1.Controls.Add(this.btnGoodJavaScriptParts);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 201);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(762, 29);
this.flowLayoutPanel1.TabIndex = 4;
//
// btnClearJSLintOptions
//
this.btnClearJSLintOptions.AutoSize = true;
this.btnClearJSLintOptions.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnClearJSLintOptions.Location = new System.Drawing.Point(3, 3);
this.btnClearJSLintOptions.Name = "btnClearJSLintOptions";
this.btnClearJSLintOptions.Size = new System.Drawing.Size(94, 23);
this.btnClearJSLintOptions.TabIndex = 0;
this.btnClearJSLintOptions.Text = "Clear All Options";
this.btnClearJSLintOptions.UseVisualStyleBackColor = true;
this.btnClearJSLintOptions.Click += new System.EventHandler(this.btnClearJSLintOptions_Click);
//
// btnRecommendedJSLintOptions
//
this.btnRecommendedJSLintOptions.AutoSize = true;
this.btnRecommendedJSLintOptions.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnRecommendedJSLintOptions.Location = new System.Drawing.Point(103, 3);
this.btnRecommendedJSLintOptions.Name = "btnRecommendedJSLintOptions";
this.btnRecommendedJSLintOptions.Size = new System.Drawing.Size(128, 23);
this.btnRecommendedJSLintOptions.TabIndex = 1;
this.btnRecommendedJSLintOptions.Text = "Recommended Options";
this.btnRecommendedJSLintOptions.UseVisualStyleBackColor = true;
this.btnRecommendedJSLintOptions.Click += new System.EventHandler(this.btnRecommendedJSLintOptions_Click);
//
// btnGoodJavaScriptParts
//
this.btnGoodJavaScriptParts.AutoSize = true;
this.btnGoodJavaScriptParts.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnGoodJavaScriptParts.Location = new System.Drawing.Point(237, 3);
this.btnGoodJavaScriptParts.Name = "btnGoodJavaScriptParts";
this.btnGoodJavaScriptParts.Size = new System.Drawing.Size(70, 23);
this.btnGoodJavaScriptParts.TabIndex = 2;
this.btnGoodJavaScriptParts.Text = "Good Parts";
this.btnGoodJavaScriptParts.UseVisualStyleBackColor = true;
this.btnGoodJavaScriptParts.Click += new System.EventHandler(this.btnGoodJavaScriptParts_Click);
//
// OptionsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(768, 519);
this.Controls.Add(this.chkIntegrateWithBuild);
this.Controls.Add(this.groupIntegrateWithBuild);
this.Controls.Add(this.groupJSLintOptions);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "OptionsForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "JSLint.VS Options";
this.Load += new System.EventHandler(this.OptionsForm_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OptionsForm_FormClosing);
this.groupIntegrateWithBuild.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.groupCheckingScope.ResumeLayout(false);
this.groupCheckingScope.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numJSLintProcessWaitTime)).EndInit();
this.groupJSLintOptions.ResumeLayout(false);
this.groupJSLintOptions.PerformLayout();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.CheckBox chkIntegrateWithBuild;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.TreeView treeSolution;
private System.Windows.Forms.GroupBox groupIntegrateWithBuild;
private System.Windows.Forms.CheckBox chkStopBuildOnErrors;
private System.Windows.Forms.GroupBox groupCheckingScope;
private System.Windows.Forms.CheckBox chkScheckingScope;
private System.Windows.Forms.GroupBox groupJSLintOptions;
private System.Windows.Forms.CheckedListBox chkListJSLintOptions;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button btnClearJSLintOptions;
private System.Windows.Forms.Button btnRecommendedJSLintOptions;
private System.Windows.Forms.Button btnGoodJavaScriptParts;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numJSLintProcessWaitTime;
private System.Windows.Forms.Label label2;
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocClassEdit
// ObjectType: DocClassEdit
// CSLAType: DynamicEditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
using CslaGenFork.Rules.CollectionRules;
using CslaGenFork.Rules.TransformationRules;
using DocStore.Business.Security;
using System.ComponentModel.DataAnnotations;
namespace DocStore.Business
{
/// <summary>
/// Classes of document (dynamic root object).<br/>
/// This is a generated <see cref="DocClassEdit"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="DocClassEditColl"/> collection.
/// </remarks>
[Serializable]
public partial class DocClassEdit : BusinessBase<DocClassEdit>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocClassID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> DocClassIDProperty = RegisterProperty<int>(p => p.DocClassID, "Doc Class ID");
/// <summary>
/// use ID = -1 with empty Name for accepting optional specification
/// </summary>
/// <value>The Doc Class ID.</value>
public int DocClassID
{
get { return GetProperty(DocClassIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocClassName"/> property.
/// </summary>
public static readonly PropertyInfo<string> DocClassNameProperty = RegisterProperty<string>(p => p.DocClassName, "Doc Class Name");
/// <summary>
/// Gets or sets the Doc Class Name.
/// </summary>
/// <value>The Doc Class Name.</value>
[Required(AllowEmptyStrings = false, ErrorMessage = "Must fill.")]
public string DocClassName
{
get { return GetProperty(DocClassNameProperty); }
set { SetProperty(DocClassNameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Date of creation
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// ID of the creating user
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Date of last change
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// ID of the last changing user
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Row version counter for concurrency control
/// </summary>
/// <value>The Row Version.</value>
internal byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Gets the Create User Name.
/// </summary>
/// <value>The Create User Name.</value>
public string CreateUserName
{
get
{
var result = string.Empty;
if (Admin.UserAllNVL.GetUserAllNVL().ContainsKey(CreateUserID))
result = Admin.UserAllNVL.GetUserAllNVL().GetItemByKey(CreateUserID).Value;
return result;
}
}
/// <summary>
/// Gets the Change User Name.
/// </summary>
/// <value>The Change User Name.</value>
public string ChangeUserName
{
get
{
var result = string.Empty;
if (Admin.UserAllNVL.GetUserAllNVL().ContainsKey(ChangeUserID))
result = Admin.UserAllNVL.GetUserAllNVL().GetItemByKey(ChangeUserID).Value;
return result;
}
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocClassEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="DocClassEdit"/> object.</returns>
internal static DocClassEdit NewDocClassEdit()
{
return DataPortal.Create<DocClassEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocClassEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocClassEdit"/> object.</returns>
internal static DocClassEdit GetDocClassEdit(SafeDataReader dr)
{
DocClassEdit obj = new DocClassEdit();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
/// <summary>
/// Factory method. Deletes a <see cref="DocClassEdit"/> object, based on given parameters.
/// </summary>
/// <param name="docClassID">The DocClassID of the DocClassEdit to delete.</param>
internal static void DeleteDocClassEdit(int docClassID)
{
DataPortal.Delete<DocClassEdit>(docClassID);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocClassEdit"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
internal static void NewDocClassEdit(EventHandler<DataPortalResult<DocClassEdit>> callback)
{
DataPortal.BeginCreate<DocClassEdit>(callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="DocClassEdit"/> object, based on given parameters.
/// </summary>
/// <param name="docClassID">The DocClassID of the DocClassEdit to delete.</param>
/// <param name="callback">The completion callback method.</param>
internal static void DeleteDocClassEdit(int docClassID, EventHandler<DataPortalResult<DocClassEdit>> callback)
{
DataPortal.BeginDelete<DocClassEdit>(docClassID, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocClassEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocClassEdit()
{
// Use factory methods and do not use direct creation.
Saved += OnDocClassEditSaved;
}
#endregion
#region Cache Invalidation
private void OnDocClassEditSaved(object sender, Csla.Core.SavedEventArgs e)
{
// this runs on the client
DocClassList.InvalidateCache();
DocClassNVL.InvalidateCache();
}
/// <summary>
/// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e)
{
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server &&
e.Operation == DataPortalOperations.Update)
{
// this runs on the server
DocClassList.InvalidateCache();
DocClassNVL.InvalidateCache();
}
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (DocClassEdit), new IsInRole(AuthorizationActions.CreateObject, "Admin"));
BusinessRules.AddRule(typeof (DocClassEdit), new IsInRole(AuthorizationActions.GetObject, "User"));
BusinessRules.AddRule(typeof (DocClassEdit), new IsInRole(AuthorizationActions.EditObject, "Admin"));
BusinessRules.AddRule(typeof (DocClassEdit), new IsInRole(AuthorizationActions.DeleteObject, "Admin"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can create a new DocClassEdit object.
/// </summary>
/// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
public static bool CanAddObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(DocClassEdit));
}
/// <summary>
/// Checks if the current user can retrieve DocClassEdit's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(DocClassEdit));
}
/// <summary>
/// Checks if the current user can change DocClassEdit's properties.
/// </summary>
/// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns>
public static bool CanEditObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(DocClassEdit));
}
/// <summary>
/// Checks if the current user can delete a DocClassEdit object.
/// </summary>
/// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
public static bool CanDeleteObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(DocClassEdit));
}
#endregion
#region Business Rules and Property Authorization
/// <summary>
/// Override this method in your business class to be notified when you need to set up shared business rules.
/// </summary>
/// <remarks>
/// This method is automatically called by CSLA.NET when your object should associate
/// per-type validation rules with its properties.
/// </remarks>
protected override void AddBusinessRules()
{
base.AddBusinessRules();
// Property Business Rules
// DocClassName
BusinessRules.AddRule(new CollapseWhiteSpace(DocClassNameProperty) { Priority = -1 });
BusinessRules.AddRule(new NoDuplicates(DocClassNameProperty) { MessageText = "There shall be only one!" });
AddBusinessRulesExtend();
}
/// <summary>
/// Allows the set up of custom shared business rules.
/// </summary>
partial void AddBusinessRulesExtend();
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="DocClassEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(DocClassIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="DocClassEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocClassIDProperty, dr.GetInt32("DocClassID"));
LoadProperty(DocClassNameProperty, dr.GetString("DocClassName"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="DocClassEdit"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddDocClassEdit", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocClassID", ReadProperty(DocClassIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@DocClassName", ReadProperty(DocClassNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(DocClassIDProperty, (int) cmd.Parameters["@DocClassID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocClassEdit"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateDocClassEdit", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocClassID", ReadProperty(DocClassIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocClassName", ReadProperty(DocClassNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
OnPropertyChanged("ChangeUserName");
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
OnPropertyChanged("CreateUserName");
}
}
/// <summary>
/// Self deletes the <see cref="DocClassEdit"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(DocClassID);
}
/// <summary>
/// Deletes the <see cref="DocClassEdit"/> object from database.
/// </summary>
/// <param name="docClassID">The delete criteria.</param>
protected void DataPortal_Delete(int docClassID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteDocClassEdit", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocClassID", docClassID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, docClassID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#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
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Automation;
using EnvDTE;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
namespace PythonToolsUITests {
// Object browser is currently disabled
//[TestClass]
public class ObjectBrowserTest {
private class NodeInfo {
public NodeInfo(string name, string description, string[] members = null) {
Name = name;
Description = description;
Members = (members != null) ? new Collection<string>(members) : new Collection<string>();
}
public string Name { get; private set; }
public string Description { get; private set; }
public Collection<string> Members { get; private set; }
}
private static void AssertNodes(ObjectBrowser objectBrowser, params NodeInfo[] expectedNodes) {
AssertNodes(objectBrowser, true, expectedNodes);
}
private static void AssertNodes(ObjectBrowser objectBrowser, bool expand, params NodeInfo[] expectedNodes) {
for (int i = 0; i < expectedNodes.Length; ++i) {
// Check node name
for (int j = 0; j < 100; j++) {
if (i < objectBrowser.TypeBrowserPane.Nodes.Count) {
break;
}
System.Threading.Thread.Sleep(250);
}
string str = objectBrowser.TypeBrowserPane.Nodes[i].Value.Trim();
Console.WriteLine("Found node: {0}", str);
Assert.AreEqual(expectedNodes[i].Name, str, "");
objectBrowser.TypeBrowserPane.Nodes[i].Select();
if (expand) {
try {
objectBrowser.TypeBrowserPane.Nodes[i].ExpandCollapse();
} catch (InvalidOperationException) {
}
}
System.Threading.Thread.Sleep(1000);
// Check detailed node description.
str = objectBrowser.DetailPane.Value.Trim();
if (expectedNodes[i].Description != str) {
for (int j = 0; j < str.Length; j++) {
Console.WriteLine("{0} {1}", (int)str[j], (int)expectedNodes[i].Description[j]);
}
}
Assert.AreEqual(expectedNodes[i].Description, str, "");
// Check dependent nodes in member pane
int nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count;
var expectedMembers = expectedNodes[i].Members;
if (expectedMembers == null) {
Assert.AreEqual(0, nodeCount, "Node Count: " + nodeCount.ToString());
} else {
Assert.AreEqual(expectedMembers.Count, nodeCount, "Node Count: " + nodeCount.ToString());
for (int j = 0; j < expectedMembers.Count; ++j) {
str = objectBrowser.TypeNavigatorPane.Nodes[j].Value.Trim();
Assert.AreEqual(expectedMembers[j], str, "");
}
}
}
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserBasicTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\Outlining.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
AssertNodes(objectBrowser,
new NodeInfo("Outlining", "Outlining"),
new NodeInfo("BadForStatement.py", "BadForStatement.py"),
new NodeInfo("NestedFuncDef.py", "NestedFuncDef.py", new[] { "def f()" }),
new NodeInfo("Program.py", "Program.py", new[] { "def f()", "i" }));
app.Dte.Solution.Close(false);
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserSearchTextTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\ObjectBrowser.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
objectBrowser.EnsureLoaded();
// Initially, we should have only the top-level collapsed node for the project
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
// Sanity-check the starting view with all nodes expanded.
var expectedNodesBeforeSearch = new[] {
new NodeInfo("ObjectBrowser", "ObjectBrowser"),
new NodeInfo("Program.py", "Program.py", new[] { "def frob()" }),
new NodeInfo("class Fob", "class Fob"),
new NodeInfo("class FobOarBaz", "class FobOarBaz", new[] { "def frob(self)" }),
new NodeInfo("class Oar", "class Oar", new[] { "def oar(self)" }),
};
AssertNodes(objectBrowser, expectedNodesBeforeSearch);
// Do the search and check results
objectBrowser.SearchText.SetValue("oar");
System.Threading.Thread.Sleep(1000);
objectBrowser.SearchButton.Click();
System.Threading.Thread.Sleep(1000);
var expectedNodesAfterSearch = new[] {
new NodeInfo("oar", "def oar(self)\rdeclared in Oar"),
new NodeInfo("Oar", "class Oar", new[] { "def oar(self)" }),
new NodeInfo("FobOarBaz", "class FobOarBaz", new[] { "def frob(self)" }),
};
AssertNodes(objectBrowser, expectedNodesAfterSearch);
// Clear the search and check that we get back to the starting view.
objectBrowser.ClearSearchButton.Click();
System.Threading.Thread.Sleep(1000);
AssertNodes(objectBrowser, false, expectedNodesBeforeSearch);
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserExpandTypeBrowserTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\Inheritance.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
objectBrowser.EnsureLoaded();
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[0].Value;
Assert.AreEqual("Inheritance", str, "");
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString());
str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserCommentsTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\Inheritance.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[1].Select();
nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count;
Assert.AreEqual(4, nodeCount, "Node Count: " + nodeCount.ToString());
str = objectBrowser.TypeNavigatorPane.Nodes[0].Value;
Assert.AreEqual("member", str.Trim(), "");
str = objectBrowser.TypeNavigatorPane.Nodes[1].Value;
Assert.AreEqual("members", str.Trim(), "");
str = objectBrowser.TypeNavigatorPane.Nodes[2].Value;
Assert.AreEqual("s", str.Trim(), "");
str = objectBrowser.TypeNavigatorPane.Nodes[3].Value;
Assert.AreEqual("t", str.Trim(), "");
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[2].Select();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count;
Assert.AreEqual(2, nodeCount, "Node Count: " + nodeCount.ToString());
str = objectBrowser.TypeNavigatorPane.Nodes[0].Value;
Assert.IsTrue(str.Trim().StartsWith("def __init__(self"), str);
str = objectBrowser.TypeNavigatorPane.Nodes[1].Value;
Assert.AreEqual("def tell(self)", str.Trim(), "");
str = objectBrowser.DetailPane.Value;
Assert.IsTrue(str.Trim().Contains("SchoolMember"), str);
Assert.IsTrue(str.Trim().Contains("Represents any school member."), str);
objectBrowser.TypeNavigatorPane.Nodes[1].Select();
System.Threading.Thread.Sleep(1000);
str = objectBrowser.DetailPane.Value;
Assert.IsTrue(str.Trim().Contains("def tell(self)"), str);
Assert.IsTrue(str.Trim().Contains("Tell my detail."), str);
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserInheritanceRelationshipTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\Inheritance.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[3].Select();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count;
Assert.AreEqual(2, nodeCount, "Node Count: " + nodeCount.ToString());
str = objectBrowser.TypeNavigatorPane.Nodes[0].Value;
Assert.IsTrue(str.Trim().StartsWith("__init__ (alias of def "), str);
str = objectBrowser.TypeNavigatorPane.Nodes[1].Value;
Assert.AreEqual("def tell(self)", str.Trim(), "");
str = objectBrowser.DetailPane.Value;
Assert.IsTrue(str.Trim().Contains("Student(SchoolMember)"), str);
Assert.IsTrue(str.Trim().Contains("Represents a student."), str);
objectBrowser.TypeNavigatorPane.Nodes[1].Select();
System.Threading.Thread.Sleep(1000);
str = objectBrowser.DetailPane.Value;
Assert.IsTrue(str.Trim().Contains("def tell(self)"), str);
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserNavigationTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\MultiModule.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
objectBrowser.EnsureLoaded();
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[4].Select();
System.Threading.Thread.Sleep(1000);
app.ExecuteCommand("Edit.GoToDefinition");
System.Threading.Thread.Sleep(1000);
str = app.Dte.ActiveDocument.Name;
Assert.AreEqual("Program.py", str, "");
int lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line;
Assert.AreEqual(14, lineNo, "Line number: " + lineNo.ToString());
app.OpenObjectBrowser();
objectBrowser.TypeBrowserPane.Nodes[2].Select();
System.Threading.Thread.Sleep(1000);
app.ExecuteCommand("Edit.GoToDefinition");
System.Threading.Thread.Sleep(1000);
str = app.Dte.ActiveDocument.Name;
Assert.AreEqual("MyModule.py", str, "");
lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line;
Assert.AreEqual(1, lineNo, "Line number: " + lineNo.ToString());
objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserContextMenuBasicTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\MultiModule.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
Condition con = new PropertyCondition(
AutomationElement.ClassNameProperty,
"ContextMenu"
);
AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
Menu menu = new Menu(el);
int itemCount = menu.Items.Count;
Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString());
Assert.AreEqual("Copy", menu.Items[0].Value.Trim(), "");
Assert.AreEqual("View Namespaces", menu.Items[1].Value.Trim(), "");
Assert.AreEqual("View Containers", menu.Items[2].Value.Trim(), "");
Assert.AreEqual("Sort Alphabetically", menu.Items[3].Value.Trim(), "");
Assert.AreEqual("Sort By Object Type", menu.Items[4].Value.Trim(), "");
Assert.AreEqual("Sort By Object Access", menu.Items[5].Value.Trim(), "");
Assert.AreEqual("Group By Object Type", menu.Items[6].Value.Trim(), "");
Keyboard.PressAndRelease(System.Windows.Input.Key.Escape);
objectBrowser.TypeBrowserPane.Nodes[2].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
menu = new Menu(el);
itemCount = menu.Items.Count;
Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString());
Assert.AreEqual("Go To Definition", menu.Items[0].Value.Trim(), "");
Assert.AreEqual("Go To Declaration", menu.Items[1].Value.Trim(), "");
Assert.AreEqual("Go To Reference", menu.Items[2].Value.Trim(), "");
Assert.AreEqual("Browse Definition", menu.Items[3].Value.Trim(), "");
Assert.AreEqual("Find All References", menu.Items[4].Value.Trim(), "");
Assert.AreEqual("Filter To Type", menu.Items[5].Value.Trim(), "");
Assert.AreEqual("Copy", menu.Items[6].Value.Trim(), "");
Assert.AreEqual("View Namespaces", menu.Items[7].Value.Trim(), "");
Assert.AreEqual("View Containers", menu.Items[8].Value.Trim(), "");
Assert.AreEqual("Sort Alphabetically", menu.Items[9].Value.Trim(), "");
Assert.AreEqual("Sort By Object Type", menu.Items[10].Value.Trim(), "");
Assert.AreEqual("Sort By Object Access", menu.Items[11].Value.Trim(), "");
Assert.AreEqual("Group By Object Type", menu.Items[12].Value.Trim(), "");
Keyboard.PressAndRelease(System.Windows.Input.Key.Escape);
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserTypeBrowserViewTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\MultiModule.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
Condition con = new PropertyCondition(
AutomationElement.ClassNameProperty,
"ContextMenu"
);
AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
Menu menu = new Menu(el);
int itemCount = menu.Items.Count;
Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString());
menu.Items[1].Check();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
menu = new Menu(el);
itemCount = menu.Items.Count;
Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString());
Assert.IsTrue(menu.Items[1].ToggleStatus);
menu.Items[2].Check();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserTypeBrowserSortTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\MultiModule.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
Condition con = new PropertyCondition(
AutomationElement.ClassNameProperty,
"ContextMenu"
);
AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
Menu menu = new Menu(el);
int itemCount = menu.Items.Count;
Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString());
menu.Items[6].Check();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(4, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString());
Assert.AreEqual("Namespaces", objectBrowser.TypeBrowserPane.Nodes[3].Value, "");
Assert.AreEqual("Namespaces", objectBrowser.TypeBrowserPane.Nodes[1].Value, "");
objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
objectBrowser.TypeBrowserPane.Nodes[0].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
menu = new Menu(el);
itemCount = menu.Items.Count;
Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString());
Assert.IsTrue(menu.Items[6].ToggleStatus);
menu.Items[3].Check();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(4, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString());
str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("class SchoolMember\n", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[3].Value;
Assert.AreEqual("Program.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[4].Value;
Assert.AreEqual("class Student(MyModule.SchoolMember)\n", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[5].Value;
Assert.AreEqual("class Teacher(MyModule.SchoolMember)\n", str, "");
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserNavigateVarContextMenuTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\MultiModule.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
objectBrowser.EnsureLoaded();
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[4].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
Condition con = new PropertyCondition(
AutomationElement.ClassNameProperty,
"ContextMenu"
);
AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
Menu menu = new Menu(el);
int itemCount = menu.Items.Count;
Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString());
menu.Items[0].Check();
System.Threading.Thread.Sleep(1000);
str = app.Dte.ActiveDocument.Name;
Assert.AreEqual("Program.py", str, "");
int lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line;
Assert.AreEqual(14, lineNo, "Line number: " + lineNo.ToString());
app.OpenObjectBrowser();
objectBrowser.TypeBrowserPane.Nodes[5].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
menu = new Menu(el);
menu.Items[0].Check();
System.Threading.Thread.Sleep(1000);
lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line;
Assert.AreEqual(3, lineNo, "Line number: " + lineNo.ToString());
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ObjectBrowserFindAllReferencesTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\MultiModule.sln");
System.Threading.Thread.Sleep(1000);
app.OpenObjectBrowser();
var objectBrowser = app.ObjectBrowser;
System.Threading.Thread.Sleep(1000);
int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString());
string str = objectBrowser.TypeBrowserPane.Nodes[1].Value;
Assert.AreEqual("MyModule.py", str, "");
str = objectBrowser.TypeBrowserPane.Nodes[2].Value;
Assert.AreEqual("Program.py", str, "");
objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse();
System.Threading.Thread.Sleep(1000);
nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count;
Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString());
objectBrowser.TypeBrowserPane.Nodes[4].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
Condition con = new PropertyCondition(
AutomationElement.ClassNameProperty,
"ContextMenu"
);
AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
Menu menu = new Menu(el);
int itemCount = menu.Items.Count;
Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString());
menu.Items[4].Check();
System.Threading.Thread.Sleep(1000);
//this needs to be updated for bug #4840
str = app.Dte.ActiveWindow.Caption;
Assert.IsTrue(str.Contains("2 matches found"), str);
objectBrowser.TypeBrowserPane.Nodes[2].ShowContextMenu();
System.Threading.Thread.Sleep(1000);
el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con);
Assert.IsNotNull(el);
menu = new Menu(el);
menu.Items[4].Check();
System.Threading.Thread.Sleep(1000);
str = app.Dte.ActiveWindow.Caption;
Assert.IsTrue(str.Contains("2 matches found"), str);
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void NavigateTo(VisualStudioApp app) {
app.OpenProject(@"TestData\Navigation.sln");
using (var dialog = app.OpenNavigateTo()) {
dialog.SearchTerm = "Class";
Assert.AreEqual(4, dialog.WaitForNumberOfResults(4));
}
using (var dialog = app.OpenNavigateTo()) {
dialog.SearchTerm = "cls";
Assert.AreEqual(4, dialog.WaitForNumberOfResults(4));
}
using (var dialog = app.OpenNavigateTo()) {
dialog.SearchTerm = "func";
Assert.AreEqual(8, dialog.WaitForNumberOfResults(8));
}
using (var dialog = app.OpenNavigateTo()) {
dialog.SearchTerm = "fn";
Assert.AreEqual(8, dialog.WaitForNumberOfResults(8));
}
}
////[TestMethod, Priority(0)]
//[HostType("VSTestHost"), TestCategory("Installed")]
public void ResourceViewIsDisabledTest(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\Outlining.sln");
System.Threading.Thread.Sleep(1000);
app.OpenResourceView();
var resourceView = app.ResourceView;
Assert.IsNotNull(resourceView);
System.Threading.Thread.Sleep(1000);
Assert.IsNull(resourceView.TypeBrowserPane);
}
}
}
| |
// ZipInputStream.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Silverlight.Checksums;
using ICSharpCode.SharpZipLib.Silverlight.Encryption;
using ICSharpCode.SharpZipLib.Silverlight.Zip.Compression;
using ICSharpCode.SharpZipLib.Silverlight.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Silverlight.Zip
{
/// <summary>
/// This is an InflaterInputStream that reads the files baseInputStream an zip archive
/// one after another. It has a special method to get the zip entry of
/// the next file. The zip entry contains information about the file name
/// size, compressed size, Crc, etc.
/// It includes support for Stored and Deflated entries.
/// <br/>
/// <br/>Author of the original java version : Jochen Hoenicke
/// </summary>
///
/// <example> This sample shows how to read a zip file
/// <code lang="C#">
/// using System;
/// using System.Text;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.Zip;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) {
///
/// ZipEntry theEntry;
/// while ((theEntry = s.GetNextEntry()) != null) {
/// int size = 2048;
/// byte[] data = new byte[2048];
///
/// Console.Write("Show contents (y/n) ?");
/// if (Console.ReadLine() == "y") {
/// while (true) {
/// size = s.Read(data, 0, data.Length);
/// if (size > 0) {
/// Console.Write(new ASCIIEncoding().GetString(data, 0, size));
/// } else {
/// break;
/// }
/// }
/// }
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public class ZipInputStream : InflaterInputStream
{
#region Instance Fields
// Delegate for reading bytes from a stream.
private Crc32 crc = new Crc32();
private ZipEntry entry;
private int flags;
/// <summary>
/// The current reader this instance.
/// </summary>
private ReaderDelegate internalReader;
private int method;
private string password;
private long size;
private delegate int ReaderDelegate(byte[] b, int offset, int length);
#endregion
#region Constructors
/// <summary>
/// Creates a new Zip input stream, for reading a zip archive.
/// </summary>
/// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param>
public ZipInputStream(Stream baseInputStream)
: base(baseInputStream, new Inflater(true))
{
internalReader = ReadingNotAvailable;
}
#endregion
/// <summary>
/// Optional password used for encryption when non-null
/// </summary>
/// <value>A password for all encrypted <see cref="ZipEntry">entries </see> in this <see cref="ZipInputStream"/></value>
public string Password
{
get { return password; }
set { password = value; }
}
/// <summary>
/// Gets a value indicating if there is a current entry and it can be decompressed
/// </summary>
/// <remarks>
/// The entry can only be decompressed if the library supports the zip features required to extract it.
/// See the <see cref="ZipEntry.Version">ZipEntry Version</see> property for more details.
/// </remarks>
public bool CanDecompressEntry
{
get { return (entry != null) && entry.CanDecompress; }
}
/// <summary>
/// Returns 1 if there is an entry available
/// Otherwise returns 0.
/// </summary>
public override int Available
{
get { return entry != null ? 1 : 0; }
}
/// <summary>
/// Returns the current size that can be read from the current entry if available
/// </summary>
/// <exception cref="ZipException">Thrown if the entry size is not known.</exception>
/// <exception cref="InvalidOperationException">Thrown if no entry is currently available.</exception>
public override long Length
{
get
{
if (entry != null)
{
if (entry.Size >= 0)
{
return entry.Size;
}
else
{
throw new ZipException("Length not available for the current entry");
}
}
else
{
throw new InvalidOperationException("No current entry");
}
}
}
/// <summary>
/// Advances to the next entry in the archive
/// </summary>
/// <returns>
/// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries.
/// </returns>
/// <remarks>
/// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Input stream is closed
/// </exception>
/// <exception cref="ZipException">
/// Password is not set, password is invalid, compression method is invalid,
/// version required to extract is not supported
/// </exception>
public ZipEntry GetNextEntry()
{
if (crc == null)
{
throw new InvalidOperationException("Closed.");
}
if (entry != null)
{
CloseEntry();
}
var header = inputBuffer.ReadLeInt();
if (header == ZipConstants.CentralHeaderSignature ||
header == ZipConstants.EndOfCentralDirectorySignature ||
header == ZipConstants.CentralHeaderDigitalSignature ||
header == ZipConstants.ArchiveExtraDataSignature ||
header == ZipConstants.Zip64CentralFileHeaderSignature)
{
// No more individual entries exist
Close();
return null;
}
// -jr- 07-Dec-2003 Ignore spanning temporary signatures if found
// Spanning signature is same as descriptor signature and is untested as yet.
if ((header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature))
{
header = inputBuffer.ReadLeInt();
}
if (header != ZipConstants.LocalHeaderSignature)
{
throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header));
}
var versionRequiredToExtract = (short) inputBuffer.ReadLeShort();
flags = inputBuffer.ReadLeShort();
method = inputBuffer.ReadLeShort();
var dostime = (uint) inputBuffer.ReadLeInt();
var crc2 = inputBuffer.ReadLeInt();
csize = inputBuffer.ReadLeInt();
size = inputBuffer.ReadLeInt();
var nameLen = inputBuffer.ReadLeShort();
var extraLen = inputBuffer.ReadLeShort();
var isCrypted = (flags & 1) == 1;
var buffer = new byte[nameLen];
inputBuffer.ReadRawBuffer(buffer);
var name = ZipConstants.ConvertToStringExt(flags, buffer);
entry = new ZipEntry(name, versionRequiredToExtract);
entry.Flags = flags;
entry.CompressionMethod = (CompressionMethod) method;
if ((flags & 8) == 0)
{
entry.Crc = crc2 & 0xFFFFFFFFL;
entry.Size = size & 0xFFFFFFFFL;
entry.CompressedSize = csize & 0xFFFFFFFFL;
entry.CryptoCheckValue = (byte) ((crc2 >> 24) & 0xff);
}
else
{
// This allows for GNU, WinZip and possibly other archives, the PKZIP spec
// says these values are zero under these circumstances.
if (crc2 != 0)
{
entry.Crc = crc2 & 0xFFFFFFFFL;
}
if (size != 0)
{
entry.Size = size & 0xFFFFFFFFL;
}
if (csize != 0)
{
entry.CompressedSize = csize & 0xFFFFFFFFL;
}
entry.CryptoCheckValue = (byte) ((dostime >> 8) & 0xff);
}
entry.DosTime = dostime;
// If local header requires Zip64 is true then the extended header should contain
// both values.
// Handle extra data if present. This can set/alter some fields of the entry.
if (extraLen > 0)
{
var extra = new byte[extraLen];
inputBuffer.ReadRawBuffer(extra);
entry.ExtraData = extra;
}
entry.ProcessExtraData(true);
if (entry.CompressedSize >= 0)
{
csize = entry.CompressedSize;
}
if (entry.Size >= 0)
{
size = entry.Size;
}
if (method == (int) CompressionMethod.Stored &&
(!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size)))
{
throw new ZipException("Stored, but compressed != uncompressed");
}
// Determine how to handle reading of data if this is attempted.
if (entry.IsCompressionMethodSupported())
{
internalReader = InitialRead;
}
else
{
internalReader = ReadingNotSupported;
}
return entry;
}
/// <summary>
/// Read data descriptor at the end of compressed data.
/// </summary>
private void ReadDataDescriptor()
{
if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature)
{
throw new ZipException("Data descriptor signature not found");
}
entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL;
if (entry.LocalHeaderRequiresZip64)
{
csize = inputBuffer.ReadLeLong();
size = inputBuffer.ReadLeLong();
}
else
{
csize = inputBuffer.ReadLeInt();
size = inputBuffer.ReadLeInt();
}
entry.CompressedSize = csize;
entry.Size = size;
}
/// <summary>
/// Complete cleanup as the final part of closing.
/// </summary>
/// <param name="testCrc">True if the crc value should be tested</param>
private void CompleteCloseEntry(bool testCrc)
{
StopDecrypting();
if ((flags & 8) != 0)
{
ReadDataDescriptor();
}
size = 0;
if (testCrc &&
((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1))
{
throw new ZipException("CRC mismatch");
}
crc.Reset();
if (method == (int) CompressionMethod.Deflated)
{
inf.Reset();
}
entry = null;
}
/// <summary>
/// Closes the current zip entry and moves to the next one.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The stream is closed
/// </exception>
/// <exception cref="ZipException">
/// The Zip stream ends early
/// </exception>
public void CloseEntry()
{
if (crc == null)
{
throw new InvalidOperationException("Closed");
}
if (entry == null)
{
return;
}
if (method == (int) CompressionMethod.Deflated)
{
if ((flags & 8) != 0)
{
// We don't know how much we must skip, read until end.
var tmp = new byte[2048];
// Read will close this entry
while (Read(tmp, 0, tmp.Length) > 0)
{
}
return;
}
csize -= inf.TotalIn;
inputBuffer.Available += inf.RemainingInput;
}
if ((inputBuffer.Available > csize) && (csize >= 0))
{
inputBuffer.Available = (int) (inputBuffer.Available - csize);
}
else
{
csize -= inputBuffer.Available;
inputBuffer.Available = 0;
while (csize != 0)
{
var skipped = (int) base.Skip(csize & 0xFFFFFFFFL);
if (skipped <= 0)
{
throw new ZipException("Zip archive ends early.");
}
csize -= skipped;
}
}
CompleteCloseEntry(false);
}
/// <summary>
/// Reads a byte from the current zip entry.
/// </summary>
/// <returns>
/// The byte or -1 if end of stream is reached.
/// </returns>
public override int ReadByte()
{
var b = new byte[1];
if (Read(b, 0, 1) <= 0)
{
return -1;
}
return b[0] & 0xff;
}
/// <summary>
/// Handle attempts to read by throwing an <see cref="InvalidOperationException"/>.
/// </summary>
/// <param name="destination">The destination array to store data in.</param>
/// <param name="offset">The offset at which data read should be stored.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>Returns the number of bytes actually read.</returns>
private int ReadingNotAvailable(byte[] destination, int offset, int count)
{
throw new InvalidOperationException("Unable to read from this stream");
}
/// <summary>
/// Handle attempts to read from this entry by throwing an exception
/// </summary>
private int ReadingNotSupported(byte[] destination, int offset, int count)
{
throw new ZipException("The compression method for this entry is not supported");
}
/// <summary>
/// Perform the initial read on an entry which may include
/// reading encryption headers and setting up inflation.
/// </summary>
/// <param name="destination">The destination to fill with data read.</param>
/// <param name="offset">The offset to start reading at.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>The actual number of bytes read.</returns>
private int InitialRead(byte[] destination, int offset, int count)
{
if (!CanDecompressEntry)
{
throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version + ")");
}
// Handle encryption if required.
if (entry.IsCrypted)
{
if (password == null)
{
throw new ZipException("No password set.");
}
// Generate and set crypto transform...
var managed = new PkzipClassicManaged();
var key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password));
inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);
var cryptbuffer = new byte[ZipConstants.CryptoHeaderSize];
inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize);
if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue)
{
throw new ZipException("Invalid password");
}
if (csize >= ZipConstants.CryptoHeaderSize)
{
csize -= ZipConstants.CryptoHeaderSize;
}
else if ((entry.Flags & (int) GeneralBitFlags.Descriptor) == 0)
{
throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize));
}
}
else
{
inputBuffer.CryptoTransform = null;
}
if ((method == (int) CompressionMethod.Deflated) && (inputBuffer.Available > 0))
{
inputBuffer.SetInflaterInput(inf);
}
internalReader = BodyRead;
return BodyRead(destination, offset, count);
}
/// <summary>
/// Read a block of bytes from the stream.
/// </summary>
/// <param name="buffer">The destination for the bytes.</param>
/// <param name="offset">The index to start storing data.</param>
/// <param name="count">The number of bytes to attempt to read.</param>
/// <returns>Returns the number of bytes read.</returns>
/// <remarks>Zero bytes read means end of stream.</remarks>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", "Cannot be negative");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", "Cannot be negative");
}
if ((buffer.Length - offset) < count)
{
throw new ArgumentException("Invalid offset/count combination");
}
return internalReader(buffer, offset, count);
}
/// <summary>
/// Reads a block of bytes from the current zip entry.
/// </summary>
/// <returns>
/// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream.
/// </returns>
/// <exception name="IOException">
/// An i/o error occured.
/// </exception>
/// <exception cref="ZipException">
/// The deflated stream is corrupted.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The stream is not open.
/// </exception>
private int BodyRead(byte[] buffer, int offset, int count)
{
if (crc == null)
{
throw new InvalidOperationException("Closed");
}
if ((entry == null) || (count <= 0))
{
return 0;
}
if (offset + count > buffer.Length)
{
throw new ArgumentException("Offset + count exceeds buffer size");
}
var finished = false;
switch (method)
{
case (int) CompressionMethod.Deflated:
count = base.Read(buffer, offset, count);
if (count <= 0)
{
if (!inf.IsFinished)
{
throw new ZipException("Inflater not finished!");
}
inputBuffer.Available = inf.RemainingInput;
if ((flags & 8) == 0 && (inf.TotalIn != csize || inf.TotalOut != size))
{
throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" +
inf.TotalOut);
}
inf.Reset();
finished = true;
}
break;
case (int) CompressionMethod.Stored:
if ((count > csize) && (csize >= 0))
{
count = (int) csize;
}
if (count > 0)
{
count = inputBuffer.ReadClearTextBuffer(buffer, offset, count);
if (count > 0)
{
csize -= count;
size -= count;
}
}
if (csize == 0)
{
finished = true;
}
else
{
if (count < 0)
{
throw new ZipException("EOF in stored block");
}
}
break;
}
if (count > 0)
{
crc.Update(buffer, offset, count);
}
if (finished)
{
CompleteCloseEntry(true);
}
return count;
}
/// <summary>
/// Closes the zip input stream
/// </summary>
public override void Close()
{
internalReader = ReadingNotAvailable;
crc = null;
entry = null;
base.Close();
}
}
}
| |
// 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.Search
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for DataSourcesOperations.
/// </summary>
public static partial class DataSourcesOperationsExtensions
{
/// <summary>
/// Creates a new Azure Search datasource or updates a datasource if it
/// already exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to create or update.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
public static DataSource CreateOrUpdate(this IDataSourcesOperations operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition))
{
return Task.Factory.StartNew(s => ((IDataSourcesOperations)s).CreateOrUpdateAsync(dataSourceName, dataSource, searchRequestOptions, accessCondition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search datasource or updates a datasource if it
/// already exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to create or update.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> CreateOrUpdateAsync(this IDataSourcesOperations operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(dataSourceName, dataSource, searchRequestOptions, accessCondition, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
public static void Delete(this IDataSourcesOperations operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition))
{
Task.Factory.StartNew(s => ((IDataSourcesOperations)s).DeleteAsync(dataSourceName, searchRequestOptions, accessCondition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IDataSourcesOperations operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(dataSourceName, searchRequestOptions, accessCondition, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves a datasource definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource Get(this IDataSourcesOperations operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IDataSourcesOperations)s).GetAsync(dataSourceName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves a datasource definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> GetAsync(this IDataSourcesOperations operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all datasources available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSourceListResult List(this IDataSourcesOperations operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IDataSourcesOperations)s).ListAsync(searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all datasources available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSourceListResult> ListAsync(this IDataSourcesOperations operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource Create(this IDataSourcesOperations operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IDataSourcesOperations)s).CreateAsync(dataSource, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> CreateAsync(this IDataSourcesOperations operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Audio.Track;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Screens.Play.HUD
{
public class PerformancePointsCounter : RollingCounter<int>, ISkinnableDrawable
{
public bool UsesFixedAnchor { get; set; }
protected override bool IsRollingProportional => true;
protected override double RollingDuration => 1000;
private const float alpha_when_invalid = 0.3f;
[CanBeNull]
[Resolved(CanBeNull = true)]
private ScoreProcessor scoreProcessor { get; set; }
[Resolved(CanBeNull = true)]
[CanBeNull]
private GameplayState gameplayState { get; set; }
[CanBeNull]
private List<TimedDifficultyAttributes> timedAttributes;
private readonly CancellationTokenSource loadCancellationSource = new CancellationTokenSource();
private JudgementResult lastJudgement;
public PerformancePointsCounter()
{
Current.Value = DisplayedCount = 0;
}
private Mod[] clonedMods;
[BackgroundDependencyLoader]
private void load(OsuColour colours, BeatmapDifficultyCache difficultyCache)
{
Colour = colours.BlueLighter;
if (gameplayState != null)
{
clonedMods = gameplayState.Mods.Select(m => m.DeepClone()).ToArray();
var gameplayWorkingBeatmap = new GameplayWorkingBeatmap(gameplayState.Beatmap);
difficultyCache.GetTimedDifficultyAttributesAsync(gameplayWorkingBeatmap, gameplayState.Ruleset, clonedMods, loadCancellationSource.Token)
.ContinueWith(task => Schedule(() =>
{
timedAttributes = task.GetResultSafely();
IsValid = true;
if (lastJudgement != null)
onJudgementChanged(lastJudgement);
}), TaskContinuationOptions.OnlyOnRanToCompletion);
}
}
protected override void LoadComplete()
{
base.LoadComplete();
if (scoreProcessor != null)
{
scoreProcessor.NewJudgement += onJudgementChanged;
scoreProcessor.JudgementReverted += onJudgementChanged;
}
if (gameplayState?.LastJudgementResult.Value != null)
onJudgementChanged(gameplayState.LastJudgementResult.Value);
}
private bool isValid;
protected bool IsValid
{
set
{
if (value == isValid)
return;
isValid = value;
DrawableCount.FadeTo(isValid ? 1 : alpha_when_invalid, 1000, Easing.OutQuint);
}
}
private void onJudgementChanged(JudgementResult judgement)
{
lastJudgement = judgement;
var attrib = getAttributeAtTime(judgement);
if (gameplayState == null || attrib == null)
{
IsValid = false;
return;
}
// awkward but we need to make sure the true mods are not passed to PerformanceCalculator as it makes a mess of track applications.
var scoreInfo = gameplayState.Score.ScoreInfo.DeepClone();
scoreInfo.Mods = clonedMods;
var calculator = gameplayState.Ruleset.CreatePerformanceCalculator(attrib, scoreInfo);
Current.Value = (int)Math.Round(calculator?.Calculate().Total ?? 0, MidpointRounding.AwayFromZero);
IsValid = true;
}
[CanBeNull]
private DifficultyAttributes getAttributeAtTime(JudgementResult judgement)
{
if (timedAttributes == null || timedAttributes.Count == 0)
return null;
int attribIndex = timedAttributes.BinarySearch(new TimedDifficultyAttributes(judgement.HitObject.GetEndTime(), null));
if (attribIndex < 0)
attribIndex = ~attribIndex - 1;
return timedAttributes[Math.Clamp(attribIndex, 0, timedAttributes.Count - 1)].Attributes;
}
protected override LocalisableString FormatCount(int count) => count.ToString(@"D");
protected override IHasText CreateText() => new TextComponent
{
Alpha = alpha_when_invalid
};
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (scoreProcessor != null)
{
scoreProcessor.NewJudgement -= onJudgementChanged;
scoreProcessor.JudgementReverted -= onJudgementChanged;
}
loadCancellationSource?.Cancel();
}
private class TextComponent : CompositeDrawable, IHasText
{
public LocalisableString Text
{
get => text.Text;
set => text.Text = value;
}
private readonly OsuSpriteText text;
public TextComponent()
{
AutoSizeAxes = Axes.Both;
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Spacing = new Vector2(2),
Children = new Drawable[]
{
text = new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Font = OsuFont.Numeric.With(size: 16, fixedWidth: true)
},
new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Text = @"pp",
Font = OsuFont.Numeric.With(size: 8),
Padding = new MarginPadding { Bottom = 1.5f }, // align baseline better
}
}
};
}
}
// TODO: This class shouldn't exist, but requires breaking changes to allow DifficultyCalculator to receive an IBeatmap.
private class GameplayWorkingBeatmap : WorkingBeatmap
{
private readonly IBeatmap gameplayBeatmap;
public GameplayWorkingBeatmap(IBeatmap gameplayBeatmap)
: base(gameplayBeatmap.BeatmapInfo, null)
{
this.gameplayBeatmap = gameplayBeatmap;
}
public override IBeatmap GetPlayableBeatmap(IRulesetInfo ruleset, IReadOnlyList<Mod> mods, CancellationToken cancellationToken)
=> gameplayBeatmap;
protected override IBeatmap GetBeatmap() => gameplayBeatmap;
protected override Texture GetBackground() => throw new NotImplementedException();
protected override Track GetBeatmapTrack() => throw new NotImplementedException();
protected internal override ISkin GetSkin() => throw new NotImplementedException();
public override Stream GetStream(string storagePath) => throw new NotImplementedException();
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2014 Microsoft Corporation
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.Threading.Tasks;
using Microsoft.Research.Naiad;
using Microsoft.Research.Naiad.Input;
using Microsoft.Research.Naiad.Dataflow;
using Microsoft.Research.Naiad.Dataflow.PartitionBy;
using Microsoft.Research.Naiad.Dataflow.StandardVertices;
using Microsoft.Research.Naiad.Frameworks.Lindi;
using Microsoft.Research.Naiad.Frameworks.GraphLINQ;
namespace Algorithm3.Indices
{
public static class TypedIndexExtensionMethods
{
/// <summary>
/// Builds an index with an arbitrary type of key
/// </summary>
/// <typeparam name="TKey">The type of the keys</typeparam>
/// <typeparam name="TValue">The type of the values</typeparam>
/// <typeparam name="TRecord">The type of the records</typeparam>
/// <param name="source">The source of records</param>
/// <param name="controller">The controller</param>
/// <param name="keySelector">A function from record to key</param>
/// <param name="valueSelector">A function from record to value</param>
/// <returns>An index of values</returns>
public static TypedKeyIndex<TKey, TValue, TRecord> ToTypedIndex<TKey, TValue, TRecord>(this InterGraphDataSink<TRecord> source, Controller controller, Func<TRecord, TKey> keySelector, Func<TRecord, TValue> valueSelector)
where TValue : IComparable<TValue>
{
return new TypedKeyIndex<TKey, TValue, TRecord>(source, controller, keySelector, valueSelector);
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRecord"></typeparam>
public class TypedKeyIndex<TKey, TValue, TRecord> where TValue : IComparable<TValue>
{
private class Fragment
{
private struct LinkedListNode<T>
{
public T Data;
public int Next;
public LinkedListNode(T data) { this.Data = data; this.Next = -1; }
public LinkedListNode(T data, int next) { this.Data = data; this.Next = next; }
}
private Dictionary<TKey, Pair<int, int>> OffsetCounts = new Dictionary<TKey, Pair<int, int>>();
private TValue[] Values;
private Dictionary<TKey, int> tempDict = new Dictionary<TKey, int>();
private HashSet<Pair<TKey, TValue>> tempHash = new HashSet<Pair<TKey, TValue>>();
private List<LinkedListNode<TValue>> tempList = new List<LinkedListNode<TValue>>();
internal void AddRecords(Pair<TKey, TValue>[] records, int count)
{
for (int i = 0; i < count; i++)
{
var record = records[i];
if (this.tempHash.Add(record))
{
if (!tempDict.ContainsKey(record.First))
{
tempList.Add(new LinkedListNode<TValue>(record.Second));
tempDict.Add(record.First, tempList.Count - 1);
}
else
{
tempList.Add(new LinkedListNode<TValue>(record.Second, tempDict[record.First]));
tempDict[record.First] = tempList.Count - 1;
}
}
}
}
internal Fragment Build()
{
this.Values = new TValue[tempList.Count];
var cursor = 0;
foreach (var key in tempDict.Keys)
{
var start = cursor;
for (int next = tempDict[key]; next != -1; next = tempList[next].Next)
this.Values[cursor++] = tempList[next].Data;
this.OffsetCounts.Add(key, start.PairWith(cursor - start));
}
this.tempDict = null;
this.tempList = null;
this.tempHash = null;
foreach (var pair in this.OffsetCounts.Values)
{
Array.Sort(this.Values, pair.First, pair.Second);
}
return this;
}
internal Int64 Count(TKey prefix) { if (this.OffsetCounts.ContainsKey(prefix)) return this.OffsetCounts[prefix].Second; else return 0; }
internal ArraySegment<TValue> Extend(TKey prefix)
{
Pair<int, int> lookup;
if (this.OffsetCounts.TryGetValue(prefix, out lookup))
return new ArraySegment<TValue>(this.Values, lookup.First, lookup.Second);
else
return new ArraySegment<TValue>(this.Values, 0, 0);
}
private TValue[] tempArray = new TValue[] { };
internal Pair<TKey, TValue[]> Validate(Pair<TKey, TValue[]> extensions)
{
if (this.OffsetCounts.ContainsKey(extensions.First))
{
var offsetCount = this.OffsetCounts[extensions.First];
if (Math.Min(offsetCount.Second, extensions.Second.Length) >= tempArray.Length)
tempArray = new TValue[Math.Max(Math.Min(offsetCount.Second, extensions.Second.Length) + 1, 2 * tempArray.Length)];
var counter = IntersectSortedArrays(new ArraySegment<TValue>(this.Values, offsetCount.First, offsetCount.Second),
new ArraySegment<TValue>(extensions.Second),
tempArray);
if (counter > 0)
{
var resultArray = new TValue[counter];
Array.Copy(tempArray, resultArray, counter);
return extensions.First.PairWith(resultArray);
}
else
return extensions.First.PairWith((TValue[])null);
}
else
return extensions.First.PairWith((TValue[])null);
}
internal static int IntersectSortedArrays<T>(ArraySegment<T> array1, ArraySegment<T> array2, T[] destination) where T : IComparable<T>
{
int matchCount = 0;
int cursor1 = array1.Offset;
int cursor2 = array2.Offset;
int extent1 = array1.Offset + array1.Count;
int extent2 = array2.Offset + array2.Count;
while (cursor1 < extent1 && cursor2 < extent2)
{
if (array1.Array[cursor1].CompareTo(array2.Array[cursor2]) == 0)
{
destination[matchCount] = array1.Array[cursor1];
matchCount++;
cursor1++;
cursor2++;
}
else
{
if (array1.Array[cursor1].CompareTo(array2.Array[cursor2]) < 0)
cursor1 = AdvanceCursor(cursor1, array1, array2.Array[cursor2]);
else
cursor2 = AdvanceCursor(cursor2, array2, array1.Array[cursor1]);
}
}
return matchCount;
}
// returns the position of the first element at least as large as otherValue.
// If no such element exists, returns values.Offset + values.Count.
internal static int AdvanceCursor<T>(int cursor, ArraySegment<T> values, T otherValue) where T : IComparable<T>
{
var extent = values.Offset + values.Count;
int step = 1;
while (cursor + step < extent && values.Array[cursor + step].CompareTo(otherValue) <= 0)
{
cursor = cursor + step;
step *= 2;
}
// either cursor + step is off the end of the array, or points at a value larger than otherValue
while (step > 0)
{
if (cursor + step < extent && values.Array[cursor + step].CompareTo(otherValue) <= 0)
cursor = cursor + step;
step = step / 2;
}
// perhaps we didn't find the right value, but should still advance the cursor to/past the match
if (values.Array[cursor].CompareTo(otherValue) < 0)
cursor++;
return cursor;
}
}
private class Extender<TPrefix> : PrefixExtender<TPrefix, TValue>
{
private readonly Stream<Fragment, Epoch> Index;
private readonly Func<TPrefix, TKey> tupleKey;
public Extender(Stream<Fragment, Epoch> stream, Func<TPrefix, TKey> tKey)
{
this.Index = stream;
this.tupleKey = tKey;
}
public Stream<ExtensionProposal<TPrefix>, Epoch> CountExtensions(Stream<TPrefix, Epoch> stream, int identifier)
{
return this.Index
.IndexJoin(stream, tupleKey, (index, tuple) => new ExtensionProposal<TPrefix>(identifier, tuple, index.Count(tupleKey(tuple))));
}
public Stream<Pair<TPrefix, TValue[]>, Epoch> ExtendPrefixes(Stream<ExtensionProposal<TPrefix>, Epoch> stream, int identifier)
{
return this.Index
.IndexJoin(stream.Where(x => x.Index == identifier)
.Select(x => x.Record),
tupleKey, (index, tuple) => tuple.PairWith(index.Extend(tupleKey(tuple)).ToArray()));
}
public Stream<Pair<TPrefix, TValue[]>, Epoch> ValidateExtensions(Stream<Pair<TPrefix, TValue[]>, Epoch> stream)
{
return this.Index
.IndexJoin(stream, tuple => tupleKey(tuple.First), (index, tuple) => tuple.First.PairWith(index.Validate(tupleKey(tuple.First).PairWith(tuple.Second)).Second))
.Where(x => x.Second != null && x.Second.Length != 0);
}
public Stream<ExtensionProposal<TPrefix>, Epoch> ImproveExtensions(Stream<ExtensionProposal<TPrefix>, Epoch> stream, int identifier)
{
throw new NotImplementedException();
}
public Stream<Pair<TPrefix, TValue>, Epoch> ValidateExtensions(Stream<Pair<TPrefix, TValue>, Epoch> stream)
{
throw new NotImplementedException();
}
}
private readonly InterGraphDataSink<Fragment> result;
public TypedKeyIndex(InterGraphDataSink<TRecord> relation, Controller controller, Func<TRecord, TKey> keySelector, Func<TRecord, TValue> valueSelector)
{
using (var compuation = controller.NewComputation())
{
var stream = compuation.NewInput(relation.NewDataSource())
.Select(x => keySelector(x).PairWith(valueSelector(x)))
.NewUnaryStage((i, s) => new IndexBuilder(i, s), x => x.First.GetHashCode(), null, "IndexBuilder");
result = new InterGraphDataSink<Fragment>(stream);
compuation.Activate();
compuation.Join();
}
}
public PrefixExtender<TPrefix, TValue> CreateExtender<TPrefix>(Computation computation, Func<TPrefix, TKey> prefixKeySelector)
{
return new Extender<TPrefix>(computation.NewInput(result.NewDataSource()), prefixKeySelector);
}
private class IndexBuilder : UnaryVertex<Pair<TKey, TValue>, Fragment, Epoch>
{
Fragment PrefixIndex = new Fragment();
public override void OnReceive(Message<Pair<TKey, TValue>, Epoch> message)
{
this.PrefixIndex.AddRecords(message.payload, message.length);
NotifyAt(message.time);
}
public override void OnNotify(Epoch time)
{
this.Output.GetBufferForTime(time).Send(this.PrefixIndex.Build());
}
public IndexBuilder(int index, Stage<Epoch> stage) : base(index, stage) { }
}
}
}
| |
// AspNetEdit.Editor.Persistence.ControlPersister
// based on Mono's System.Web.UI.Design.ControlPersister
//
// Authors:
// Gert Driesen ([email protected])
// Michael Hutchinson <[email protected]>
//
// (C) 2004 Novell
// (c) 2205 Michael Hutchinson
//
// 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.IO;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web.UI;
using System.Web.UI.Design;
namespace AspNetEdit.Editor.Persistence
{
public sealed class ControlPersister
{
private ControlPersister ()
{
}
#region Public members. They call private methods with some checking and restrictions.
public static string PersistControl (Control control)
{
if (control.Site == null)
return string.Empty;
IDesignerHost host = control.Site.GetService (typeof(IDesignerHost)) as IDesignerHost;
return PersistControl (control, host);
}
public static void PersistControl (TextWriter sw, Control control)
{
if (control.Site == null)
return;
IDesignerHost host = control.Site.GetService (typeof(IDesignerHost)) as IDesignerHost;
PersistControl (sw, control, host);
}
public static string PersistControl (Control control, IDesignerHost host)
{
TextWriter writer = new StringWriter ();
PersistControl (writer, control, host);
writer.Flush ();
return writer.ToString ();
}
public static void PersistControl(TextWriter sw, Control control, IDesignerHost host)
{
//check input
if (host == null)
throw new ArgumentNullException ("host");
if (control == null)
throw new ArgumentNullException ("control");
if (sw == null)
throw new ArgumentNullException ("sw");
//We use an HtmlTextWriter for output
HtmlTextWriter writer;
if (sw is HtmlTextWriter)
writer = (HtmlTextWriter) sw;
else
writer = new HtmlTextWriter (sw);
PersistObject(writer, control, host, true);
}
public static string PersistInnerProperties (object component, IDesignerHost host)
{
TextWriter sw = new StringWriter ();
PersistInnerProperties (sw, component, host);
sw.Flush();
return sw.ToString();
}
public static void PersistInnerProperties (TextWriter sw, object component, IDesignerHost host)
{
//check input
if (host == null)
throw new ArgumentNullException ("host");
if (component == null)
throw new ArgumentNullException ("component");
if (!(component is System.Web.UI.Control))
throw new InvalidOperationException ("Only components that derive from System.Web.UI.Control can be serialised");
//privte method needs an HtmlTextWriter
HtmlTextWriter writer;
if (sw is HtmlTextWriter)
writer = (HtmlTextWriter) sw;
else
writer = new HtmlTextWriter (sw);
//write and flush
PersistInnerProperties (writer, component, host);
writer.Flush();
}
#endregion
private static void PersistObject (HtmlTextWriter writer, object control, IDesignerHost host, bool runAtServer)
{
//look up tag prefix from host
IWebFormReferenceManager refMan = host.GetService (typeof (IWebFormReferenceManager)) as IWebFormReferenceManager;
if (refMan == null)
throw new Exception("Could not obtain IWebFormReferenceManager service");
string prefix = refMan.GetTagPrefix (control.GetType ());
//write tag to HtmlTextWriter
writer.WriteBeginTag (prefix + ":" + control.GetType().Name);
//go through all the properties and add attributes if necessary
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (control);
foreach (PropertyDescriptor prop in properties)
ProcessAttribute (prop, control, writer, string.Empty);
if (runAtServer)
writer.WriteAttribute ("runat", "server");
//do the same for events
IComponent comp = control as IComponent;
if (comp != null && comp.Site != null) {
IEventBindingService evtBind = (IEventBindingService) comp.Site.GetService (typeof (IEventBindingService));
if (evtBind != null)
foreach (EventDescriptor e in TypeDescriptor.GetEvents (comp))
ProcessEvent (e, comp, writer, evtBind);
}
//ControlDesigner designer = (ControlDesigner) host.GetDesigner(control);
//TODO: we don't yet support designer.GetPersistInnerHtml() 'cause we don't have the designers...
if (HasInnerProperties(control)) {
writer.Write (HtmlTextWriter.TagRightChar);
writer.Indent++;
PersistInnerProperties (writer, control, host);
writer.Indent--;
writer.WriteEndTag (prefix + ":" + control.GetType ().Name);
}
else
writer.Write (HtmlTextWriter.SelfClosingTagEnd);
writer.WriteLine ();
writer.Flush ();
}
private static void ProcessEvent (EventDescriptor e, IComponent comp, HtmlTextWriter writer, IEventBindingService evtBind)
{
PropertyDescriptor prop = evtBind.GetEventProperty (e);
string value = prop.GetValue (comp) as string;
if (prop.SerializationVisibility != DesignerSerializationVisibility.Visible
|| value == null
|| prop.DesignTimeOnly
|| prop.IsReadOnly
|| !prop.ShouldSerializeValue (comp))
return;
writer.WriteAttribute ("On" + prop.Name, value);
}
/// <summary>
/// Writes an attribute to an HtmlTextWriter if it needs serializing
/// </summary>
/// <returns>True if it does any writing</returns>
private static bool ProcessAttribute (PropertyDescriptor prop, object o, HtmlTextWriter writer, string prefix)
{
//check whether we're serialising it
if (prop.SerializationVisibility == DesignerSerializationVisibility.Hidden
|| prop.DesignTimeOnly
|| prop.IsReadOnly
|| !prop.ShouldSerializeValue (o)
|| prop.Converter == null
|| !prop.Converter.CanConvertTo (typeof(string)))
return false;
bool foundAttrib = false;
//is this an attribute? If it's content, we deal with it later.
PersistenceModeAttribute modeAttrib = prop.Attributes[typeof (PersistenceModeAttribute)] as PersistenceModeAttribute;
if (modeAttrib == null || modeAttrib.Mode == PersistenceMode.Attribute)
{
if (prop.SerializationVisibility == DesignerSerializationVisibility.Visible) {
if (prefix == string.Empty)
writer.WriteAttribute (prop.Name, prop.Converter.ConvertToString (prop.GetValue (o)));
else
writer.WriteAttribute (prefix + "-" + prop.Name, prop.Converter.ConvertToString (prop.GetValue(o)));
foundAttrib = true;
}
//recursively handle subproperties
else if (prop.SerializationVisibility == DesignerSerializationVisibility.Content) {
object val = prop.GetValue (o);
foreach (PropertyDescriptor p in prop.GetChildProperties (val))
if (ProcessAttribute (p, val, writer, prop.Name))
foundAttrib = true;
}
}
return foundAttrib;
}
private static void PersistInnerProperties (HtmlTextWriter writer, object component, IDesignerHost host)
{
//Do we have child controls as inner content of control?
PersistChildrenAttribute persAtt = TypeDescriptor.GetAttributes (component)[typeof (PersistChildrenAttribute)] as PersistChildrenAttribute;
if (persAtt != null && persAtt.Persist && (component is Control))
{
if (((Control)component).Controls.Count > 0)
{
writer.Indent++;
foreach (Control child in ((Control) component).Controls) {
PersistControl (writer, child, host);
}
writer.Indent--;
}
}
//We don't, so we're going to have to go though the properties
else
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (component);
bool contentStarted = false;
foreach (PropertyDescriptor prop in properties)
{
//check whether we're serialising it
if (prop.SerializationVisibility == DesignerSerializationVisibility.Hidden
|| prop.DesignTimeOnly
//|| !prop.ShouldSerializeValue (component) //confused by collections...
|| prop.Converter == null)
continue;
PersistenceModeAttribute modeAttrib = prop.Attributes[typeof(PersistenceModeAttribute)] as PersistenceModeAttribute;
if (modeAttrib == null || modeAttrib.Mode == PersistenceMode.Attribute)
continue;
//handle the different modes
switch (modeAttrib.Mode)
{
case PersistenceMode.EncodedInnerDefaultProperty:
if (contentStarted)
throw new Exception("The Control has inner properties in addition to a default inner property");
if (prop.Converter.CanConvertTo (typeof (string))){
writer.Write(System.Web.HttpUtility.HtmlEncode (prop.Converter.ConvertToString (prop.GetValue (component))));
return;
}
break;
case PersistenceMode.InnerDefaultProperty:
if (contentStarted)
throw new Exception("The Control has inner properties in addition to a default inner property");
PersistInnerProperty(prop, prop.GetValue (component), writer, host, true);
return;
case PersistenceMode.InnerProperty:
PersistInnerProperty (prop, prop.GetValue (component), writer, host, false);
contentStarted = true;
break;
}
}
writer.WriteLine();
}
}
//once we've determined we need to persist a property, this does the actual work
private static void PersistInnerProperty (PropertyDescriptor prop, object value, HtmlTextWriter writer, IDesignerHost host, bool isDefault)
{
//newline and indent
writer.WriteLine();
//trivial case
if (value == null) {
if (!isDefault) {
writer.WriteBeginTag (prop.Name);
writer.Write (HtmlTextWriter.SelfClosingTagEnd);
}
return;
}
//A collection? Persist individual objects.
if (value is ICollection) {
if (((ICollection) value).Count > 0) {
//if default property needs no surrounding tags
if(!isDefault) {
writer.WriteFullBeginTag (prop.Name);
writer.Indent++;
}
foreach (object o in (ICollection)value)
PersistObject (writer, o, host, false);
if(!isDefault) {
writer.Indent--;
writer.WriteEndTag (prop.Name);
}
}
}
//default but not collection: just write content
else if (isDefault) {
if (prop.Converter.CanConvertTo (typeof (string))){
writer.Write (prop.Converter.ConvertToString (value));
return;
}
}
//else: a tag of property name, with sub-properties as attribs
else {
//only want to render tag if it has any attributes
writer.WriteBeginTag (prop.Name);
foreach (PropertyDescriptor p in TypeDescriptor.GetProperties(value))
ProcessAttribute (p, value, writer, string.Empty);
writer.Write (HtmlTextWriter.SelfClosingTagEnd);
}
}
//simply checks if there are any inner properties to render so we can use self-closing tags
private static bool HasInnerProperties (object component)
{
if (component == null)
throw new ArgumentNullException ("component");
//Do we have child controls as inner content of control?
PersistChildrenAttribute persAtt = TypeDescriptor.GetAttributes (component)[typeof(PersistChildrenAttribute)] as PersistChildrenAttribute;
if (persAtt != null && persAtt.Persist && (component is Control))
{
return true;
}
//We don't, so we're going to have to go though the properties
else
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (component);
foreach (PropertyDescriptor prop in properties)
{
//check whether we're serialising it
if (prop.SerializationVisibility == DesignerSerializationVisibility.Hidden
|| prop.DesignTimeOnly
//|| !prop.ShouldSerializeValue(component) //confused by collections....
|| prop.Converter == null)
continue;
PersistenceModeAttribute modeAttrib = prop.Attributes[typeof (PersistenceModeAttribute)] as PersistenceModeAttribute;
if (modeAttrib == null || modeAttrib.Mode == PersistenceMode.Attribute)
continue;
return true;
}
}
return false;
}
}
}
| |
/*
This file is licensed to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using net.sf.xmlunit.exceptions;
namespace net.sf.xmlunit.transform {
/// <summary>
/// Provides a convenience layer over System.Xml.Xsl.
/// </summary>
/// <remarks>
/// Apart from ArgumentExceptions if you try to pass in null
/// values only the Transform methods will ever throw exceptions
/// and these will be XMLUnit's exceptions.
///
/// Each invocation of a Transform method will use a fresh
/// XslCompiledTransform instance, the Transform methods are
/// thread-safe.
/// </remarks>
public sealed class Transformation {
private ISource source;
private ISource styleSheet;
private XmlResolver xmlResolver = null;
private readonly XsltSettings settings = new XsltSettings();
private readonly XsltArgumentList args = new XsltArgumentList();
public Transformation() {
}
/// <param name="s">the source to transform - must not be null.</param>
public Transformation(ISource s) {
Source = s;
}
/// <summary>
/// Set the source document to transform - must not be null.
/// </summary>
public ISource Source {
set {
if (value == null) {
throw new ArgumentNullException();
}
source = value;
}
}
/// <summary>
/// Set the stylesheet to use - may be null in which case an
/// identity transformation will be performed.
/// </summary>
/// <param name="s">the stylesheet to use</param>
public ISource Stylesheet {
set {
styleSheet = value;
}
}
/// <summary>
/// Add a named extension object.
/// </summary>
public void AddExtensionObject(string namespaceUri, object extension) {
if (namespaceUri == null) {
throw new ArgumentNullException("namespaceUri");
}
args.AddExtensionObject(namespaceUri, extension);
}
/// <summary>
/// Clears all extension objects and parameters.
/// </summary>
public void Clear() {
args.Clear();
}
/// <summary>
/// Add a named parameter.
/// </summary>
public void AddParameter(string name, string nsUri, object parameter) {
if (name == null) {
throw new ArgumentNullException("name");
}
if (nsUri == null) {
throw new ArgumentNullException("nsUri");
}
args.AddParam(name, nsUri, parameter);
}
/// <summary>
/// Set the resolver to use for document() and xsl:include/import
/// </summary>
/// <remarks>may be null in which case an empty XmlUrlResolver
/// will be used.</remarks>
public XmlResolver XmlResolver {
set {
xmlResolver = value;
}
}
/// <summary>
/// Whether the document() function will be allowed.
/// </summary>
public bool EnableDocumentFunction {
set {
settings.EnableDocumentFunction = value;
}
}
/// <summary>
/// Whether embedded script blocks will be allowed.
/// </summary>
public bool EnableScriptBlocks {
set {
settings.EnableScript = value;
}
}
/// <summary>
/// Perform the transformation.
/// </summary>
public void TransformTo(Stream stream) {
if (stream == null) {
throw new ArgumentNullException("stream");
}
Transform(TransformToStream(stream));
}
/// <summary>
/// Perform the transformation.
/// </summary>
public void TransformTo(TextWriter writer) {
if (writer == null) {
throw new ArgumentNullException("writer");
}
Transform(TransformToTextWriter(writer));
}
/// <summary>
/// Perform the transformation.
/// </summary>
public void TransformTo(XmlWriter writer) {
if (writer == null) {
throw new ArgumentNullException("writer");
}
Transform(TransformToXmlWriter(writer));
}
/// <summary>
/// Perform the transformation.
/// </summary>
private void Transform(Transformer transformer) {
if (source == null) {
throw new ArgumentNullException("source");
}
try {
XslCompiledTransform t = new XslCompiledTransform();
if (styleSheet != null) {
t.Load(styleSheet.Reader, settings, xmlResolver);
}
transformer(t, source.Reader, args);
} catch (System.Exception ex) {
throw new XMLUnitException(ex);
}
}
/// <summary>
/// Convenience method that returns the result of the
/// transformation as a String.
/// </summary>
public string TransformToString() {
StringWriter sw = new StringWriter();
TransformTo(sw);
return sw.ToString();
}
/// <summary>
/// Convenience method that returns the result of the
/// transformation as a Document.
/// </summary>
public XmlDocument TransformToDocument() {
using (MemoryStream ms = new MemoryStream()) {
TransformTo(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
XmlDocument doc = new XmlDocument();
doc.Load(ms);
return doc;
}
}
private delegate void Transformer(XslCompiledTransform t,
XmlReader r,
XsltArgumentList args);
private static Transformer TransformToStream(Stream stream) {
return delegate(XslCompiledTransform t, XmlReader r,
XsltArgumentList args) {
t.Transform(r, args, stream);
};
}
private static Transformer TransformToTextWriter(TextWriter tw) {
return delegate(XslCompiledTransform t, XmlReader r,
XsltArgumentList args) {
t.Transform(r, args, tw);
};
}
private static Transformer TransformToXmlWriter(XmlWriter xw) {
return delegate(XslCompiledTransform t, XmlReader r,
XsltArgumentList args) {
t.Transform(r, args, xw);
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using bv.model.BLToolkit;
using bv.winclient.Layout;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using eidss.model.Reports.Common;
using eidss.model.Reports.OperationContext;
using EIDSS.Reports.BaseControls.Filters;
using EIDSS.Reports.BaseControls.Keeper;
namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers
{
public partial class BaseComparativeReportKeeper : BaseReportKeeper
{
private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (BaseComparativeReportKeeper));
private List<ItemWrapper> m_MonthCollection;
private List<ItemWrapper> m_CounterCollection;
public BaseComparativeReportKeeper()
: base(new Dictionary<string, string>())
{
InitializeComponent();
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
SetMandatory();
Year2SpinEdit.Value = DateTime.Now.Year;
Year1SpinEdit.Value = DateTime.Now.Year - 1;
BindLookup(StartMonthLookUp, MonthCollection, EndYearLabel.Text);
BindLookup(EndMonthLookUp, MonthCollection, EndMonthLabel.Text);
StartMonthLookUp.EditValue = MonthCollection[0];
EndMonthLookUp.EditValue = MonthCollection[DateTime.Now.Month - 1];
CounterLookUp.EditValue = CounterCollection[0];
}
m_HasLoad = true;
}
#region Properties
[Browsable(false)]
protected int Year1Param
{
get { return (int) Year1SpinEdit.Value; }
}
[Browsable(false)]
protected int Year2Param
{
get { return (int) Year2SpinEdit.Value; }
}
[Browsable(false)]
protected int? StartMonthParam
{
get
{
return (StartMonthLookUp.EditValue == null)
? (int?) null
: ((ItemWrapper) StartMonthLookUp.EditValue).Number;
}
}
[Browsable(false)]
protected int? EndMonthParam
{
get
{
return (EndMonthLookUp.EditValue == null)
? (int?) null
: ((ItemWrapper) EndMonthLookUp.EditValue).Number;
}
}
[Browsable(false)]
protected int CounterParam
{
get
{
return (CounterLookUp.EditValue == null)
? -1
: ((ItemWrapper) CounterLookUp.EditValue).Number;
}
}
[Browsable(false)]
protected long? FirstRegionIdParam
{
get { return region1Filter.RegionId > 0 ? (long?) region1Filter.RegionId : null; }
}
[Browsable(false)]
protected long? FirstRayonIdParam
{
get { return rayon1Filter.RayonId > 0 ? (long?) rayon1Filter.RayonId : null; }
}
[Browsable(false)]
protected long? SecondRegionIdParam
{
get { return region2Filter.RegionId > 0 ? (long?) region2Filter.RegionId : null; }
}
[Browsable(false)]
protected long? SecondRayonIdParam
{
get { return rayon2Filter.RayonId > 0 ? (long?) rayon2Filter.RayonId : null; }
}
protected List<ItemWrapper> MonthCollection
{
get { return m_MonthCollection ?? (m_MonthCollection = FilterHelper.GetWinMonthList()); }
}
protected List<ItemWrapper> CounterCollection
{
get { return m_CounterCollection ?? (m_CounterCollection = FilterHelper.GetWinCounterList()); }
}
#endregion
protected internal override void ApplyResources(DbManagerProxy manager)
{
m_MonthCollection = null;
m_CounterCollection = null;
base.ApplyResources(manager);
//m_Resources.ApplyResources(StartMonthLookUp, "StartMonthLookUp");
//m_Resources.ApplyResources(EndMonthLookUp, "EndMonthLookUp");
m_Resources.ApplyResources(StartYearLabel, "StartYearLabel");
m_Resources.ApplyResources(EndYearLabel, "EndYearLabel");
m_Resources.ApplyResources(StartMonthLabel, "StartMonthLabel");
m_Resources.ApplyResources(EndMonthLabel, "EndMonthLabel");
m_Resources.ApplyResources(CounterLabel, "CounterLabel");
m_Resources.ApplyResources(DistrictLabel, "DistrictLabel");
m_Resources.ApplyResources(ProvinceLabel, "ProvinceLabel");
// Note: do not load resources for spinEdit because it reset it's value
//m_Resources.ApplyResources(spinEdit, "spinEdit");
ApplyLookupResources(StartMonthLookUp, MonthCollection, StartMonthParam, EndYearLabel.Text);
ApplyLookupResources(EndMonthLookUp, MonthCollection, EndMonthParam, EndMonthLabel.Text);
ApplyLookupResources(CounterLookUp, CounterCollection, CounterParam, CounterLabel.Text);
region1Filter.DefineBinding();
rayon1Filter.DefineBinding();
region2Filter.DefineBinding();
rayon2Filter.DefineBinding();
region1Filter.Top = 56;
rayon1Filter.Top = 55;
region2Filter.Top = 100;
rayon2Filter.Top = 99;
ceUseArchiveData.Top = 116;
}
protected virtual void CorrectYearRange()
{
if (Year2Param < Year1Param)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
Year2SpinEdit.EditValue = Year1SpinEdit.EditValue;
}
}
}
private void SetMandatory()
{
BaseFilter.SetLookupMandatory(CounterLookUp);
LayoutCorrector.SetStyleController(Year1SpinEdit, LayoutCorrector.MandatoryStyleController);
LayoutCorrector.SetStyleController(Year2SpinEdit, LayoutCorrector.MandatoryStyleController);
}
private void seYear1_EditValueChanged(object sender, EventArgs e)
{
CorrectYearRange();
}
private void seYear2_EditValueChanged(object sender, EventArgs e)
{
CorrectYearRange();
}
private void StartMonth_EditValueChanged(object sender, EventArgs e)
{
CorrectMonthRange();
}
private void EndMonth_EditValueChanged(object sender, EventArgs e)
{
CorrectMonthRange();
}
private void CorrectMonthRange()
{
if ((EndMonthLookUp.EditValue != null) && (StartMonthLookUp.EditValue != null))
{
var startMonth = ((ItemWrapper) (StartMonthLookUp.EditValue));
var endMonth = ((ItemWrapper) (EndMonthLookUp.EditValue));
if (endMonth.Number < startMonth.Number)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
EndMonthLookUp.EditValue = StartMonthLookUp.EditValue;
}
}
}
}
private void cbMonth_ButtonClick(object sender, ButtonPressedEventArgs e)
{
if (e.Button.Kind == ButtonPredefines.Delete && sender is LookUpEdit)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
StartMonthLookUp.EditValue = null;
EndMonthLookUp.EditValue = null;
}
}
}
private void region1Filter_ValueChanged(object sender, SingleFilterEventArgs e)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
{
LocationHelper.RegionFilterValueChanged(region1Filter, rayon1Filter, e);
}
}
private void rayon1Filter_ValueChanged(object sender, SingleFilterEventArgs e)
{
if (ContextKeeper.ContainsContext(ContextValue.ReportFilterResetting))
{
return;
}
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
{
LocationHelper.RayonFilterValueChanged(region1Filter, rayon1Filter, e);
}
}
private void region2Filter_ValueChanged(object sender, SingleFilterEventArgs e)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
{
LocationHelper.RegionFilterValueChanged(region2Filter, rayon2Filter, e);
}
}
private void rayon2Filter_ValueChanged(object sender, SingleFilterEventArgs e)
{
if (ContextKeeper.ContainsContext(ContextValue.ReportFilterResetting))
{
return;
}
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
{
LocationHelper.RayonFilterValueChanged(region2Filter, rayon2Filter, e);
}
}
}
}
| |
// 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.Security;
using System;
public struct TestStruct
{
public int IntValue;
public string StringValue;
}
public class DisposableClass : IDisposable
{
public void Dispose()
{
}
}
/// <summary>
/// ctor(System.Object)
/// </summary>
[SecuritySafeCritical]
public class WeakReferenceCtor2
{
#region Private Fields
private const int c_MIN_STRING_LENGTH = 8;
private const int c_MAX_STRING_LENGTH = 1024;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Ctor with valid target reference");
try
{
Object obj = new Object();
WeakReference reference = new WeakReference(obj);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(obj)))
{
TestLibrary.TestFramework.LogError("001.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", obj = " + obj.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Ctor with IntPtr.Zero reference");
try
{
Object desiredValue = IntPtr.Zero;
WeakReference reference = new WeakReference(desiredValue);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("002.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
desiredValue = new IntPtr(TestLibrary.Generator.GetInt32(-55));
reference = new WeakReference(desiredValue);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("002.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Ctor with value type target reference");
try
{
int randValue = TestLibrary.Generator.GetInt32(-55);
WeakReference reference = new WeakReference(randValue);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(randValue)))
{
TestLibrary.TestFramework.LogError("003.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", randValue = " + randValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Ctor with reference type target reference");
try
{
string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
WeakReference reference = new WeakReference(randValue);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(randValue)))
{
TestLibrary.TestFramework.LogError("004.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", randValue = " + randValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Call Ctor with null reference");
try
{
WeakReference reference = new WeakReference(null);
if ((reference.TrackResurrection != false) || (reference.Target != null))
{
TestLibrary.TestFramework.LogError("005.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Call Ctor with IntPtr reference and set trackResurrection to true");
try
{
DisposableClass dc = new DisposableClass();
Object desiredValue = dc;
WeakReference reference = new WeakReference(desiredValue);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("006.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006.7", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Call Ctor with IntPtr reference and set trackResurrection to true");
try
{
TestStruct ts = new TestStruct();
ts.IntValue = TestLibrary.Generator.GetInt32(-55);
ts.StringValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
Object desiredValue = ts;
WeakReference reference = new WeakReference(desiredValue);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("007.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
WeakReferenceCtor2 test = new WeakReferenceCtor2();
TestLibrary.TestFramework.BeginTestCase("WeakReferenceCtor2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Relisten.Api.Models;
namespace Relisten.Data
{
public class EntityOneToManyMapper<TP, TC, TPk>
{
private readonly IDictionary<TPk, TP> _lookup = new Dictionary<TPk, TP>();
public Action<TP, TC> AddChildAction { get; set; }
public Func<TP, TPk> ParentKey { get; set; }
public virtual TP Map(TP parent, TC child)
{
TP entity;
var found = true;
var primaryKey = ParentKey(parent);
if (!_lookup.TryGetValue(primaryKey, out entity))
{
_lookup.Add(primaryKey, parent);
entity = parent;
found = false;
}
AddChildAction(entity, child);
return !found ? entity : default;
}
}
public class SourceService : RelistenDataServiceBase
{
public SourceService(
DbService db,
SourceSetService sourceSetService
) : base(db)
{
_sourceSetService = sourceSetService;
}
private SourceSetService _sourceSetService { get; }
public async Task<Source> ForUpstreamIdentifier(Artist artist, string upstreamId)
{
return await db.WithConnection(con => con.QueryFirstOrDefaultAsync<Source>(@"
SELECT
src.*
FROM
sources src
WHERE
src.artist_id = @artistId
AND src.upstream_identifier = @upstreamId
", new {artistId = artist.id, upstreamId}));
}
public Task<IEnumerable<SourceFull>> FullSourcesForShow(Artist artist, Show show)
{
return FullSourcesGeneric(
"s.artist_id = @artistId AND s.show_id = @showId",
new {showId = show.id, artistId = artist.id}
);
}
public async Task<IEnumerable<SourceFull>> FullSourcesGeneric(string where, object param)
{
var LinkMapper = new EntityOneToManyMapper<SourceFull, Link, int>
{
AddChildAction = (source, link) =>
{
if (source.links == null)
{
source.links = new List<Link>();
}
if (link != null)
{
source.links.Add(link);
}
},
ParentKey = source => source.id
};
var TrackMapper = new EntityOneToManyMapper<SourceSet, SourceTrack, int>
{
AddChildAction = (set, track) =>
{
if (set.tracks == null)
{
set.tracks = new List<SourceTrack>();
}
if (track != null)
{
set.tracks.Add(track);
}
},
ParentKey = set => set.id
};
return await db.WithConnection(async con =>
{
var t_srcsWithReviews = await con.QueryAsync<SourceFull, Link, SourceFull>($@"
SELECT
s.*
, a.uuid as artist_uuid
, v.uuid as venue_uuid
, sh.uuid as show_uuid
, COALESCE(review_counts.source_review_count, 0) as review_count
, l.*
FROM
sources s
JOIN artists a ON a.id = s.artist_id
LEFT JOIN venues v ON v.id = s.venue_id
LEFT JOIN shows sh ON sh.id = s.show_id
LEFT JOIN links l ON l.source_id = s.id
LEFT JOIN source_review_counts review_counts ON review_counts.source_id = s.id
WHERE
{where}
ORDER BY
s.avg_rating_weighted DESC
",
LinkMapper.Map,
param
);
var t_setsWithTracks = await con.QueryAsync<SourceSet, SourceTrack, SourceSet>($@"
SELECT
sets.*, a.uuid as artist_uuid, s.uuid as source_uuid
, t.*, s.uuid as source_uuid, sets.uuid as source_set_uuid, a.uuid as artist_uuid
FROM
source_sets sets
LEFT JOIN sources s ON s.id = sets.source_id
LEFT JOIN artists a ON a.id = s.artist_id
LEFT JOIN source_tracks t ON t.source_set_id = sets.id
WHERE
{where}
ORDER BY
sets.index ASC, t.track_position ASC
",
TrackMapper.Map,
param
);
var setsWithTracks = t_setsWithTracks
.Where(s => s != null)
.GroupBy(s => s.source_id)
.ToDictionary(grp => grp.Key, grp => grp.AsList())
;
var sources = t_srcsWithReviews
.Where(s => s != null)
.ToList();
foreach (var src in sources)
{
src.sets = setsWithTracks[src.id];
}
return sources;
});
}
public Task<IEnumerable<SourceReview>> ReviewsForSource(int sourceId)
{
return db.WithConnection(conn => conn.QueryAsync<SourceReview>(@"
SELECT
r.*
FROM
source_reviews r
WHERE
r.source_id = @sourceId
ORDER BY
r.updated_at DESC
", new {sourceId}));
}
public Task<IEnumerable<SlimSourceWithShowVenueAndArtist>> SlimSourceWithShowAndArtistForIds(IList<int> ids)
{
return db.WithConnection(con =>
con.QueryAsync<SlimSourceWithShowVenueAndArtist, SlimArtistWithFeatures, Features, Show,
VenueWithShowCount, Venue, SlimSourceWithShowVenueAndArtist>(@"
SELECT
s.*, a.*, f.*, sh.*, shVenue.*, shVenue_counts.shows_at_venue, sVenue.*
FROM
sources s
JOIN artists a ON s.artist_id = a.id
JOIN features f ON f.artist_id = a.id
JOIN shows sh ON sh.id = s.show_id
LEFT JOIN venues shVenue ON shVenue.id = sh.venue_id
LEFT JOIN venues sVenue ON sVenue.id = sh.venue_id
LEFT JOIN venue_show_counts shVenue_counts ON shVenue_counts.id = sh.venue_id
WHERE
s.id = ANY(@ids)
", (s, a, f, sh, shVenue, sVenue) =>
{
sh.venue = shVenue;
s.venue = sVenue;
a.features = f;
s.artist = a;
s.show = sh;
return s;
}, new {ids}));
}
public async Task<IEnumerable<Source>> AllForArtist(Artist artist)
{
return await db.WithConnection(con => con.QueryAsync<Source>(@"
SELECT
s.*
FROM
sources s
WHERE
s.artist_id = @id
", new {artist.id}));
}
public async Task<IEnumerable<SourceReviewInformation>> AllSourceReviewInformationForArtist(Artist artist)
{
return await db.WithConnection(con => con.QueryAsync<SourceReviewInformation>(@"
SELECT
r.source_id
, s.upstream_identifier
, r.source_review_max_updated_at as review_max_updated_at
, r.source_review_count as review_count
FROM
sources s
JOIN source_review_counts r ON s.id = r.source_id
WHERE
s.artist_id = @id
", new {artist.id}));
}
public async Task<int> RemoveSourcesWithUpstreamIdentifiers(IEnumerable<string> upstreamIdentifiers)
{
return await db.WithConnection(con => con.ExecuteAsync(@"
DELETE FROM
sources
WHERE
upstream_identifier = ANY(@upstreamIdentifiers)
", new {upstreamIdentifiers = upstreamIdentifiers.ToList()}));
}
public async Task<Source> Save(Source source)
{
var p = new
{
source.id,
source.artist_id,
source.show_id,
source.is_soundboard,
source.is_remaster,
source.avg_rating,
source.num_reviews,
source.upstream_identifier,
source.has_jamcharts,
source.description,
source.taper_notes,
source.source,
source.taper,
source.transferrer,
source.lineage,
source.updated_at,
source.display_date,
source.venue_id,
source.num_ratings,
source.flac_type
};
return await db.WithConnection(con => con.QuerySingleAsync<Source>(@"
INSERT INTO
sources
(
artist_id,
show_id,
is_soundboard,
is_remaster,
avg_rating,
num_reviews,
upstream_identifier,
has_jamcharts,
description,
taper_notes,
source,
taper,
transferrer,
lineage,
updated_at,
display_date,
venue_id,
num_ratings,
flac_type,
uuid
)
VALUES
(
@artist_id,
@show_id,
@is_soundboard,
@is_remaster,
@avg_rating,
@num_reviews,
@upstream_identifier,
@has_jamcharts,
@description,
@taper_notes,
@source,
@taper,
@transferrer,
@lineage,
@updated_at,
@display_date,
@venue_id,
@num_ratings,
@flac_type,
md5(@artist_id || '::source::' || @upstream_identifier)::uuid
)
ON CONFLICT ON CONSTRAINT sources_uuid_key
DO
UPDATE SET
artist_id = EXCLUDED.artist_id,
show_id = EXCLUDED.show_id,
is_soundboard = EXCLUDED.is_soundboard,
is_remaster = EXCLUDED.is_remaster,
avg_rating = EXCLUDED.avg_rating,
num_reviews = EXCLUDED.num_reviews,
upstream_identifier = EXCLUDED.upstream_identifier,
has_jamcharts = EXCLUDED.has_jamcharts,
description = EXCLUDED.description,
taper_notes = EXCLUDED.taper_notes,
source = EXCLUDED.source,
taper = EXCLUDED.taper,
transferrer = EXCLUDED.transferrer,
lineage = EXCLUDED.lineage,
updated_at = EXCLUDED.updated_at,
display_date = EXCLUDED.display_date,
venue_id = EXCLUDED.venue_id,
num_ratings = EXCLUDED.num_ratings,
flac_type = EXCLUDED.flac_type
RETURNING *
", p));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
/*******************************************************************************
* Free ASP.net IMDb Scraper API for the new IMDb Template.
* Author: Abhinay Rathore
* Website: http://www.AbhinayRathore.com
* Blog: http://web3o.blogspot.com
* More Info: http://web3o.blogspot.com/2010/11/aspnetc-imdb-scraping-api.html
* Last Updated: Feb 20, 2013
*******************************************************************************/
namespace IMDb_Scraper
{
public class IMDb
{
public bool status { get; set; }
public string Id { get; set; }
public string Title { get; set; }
public string OriginalTitle { get; set; }
public string Year { get; set; }
public string Rating { get; set; }
public ArrayList Genres { get; set; }
public ArrayList Directors { get; set; }
public ArrayList Writers { get; set; }
public ArrayList Cast { get; set; }
public ArrayList Producers { get; set; }
public ArrayList Musicians { get; set; }
public ArrayList Cinematographers { get; set; }
public ArrayList Editors { get; set; }
public string MpaaRating { get; set; }
public string ReleaseDate { get; set; }
public string Plot { get; set; }
public ArrayList PlotKeywords { get; set; }
public string Poster { get; set; }
public string PosterLarge { get; set; }
public string PosterFull { get; set; }
public string Runtime { get; set; }
public string Top250 { get; set; }
public string Oscars { get; set; }
public string Awards { get; set; }
public string Nominations { get; set; }
public string Storyline { get; set; }
public string Tagline { get; set; }
public string Votes { get; set; }
public ArrayList Languages { get; set; }
public ArrayList Countries { get; set; }
public ArrayList ReleaseDates { get; set; }
public ArrayList MediaImages { get; set; }
public ArrayList RecommendedTitles { get; set; }
public string ImdbURL { get; set; }
//Search Engine URLs
private string GoogleSearch = "http://www.google.com/search?q=imdb+";
private string BingSearch = "http://www.bing.com/search?q=imdb+";
private string AskSearch = "http://www.ask.com/web?q=imdb+";
//Constructor
public IMDb(string MovieName, bool GetExtraInfo = true)
{
string imdbUrl = getIMDbUrl(System.Uri.EscapeUriString(MovieName));
status = false;
if (!string.IsNullOrEmpty(imdbUrl))
{
parseIMDbPage(imdbUrl, GetExtraInfo);
}
}
//Get IMDb URL from search results
private string getIMDbUrl(string MovieName, string searchEngine = "google")
{
string url = GoogleSearch + MovieName; //default to Google search
if (searchEngine.ToLower().Equals("bing")) url = BingSearch + MovieName;
if (searchEngine.ToLower().Equals("ask")) url = AskSearch + MovieName;
string html = getUrlData(url);
ArrayList imdbUrls = matchAll(@"<a href=""(http://www.imdb.com/title/tt\d{7}/)"".*?>.*?</a>", html);
if (imdbUrls.Count > 0)
return (string)imdbUrls[0]; //return first IMDb result
else if (searchEngine.ToLower().Equals("google")) //if Google search fails
return getIMDbUrl(MovieName, "bing"); //search using Bing
else if (searchEngine.ToLower().Equals("bing")) //if Bing search fails
return getIMDbUrl(MovieName, "ask"); //search using Ask
else //search fails
return string.Empty;
}
//Parse IMDb page data
private void parseIMDbPage(string imdbUrl, bool GetExtraInfo)
{
string html = getUrlData(imdbUrl+"combined");
Id = match(@"<link rel=""canonical"" href=""http://www.imdb.com/title/(tt\d{7})/combined"" />", html);
if (!string.IsNullOrEmpty(Id))
{
status = true;
Title = match(@"<title>(IMDb \- )*(.*?) \(.*?</title>", html, 2);
OriginalTitle = match(@"title-extra"">(.*?)<", html);
Year = match(@"<title>.*?\(.*?(\d{4}).*?\).*?</title>", html);
Rating = match(@"<b>(\d.\d)/10</b>", html);
Genres = matchAll(@"<a.*?>(.*?)</a>", match(@"Genre.?:(.*?)(</div>|See more)", html));
Directors = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Directed by</a></h5>(.*?)</table>", html));
Writers = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Writing credits</a></h5>(.*?)</table>", html));
Producers = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Produced by</a></h5>(.*?)</table>", html));
Musicians = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Original Music by</a></h5>(.*?)</table>", html));
Cinematographers = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Cinematography by</a></h5>(.*?)</table>", html));
Editors = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Film Editing by</a></h5>(.*?)</table>", html));
Cast = matchAll(@"<td class=""nm""><a.*?href=""/name/.*?/"".*?>(.*?)</a>", match(@"<h3>Cast</h3>(.*?)</table>", html));
Plot = match(@"Plot:</h5>.*?<div class=""info-content"">(.*?)(<a|</div)", html);
PlotKeywords = matchAll(@"<a.*?>(.*?)</a>", match(@"Plot Keywords:</h5>.*?<div class=""info-content"">(.*?)</div", html));
ReleaseDate = match(@"Release Date:</h5>.*?<div class=""info-content"">.*?(\d{1,2} (January|February|March|April|May|June|July|August|September|October|November|December) (19|20)\d{2})", html);
Runtime = match(@"Runtime:</h5><div class=""info-content"">(\d{1,4}) min[\s]*.*?</div>", html);
Top250 = match(@"Top 250: #(\d{1,3})<", html);
Oscars = match(@"Won (\d+) Oscars?\.", html);
if (string.IsNullOrEmpty(Oscars) && "Won Oscar.".Equals(match(@"(Won Oscar\.)", html))) Oscars = "1";
Awards = match(@"(\d{1,4}) wins", html);
Nominations = match(@"(\d{1,4}) nominations", html);
Tagline = match(@"Tagline:</h5>.*?<div class=""info-content"">(.*?)(<a|</div)", html);
MpaaRating = match(@"MPAA</a>:</h5><div class=""info-content"">Rated (G|PG|PG-13|PG-14|R|NC-17|X) ", html);
Votes = match(@">(\d+,?\d*) votes<", html);
Languages = matchAll(@"<a.*?>(.*?)</a>", match(@"Language.?:(.*?)(</div>|>.?and )", html));
Countries = matchAll(@"<a.*?>(.*?)</a>", match(@"Country:(.*?)(</div>|>.?and )", html));
Poster = match(@"<div class=""photo"">.*?<a name=""poster"".*?><img.*?src=""(.*?)"".*?</div>", html);
if (!string.IsNullOrEmpty(Poster) && Poster.IndexOf("media-imdb.com") > 0)
{
Poster = Regex.Replace(Poster, @"_V1.*?.jpg", "_V1._SY200.jpg");
PosterLarge = Regex.Replace(Poster, @"_V1.*?.jpg", "_V1._SY500.jpg");
PosterFull = Regex.Replace(Poster, @"_V1.*?.jpg", "_V1._SY0.jpg");
}
else
{
Poster = string.Empty;
PosterLarge = string.Empty;
PosterFull = string.Empty;
}
ImdbURL = "http://www.imdb.com/title/" + Id + "/";
if (GetExtraInfo)
{
string plotHtml = getUrlData(imdbUrl + "plotsummary");
Storyline = match(@"<p class=""plotpar"">(.*?)(<i>|</p>)", plotHtml);
ReleaseDates = getReleaseDates();
MediaImages = getMediaImages();
RecommendedTitles = getRecommendedTitles();
}
}
}
//Get all release dates
private ArrayList getReleaseDates()
{
ArrayList list = new ArrayList();
string releasehtml = getUrlData("http://www.imdb.com/title/" + Id + "/releaseinfo");
foreach (string r in matchAll(@"<tr>(.*?)</tr>", match(@"Date</th></tr>\n*?(.*?)</table>", releasehtml)))
{
Match rd = new Regex(@"<td>(.*?)</td>\n*?.*?<td align=""right"">(.*?)</td>", RegexOptions.Multiline).Match(r);
list.Add(StripHTML(rd.Groups[1].Value.Trim()) + " = " + StripHTML(rd.Groups[2].Value.Trim()));
}
return list;
}
//Get all media images
private ArrayList getMediaImages()
{
ArrayList list = new ArrayList();
string mediaurl = "http://www.imdb.com/title/" + Id + "/mediaindex";
string mediahtml = getUrlData(mediaurl);
int pagecount = matchAll(@"<a href=""\?page=(.*?)"">", match(@"<span style=""padding: 0 1em;"">(.*?)</span>", mediahtml)).Count;
for (int p = 1; p <= pagecount + 1; p++)
{
mediahtml = getUrlData(mediaurl + "?page=" + p);
foreach (Match m in new Regex(@"src=""(.*?)""", RegexOptions.Multiline).Matches(match(@"<div class=""thumb_list"" style=""font-size: 0px;"">(.*?)</div>", mediahtml)))
{
String image = m.Groups[1].Value;
list.Add(Regex.Replace(image, @"_V1\..*?.jpg", "_V1._SY0.jpg"));
}
}
return list;
}
//Get Recommended Titles
private ArrayList getRecommendedTitles()
{
ArrayList list = new ArrayList();
string recUrl = "http://www.imdb.com/widget/recommendations/_ajax/get_more_recs?specs=p13nsims%3A" + Id;
string json = getUrlData(recUrl);
list = matchAll(@"title=\\""(.*?)\\""", json);
HashSet<String> set = new HashSet<string>();
foreach(String rec in list) set.Add(rec);
return new ArrayList(set.ToList());
}
/*******************************[ Helper Methods ]********************************/
//Match single instance
private string match(string regex, string html, int i = 1)
{
return new Regex(regex, RegexOptions.Multiline).Match(html).Groups[i].Value.Trim();
}
//Match all instances and return as ArrayList
private ArrayList matchAll(string regex, string html, int i = 1)
{
ArrayList list = new ArrayList();
foreach (Match m in new Regex(regex, RegexOptions.Multiline).Matches(html))
list.Add(m.Groups[i].Value.Trim());
return list;
}
//Strip HTML Tags
static string StripHTML(string inputString)
{
return Regex.Replace(inputString, @"<.*?>", string.Empty);
}
//Get URL Data
private string getUrlData(string url)
{
WebClient client = new WebClient();
Random r = new Random();
//Random IP Address
client.Headers["X-Forwarded-For"] = r.Next(0, 255) + "." + r.Next(0, 255) + "." + r.Next(0, 255) + "." + r.Next(0, 255);
//Random User-Agent
client.Headers["User-Agent"] = "Mozilla/" + r.Next(3, 5) + ".0 (Windows NT " + r.Next(3, 5) + "." + r.Next(0, 2) + "; rv:2.0.1) Gecko/20100101 Firefox/" + r.Next(3, 5) + "." + r.Next(0, 5) + "." + r.Next(0, 5);
Stream datastream = client.OpenRead(url);
StreamReader reader = new StreamReader(datastream);
StringBuilder sb = new StringBuilder();
while (!reader.EndOfStream)
sb.Append(reader.ReadLine());
return sb.ToString();
}
}
}
| |
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace PortAudio
{
#region Enum's
public enum PaHostApiTypeId
{
paInDevelopment = 0,
paDirectSound = 1,
paMME = 2,
paASIO = 3,
paSoundManager = 4,
paCoreAudio = 5,
paOSS = 7,
paALSA = 8,
paAL = 9,
paBeOS = 10,
paWDMKS = 11,
paJACK = 12,
paWASAPI = 13,
paAudioScienceHPI = 14
}
public enum PaSampleFormat
{
paFloat32 = 0x00000001,
paInt32 = 0x00000002,
paInt24 = 0x00000004,
paInt16 = 0x00000008,
paInt8 = 0x00000010,
paUInt8 = 0x00000020,
paCustomFormat = 0x00010000,
paNonInterleaved = ~0x7fffffff
}
public enum PaStreamCallbackResult
{
paContinue = 0,
paComplete = 1,
paAbort = 2
}
#endregion
#region Struct's
[StructLayout(LayoutKind.Sequential)]
public struct PaStream { }
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public class PaHostApiInfo
{
public int structVersion;
public PaHostApiTypeId type;
public string name;
public int deviceCount;
public int defaultInputDevice;
public int defaultOutputDevice;
public override string ToString()
{
return name;
}
public String Dump()
{
StringBuilder sb = new StringBuilder();
sb.Append("structVersion: " + structVersion + "\r\n");
sb.Append("type: " + type + "\r\n");
sb.Append("name: " + name + "\r\n");
sb.Append("deviceCount: " + deviceCount + "\r\n");
sb.Append("defaultInputDevice: " + defaultInputDevice + "\r\n");
sb.Append("defaultOutputDevice: " + defaultOutputDevice + "\r\n");
Trace.WriteLine(sb.ToString());
return sb.ToString();
}
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class PaDeviceInfo
{
public int structVersion;
public string name;
public int hostApi;
public int maxInputChannels;
public int maxOutputChannels;
public double defaultLowInputLatency;
public double defaultLowOutputLatency;
public double defaultHighInputLatency;
public double defaultHighOutputLatency;
public double defaultSampleRate;
public override string ToString()
{
return name;
}
public String Dump()
{
StringBuilder sb = new StringBuilder();
sb.Append("structVersion: " + structVersion + "\r\n");
sb.Append("name: " + name + "\r\n");
sb.Append("hostApi: " + hostApi + "\r\n");
sb.Append("maxInputChannels: " + maxInputChannels + "\r\n");
sb.Append("maxOutputChannels: " + maxOutputChannels + "\r\n");
sb.Append("defaultLowInputLatency: " + defaultLowInputLatency + "\r\n");
sb.Append("defaultLowOutputLatency: " + defaultLowOutputLatency + "\r\n");
sb.Append("defaultHighInputLatency: " + defaultHighInputLatency + "\r\n");
sb.Append("defaultHighOutputLatency: " + defaultHighOutputLatency + "\r\n");
sb.Append("defaultSampleRate: " + defaultSampleRate + "\r\n");
Trace.WriteLine(sb.ToString());
return sb.ToString();
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class PaHostErrorInfo
{
PaHostApiTypeId hostApiType;
int errorCode;
string errorText;
public override string ToString()
{
return errorText;
}
}
[StructLayout(LayoutKind.Sequential)]
public class PaStreamParameters
{
public int device;
public int channelCount;
public PaSampleFormat sampleFormat;
public double suggestedLatency;
public IntPtr hostApiSpecificStreamInfo;
}
[StructLayout(LayoutKind.Sequential)]
public class PaStreamCallbackTimeInfo
{
public double inputBufferAdcTime;
public double currentTime;
public double outputBufferDacTime;
}
[StructLayout(LayoutKind.Sequential)]
public class PaStreamInfo
{
public int structVersion;
public double inputLatency;
public double outputLatency;
public double sampleRate;
}
#endregion
#region Delegates
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate PaStreamCallbackResult PaStreamCallback([In] IntPtr input, [Out] IntPtr output, UInt32 frameCount,
IntPtr timeInfo, UInt32 statusFlags, IntPtr userData);
#endregion
#region Managed Methods
unsafe public static class ManagedWrappers
{
// A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)
public static PaHostApiInfo Pa_GetHostApiInfo(int hostApi)
{
IntPtr ptr = NativeMethods.Pa_GetHostApiInfo(hostApi);
PaHostApiInfo info = (PaHostApiInfo) Marshal.PtrToStructure(ptr, typeof(PaHostApiInfo));
return info;
}
// A valid device index in the range 0 to (Pa_GetDeviceCount()-1)
public static PaDeviceInfo Pa_GetDeviceInfo(int device)
{
IntPtr ptr = NativeMethods.Pa_GetDeviceInfo(device);
PaDeviceInfo info = (PaDeviceInfo) Marshal.PtrToStructure(ptr, typeof(PaDeviceInfo));
return info;
}
public static PaDeviceInfo Pa_GetDeviceInfo(int hostApi, int hostApiDeviceIndex)
{
int deviceIndex = NativeMethods.Pa_HostApiDeviceIndexToDeviceIndex(hostApi, hostApiDeviceIndex);
PaDeviceInfo info = Pa_GetDeviceInfo(deviceIndex);
return info;
}
public static PaHostErrorInfo Pa_GetLastHostErrorInfo()
{
IntPtr ptr = NativeMethods.Pa_GetLastHostErrorInfo();
PaHostErrorInfo info = (PaHostErrorInfo) Marshal.PtrToStructure(ptr, typeof(PaHostErrorInfo));
return info;
}
public static PaStreamInfo Pa_GetStreamInfo(PaStream* stream)
{
IntPtr ptr = NativeMethods.Pa_GetStreamInfo(stream);
PaStreamInfo info = (PaStreamInfo) Marshal.PtrToStructure(ptr, typeof(PaStreamInfo));
return info;
}
}
#endregion
#region Imported Methods
unsafe public static class NativeMethods
{
#if X86
const string dllName = "portaudio_x86.dll";
#else
const string dllName = "portaudio_x64.dll";
#endif
[DllImport(dllName)]
public static extern int Pa_GetVersion();
[DllImport(dllName)]
public static extern string Pa_GetVersionText();
[DllImport(dllName)]
public static extern string Pa_GetErrorText(int errorCode);
[DllImport(dllName)]
public static extern int Pa_Initialize();
[DllImport(dllName)]
public static extern int Pa_Terminate();
[DllImport(dllName)]
public static extern int Pa_GetHostApiCount();
[DllImport(dllName)]
public static extern int Pa_GetDefaultHostApi();
/// <summary>
///
/// </summary>
/// <param name="hostApi">A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)</param>
/// <returns></returns>
[DllImport(dllName)]
public static extern IntPtr Pa_GetHostApiInfo(int hostApi);
/// <summary>
///
/// </summary>
/// <param name="type">A unique host API identifier belonging to the PaHostApiTypeId enumeration.</param>
/// <returns></returns>
[DllImport(dllName)]
public static extern int Pa_HostApiTypeIdToHostApiIndex(PaHostApiTypeId type);
/// <summary>
///
/// </summary>
/// <param name="hostApi">A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)</param>
/// <param name="hostApiDeviceIndex">A valid per-host device index in the range 0 to (Pa_GetHostApiInfo(hostApi)->deviceCount-1)</param>
/// <returns></returns>
[DllImport(dllName)]
public static extern int Pa_HostApiDeviceIndexToDeviceIndex(int hostApi, int hostApiDeviceIndex);
[DllImport(dllName)]
public static extern IntPtr Pa_GetLastHostErrorInfo();
[DllImport(dllName)]
public static extern int Pa_GetDeviceCount();
[DllImport(dllName)]
public static extern int Pa_GetDefaultInputDevice();
[DllImport(dllName)]
public static extern int Pa_GetDefaultOutputDevice();
[DllImport(dllName)]
public static extern IntPtr Pa_GetDeviceInfo(int device);
[DllImport(dllName)]
public static extern int Pa_IsFormatSupported(PaStreamParameters inputParameters, PaStreamParameters outputParameters, Double sampleRate);
[DllImport(dllName)]
public static extern int Pa_OpenStream(out IntPtr stream, PaStreamParameters inputParameters, PaStreamParameters outputParameters,
Double sampleRate, UInt32 framesPerBuffer, UInt32 streamFlags,
PaStreamCallback streamCallback, IntPtr userData);
[DllImport(dllName)]
public static extern int Pa_OpenDefaultStream([Out] IntPtr stream, int numInputChannels, int numOutputChannels,
UInt32 sampleFormat, double sampleRate, UInt32 framesPerBuffer,
PaStreamCallback streamCallback, IntPtr userData);
[DllImport(dllName)]
public static extern int Pa_CloseStream(IntPtr stream);
[DllImport(dllName)]
public static extern void PaStreamFinishedCallback(IntPtr userData);
[DllImport(dllName)]
public static extern int Pa_StartStream(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_StopStream(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_AbortStream(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_IsStreamStopped(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_IsStreamActive(IntPtr stream);
[DllImport(dllName)]
public static extern IntPtr Pa_GetStreamInfo(PaStream* stream);
[DllImport(dllName)]
public static extern double Pa_GetStreamTime(IntPtr stream);
[DllImport(dllName)]
public static extern double Pa_GetStreamCouLoad(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_ReadStream(IntPtr stream, [Out] Byte[] buffer, UInt32 frames);
[DllImport(dllName)]
public static extern int Pa_WriteStream(IntPtr stream, Byte[] buffer, UInt32 frames);
[DllImport(dllName)]
public static extern int Pa_GetStreamReadAvailable(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_GetStreamWriteAvailable(IntPtr stream);
[DllImport(dllName)]
public static extern int Pa_GetSampleSize(UInt32 format);
[DllImport(dllName)]
public static extern void Pa_Sleep(UInt32 msec);
[DllImport(dllName)]
public static extern int PaAsio_GetAvailableLatencyValues(int device, [Out] UInt32 minLatency, [Out] UInt32 maxLatency,
[Out] UInt32 preferredLatency, [Out] UInt32 granularity);
[DllImport(dllName)]
public static extern int PaAsio_ShowControlPanel(int device, IntPtr systemSpecific);
[DllImport(dllName)]
public static extern void PaUtil_InitializeX86PlainConverters();
[DllImport(dllName)]
public static extern int PaAsio_GetInputChannelName(int device, int channelIndex, [Out] string channelName);
[DllImport(dllName)]
public static extern int PaAsio_GetOutputChannelName(int device, int channelIndex, [Out] string channelName);
}
#endregion
public class PortAudioException : Exception
{
private Int32 portAudioError;
public Int32 PaErrorCode
{
get { return this.PaErrorCode; }
}
public PortAudioException(int portAudioError) : base(PortAudio.NativeMethods.Pa_GetErrorText(portAudioError))
{
this.portAudioError = portAudioError;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
public class PropertyPathSelector
{
private readonly DropDownControl<string> thisDropDown = new DropDownControl<string>();
private readonly Func<string, string> replaceDotWithSlashAndAddGOGroup = s => s.Replace('.', '/');
private readonly string name;
private bool focusBackToEdit;
private SelectedPathError error;
public PropertyPathSelector (string name)
{
this.name = name;
thisDropDown.convertForGUIContent = replaceDotWithSlashAndAddGOGroup;
thisDropDown.tooltip = "Select path the value you want to be used for comparisment.";
}
public void Draw(GameObject go, ActionBase comparer, string propertPath, Type[] accepatbleTypes, Action<GameObject> onSelectedGO, Action<string> onSelectedPath)
{
var newGO = (GameObject)EditorGUILayout.ObjectField(name, go, typeof (GameObject), true);
if (newGO != go)
onSelectedGO(newGO);
if (go != null)
{
var newPath = DrawListOfMethods (go, comparer, propertPath, accepatbleTypes, thisDropDown);
if (newPath != propertPath)
onSelectedPath (newPath);
}
}
private string DrawListOfMethods(GameObject go, ActionBase comparer, string propertPath, Type[] accepatbleTypes, DropDownControl<string> dropDown)
{
string result = propertPath;
if (accepatbleTypes == null)
{
result = DrawManualPropertyEditField(go, propertPath, accepatbleTypes, dropDown);
}
else
{
bool isPropertyOrFieldFound = true;
if (string.IsNullOrEmpty(result))
{
var options = GetFieldsAndProperties (go, comparer, result, accepatbleTypes);
isPropertyOrFieldFound = options.Any ();
if (isPropertyOrFieldFound)
{
result = options.First();
}
}
if (isPropertyOrFieldFound)
{
dropDown.Draw (go.name + '.', result,
() =>
{
try
{
var options = GetFieldsAndProperties (go, comparer, result, accepatbleTypes);
return options.ToArray ();
}
catch (Exception)
{
Debug.LogWarning ("An exception was thrown while resolving property list. Reseting property path.");
result = "";
return new string[0];
}
}, s => result = s);
}
else
{
result = DrawManualPropertyEditField(go, propertPath, accepatbleTypes, dropDown);
}
}
return result;
}
private static List<string> GetFieldsAndProperties ( GameObject go, ActionBase comparer, string extendPath, Type[] accepatbleTypes )
{
var propertyResolver = new PropertyResolver {AllowedTypes = accepatbleTypes, ExcludedFieldNames = comparer.GetExcludedFieldNames ()};
var options = propertyResolver.GetFieldsAndPropertiesFromGameObject (go, comparer.GetDepthOfSearch (), extendPath).ToList ();
options.Sort ((x, y) =>
{
if (char.IsLower (x[0]))
return -1;
if (char.IsLower (y[0]))
return 1;
return x.CompareTo (y);
});
return options;
}
private string DrawManualPropertyEditField(GameObject go, string propertPath, Type[] acceptableTypes, DropDownControl<string> dropDown)
{
var propertyResolver = new PropertyResolver { AllowedTypes = acceptableTypes };
IList<string> list;
var loadProps = new Func<string[]> (() =>
{
try
{
list = propertyResolver.GetFieldsAndPropertiesUnderPath (go, propertPath);
}
catch (ArgumentException)
{
list = propertyResolver.GetFieldsAndPropertiesUnderPath (go, "");
}
return list.ToArray ();
});
EditorGUILayout.BeginHorizontal();
var labelSize = EditorStyles.label.CalcSize(new GUIContent(go.name + '.'));
GUILayout.Label (go.name + (propertPath.Length > 0 ? "." : ""), EditorStyles.label, GUILayout.Width (labelSize.x));
string btnName = "hintBtn";
if ( GUI.GetNameOfFocusedControl () == btnName
&& Event.current.type == EventType.KeyDown
&& Event.current.keyCode == KeyCode.DownArrow)
{
Event.current.Use ();
dropDown.PrintMenu (loadProps ());
GUI.FocusControl ("");
focusBackToEdit = true;
}
EditorGUI.BeginChangeCheck ();
GUI.SetNextControlName (btnName);
var result = GUILayout.TextField(propertPath, EditorStyles.textField);
if (EditorGUI.EndChangeCheck ())
{
error = DoesPropertyExist (go, result);
}
if (focusBackToEdit)
{
focusBackToEdit = false;
GUI.FocusControl (btnName);
}
if (GUILayout.Button ("clear", EditorStyles.miniButton, GUILayout.Width (38)))
{
result = "";
GUI.FocusControl (null);
focusBackToEdit = true;
error = DoesPropertyExist (go, result);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal ();
GUILayout.Label ("", GUILayout.Width (labelSize.x));
dropDown.Draw("", result ?? "", loadProps, s =>
{
result = s;
GUI.FocusControl (null);
focusBackToEdit = true;
error = DoesPropertyExist (go, result);
});
EditorGUILayout.EndHorizontal();
switch (error)
{
case SelectedPathError.InvalidPath:
EditorGUILayout.HelpBox ("This property does not exist", MessageType.Error);
break;
case SelectedPathError.MissingComponent:
EditorGUILayout.HelpBox ("This property or field is not attached or set. It will fail unless it will be attached before the check is perfomed.", MessageType.Warning);
break;
}
return result;
}
private SelectedPathError DoesPropertyExist ( GameObject go, string propertPath )
{
try
{
object obj;
if(MemberResolver.TryGetValue (go, propertPath, out obj))
return SelectedPathError.None;
else
return SelectedPathError.InvalidPath;
}
catch (TargetInvocationException e)
{
if(e.InnerException is MissingComponentException)
return SelectedPathError.MissingComponent;
else
throw;
}
}
private enum SelectedPathError
{
None,
MissingComponent,
InvalidPath
}
}
}
| |
// 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.Collections.Specialized;
using System.ComponentModel;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
/// <summary>
/// Tests the public methods in ObservableCollection<T> as well as verifies
/// that the CollectionChanged events and eventargs are fired and populated
/// properly.
/// </summary>
public static class PublicMethodsTest
{
/// <summary>
/// Tests that is is possible to Add an item to the collection.
/// </summary>
[Fact]
public static void AddTest()
{
string[] anArray = { "one", "two", "three" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.AddOrInsertItemTest(col, "four");
}
/// <summary>
/// Tests that it is possible to remove an item from the collection.
/// - Removing an item from the collection results in a false.
/// - Removing null from collection returns a false.
/// - Removing an item that has duplicates only takes out the first instance.
/// </summary>
[Fact]
public static void RemoveTest()
{
// trying to remove item in collection.
string[] anArray = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, 2, "three", true, hasDuplicates: false);
// trying to remove item not in collection.
anArray = new string[] { "one", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, -1, "three2", false, hasDuplicates: false);
// removing null
anArray = new string[] { "one", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, -1, null, false, hasDuplicates: false);
// trying to remove item in collection that has duplicates.
anArray = new string[] { "one", "three", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemTest(col, 1, "three", true, hasDuplicates: true);
// want to ensure that there is one "three" left in collection and not both were removed.
int occurancesThree = 0;
foreach (var item in col)
{
if (item.Equals("three"))
occurancesThree++;
}
Assert.Equal(1, occurancesThree);
}
/// <summary>
/// Tests that a collection can be cleared.
/// </summary>
[Fact]
public static void ClearTest()
{
string[] anArray = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
col.Clear();
Assert.Equal(0, col.Count);
Assert.Empty(col);
Assert.Throws<ArgumentOutOfRangeException>(() => col[1]);
//tests that the collectionChanged events are fired.
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
col = new ObservableCollection<string>(anArray);
helper.ClearTest(col);
}
/// <summary>
/// Tests that we can remove items at a specific index, at the middle beginning and end.
/// </summary>
[Fact]
public static void RemoveAtTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col2 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
col0.RemoveAt(0);
string collectionString = "";
foreach (var item in col1)
collectionString += item + ", ";
Assert.False(col0.Contains(anArray[0]), "Collection0 should no longer contain the item: " + anArray[0] + " Collection: " + collectionString);
col1.RemoveAt(1);
collectionString = "";
foreach (var item in col1)
collectionString += item + ", ";
Assert.False(col1.Contains(anArray[1]), "Collection1 should no longer contain the item: " + anArray[1] + " Collection: " + collectionString);
col2.RemoveAt(2);
collectionString = "";
foreach (var item in col2)
collectionString += item + ", ";
Assert.False(col2.Contains(anArray[2]), "Collection2 should no longer contain the item: " + anArray[2] + " Collection: " + collectionString);
string[] anArrayString = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArrayString);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.RemoveItemAtTest(col, 1);
}
/// <summary>
/// Tests that exceptions are thrown:
/// ArgumentOutOfRangeException when index < 0 or index >= collection.Count.
/// And that the collection does not change.
/// </summary>
[Fact]
public static void RemoveAtTest_Negative()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
Assert.Equal(anArray.Length, collection.Count);
}
int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
Assert.Equal(anArray.Length, collection.Count);
}
}
/// <summary>
/// Tests that items can be moved throughout a collection whether from
/// beginning to end, etc.
/// </summary>
[Fact]
public static void MoveTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col01 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col10 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col12 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col21 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col20 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
col01.Move(0, 1);
Assert.Equal(anArray[0], col01[1]);
col10.Move(1, 0);
Assert.Equal(anArray[1], col10[0]);
col12.Move(1, 2);
Assert.Equal(anArray[1], col12[2]);
col21.Move(2, 1);
Assert.Equal(anArray[2], col21[1]);
col20.Move(2, 0);
Assert.Equal(anArray[2], col20[0]);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
string[] anArrayString = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArrayString);
helper.MoveItemTest(collection, 0, 2);
helper.MoveItemTest(collection, 3, 0);
helper.MoveItemTest(collection, 1, 2);
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the source or destination
/// Index is >= collection.Count or Index < 0.
/// </summary>
/// <remarks>
/// When the sourceIndex is valid, the item actually is removed from the list.
/// </remarks>
[Fact]
public static void MoveTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = null;
int validIndex = 2;
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
int[] iArrLargeValues = new Int32[] { anArray.Length, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrInvalidValues)
{
collection = new ObservableCollection<string>(anArray);
collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
// invalid startIndex, valid destination index.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(index, validIndex));
Assert.Equal(anArray.Length, collection.Count);
// valid startIndex, invalid destIndex.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(validIndex, index));
//NOTE: It actually moves the item right out of the collection.So the count is one less.
//Assert.Equal(anArray.Length, collection.Count, "Collection should not have changed. index: " + index);
}
foreach (var index in iArrLargeValues)
{
collection = new ObservableCollection<string>(anArray);
collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
// invalid startIndex, valid destination index.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(index, validIndex));
Assert.Equal(anArray.Length, collection.Count);
// valid startIndex, invalid destIndex.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(validIndex, index));
//NOTE: It actually moves the item right out of the collection. So the count is one less.
//Assert.Equal(anArray.Length, collection.Count, "Collection should not have changed.");
}
}
/// <summary>
/// Tests that an item can be inserted throughout the collection.
/// </summary>
[Fact]
public static void InsertTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
ObservableCollection<Guid> col3 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
//inserting item at the beginning.
Guid g0 = Guid.NewGuid();
col0.Insert(0, g0);
Assert.Equal(g0, col0[0]);
// inserting item in the middle
Guid g1 = Guid.NewGuid();
col1.Insert(1, g1);
Assert.Equal(g1, col1[1]);
// inserting item at the end.
Guid g3 = Guid.NewGuid();
col3.Insert(col3.Count, g3);
Assert.Equal(g3, col3[col3.Count - 1]);
string[] anArrayString = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArrayString);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.AddOrInsertItemTest(collection, "seven", 2);
helper.AddOrInsertItemTest(collection, "zero", 0);
helper.AddOrInsertItemTest(collection, "eight", collection.Count);
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0. And ensures that the collection does not change.
/// </summary>
[Fact]
public static void InsertTest_Negative()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
Guid itemToInsert = Guid.NewGuid();
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(index, itemToInsert));
Assert.Equal(anArray.Length, collection.Count);
}
int[] iArrLargeValues = new Int32[] { collection.Count + 1, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(index, itemToInsert));
Assert.Equal(anArray.Length, collection.Count);
}
}
/// <summary>
/// Tests that the appropriate collectionchanged event is fired when
/// an item is replaced in the collection.
/// </summary>
[Fact]
public static void ReplaceItemTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
helper.ReplaceItemTest(collection, 1, "seven");
helper.ReplaceItemTest(collection, 3, "zero");
}
/// <summary>
/// Tests that contains returns true when the item is in the collection
/// and false otherwise.
/// </summary>
[Fact]
public static void ContainsTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
string collectionString = "";
foreach (var item in collection)
collectionString += item + ", ";
for (int i = 0; i < collection.Count; ++i)
Assert.True(collection.Contains(anArray[i]), "ObservableCollection did not contain the item: " + anArray[i] + " Collection: " + collectionString);
string g = "six";
Assert.False(collection.Contains(g), "Collection contained an item that should not have been there. guid: " + g + " Collection: " + collectionString);
Assert.False(collection.Contains(null), "Collection should not have contained null. Collection: " + collectionString);
}
/// <summary>
/// Tests that the index of an item can be retrieved when the item is
/// in the collection and -1 otherwise.
/// </summary>
[Fact]
public static void IndexOfTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(i, collection.IndexOf(anArray[i]));
Assert.Equal(-1, collection.IndexOf("seven"));
Assert.Equal(-1, collection.IndexOf(null));
// testing that the first occurance is the index returned.
ObservableCollection<int> intCol = new ObservableCollection<int>();
for (int i = 0; i < 4; ++i)
intCol.Add(i % 2);
Assert.Equal(0, intCol.IndexOf(0));
Assert.Equal(1, intCol.IndexOf(1));
IList colAsIList = (IList)intCol;
var index = colAsIList.IndexOf("stringObj");
Assert.Equal(-1, index);
}
/// <summary>
/// Tests that the collection can be copied into a destination array.
/// </summary>
[Fact]
public static void CopyToTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray);
string[] aCopy = new string[collection.Count];
collection.CopyTo(aCopy, 0);
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(anArray[i], aCopy[i]);
// copy observable collection starting in middle, where array is larger than source.
aCopy = new string[collection.Count + 2];
int offsetIndex = 1;
collection.CopyTo(aCopy, offsetIndex);
for (int i = 0; i < aCopy.Length; i++)
{
string value = aCopy[i];
if (i == 0)
Assert.True(null == value, "Should not have a value since we did not start copying there.");
else if (i == (aCopy.Length - 1))
Assert.True(null == value, "Should not have a value since the collection is shorter than the copy array..");
else
{
int indexInCollection = i - offsetIndex;
Assert.Equal(collection[indexInCollection], aCopy[i]);
}
}
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0.
/// ArgumentException when the destination array does not have enough space to
/// contain the source Collection.
/// ArgumentNullException when the destination array is null.
/// </summary>
[Fact]
public static void CopyToTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArray);
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
string[] aCopy = new string[collection.Count];
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(aCopy, index));
}
int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
string[] aCopy = new string[collection.Count];
Assert.Throws<ArgumentException>(() => collection.CopyTo(aCopy, index));
}
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 1));
string[] copy = new string[collection.Count - 1];
Assert.Throws<ArgumentException>(() => collection.CopyTo(copy, 0));
copy = new string[0];
Assert.Throws<ArgumentException>(() => collection.CopyTo(copy, 0));
}
/// <summary>
/// Tests that it is possible to iterate through the collection with an
/// Enumerator.
/// </summary>
[Fact]
public static void GetEnumeratorTest()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> col = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
int i = 0;
IEnumerator<Guid> e;
for (e = col.GetEnumerator(); e.MoveNext(); ++i)
{
Assert.Equal(anArray[i], e.Current);
}
Assert.Equal(col.Count, i);
e.Dispose();
}
}
/// <summary>
/// Helper class to test the CollectionChanged and PropertyChanged Events.
/// </summary>
public class CollectionAndPropertyChangedTester
{
#region Properties
private const string COUNT = "Count";
private const string ITEMARRAY = "Item[]";
// Number of collection changed events that were ACTUALLY fired.
public int NumCollectionChangedFired { get; private set; }
// Number of collection changed events that are EXPECTED to be fired.
public int ExpectedCollectionChangedFired { get; private set; }
public int ExpectedNewStartingIndex { get; private set; }
public NotifyCollectionChangedAction ExpectedAction { get; private set; }
public IList ExpectedNewItems { get; private set; }
public IList ExpectedOldItems { get; private set; }
public int ExpectedOldStartingIndex { get; private set; }
private PropertyNameExpected[] _expectedPropertyChanged;
#endregion
#region Helper Methods
/// <summary>
/// Will perform an Add or Insert on the given Collection depending on whether the
/// insertIndex is null or not. If it is null, will Add, otherwise, will Insert.
/// </summary>
public void AddOrInsertItemTest(ObservableCollection<string> collection, string itemToAdd, int? insertIndex = null)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Add;
ExpectedNewItems = new string[] { itemToAdd };
if (insertIndex.HasValue)
ExpectedNewStartingIndex = insertIndex.Value;
else
ExpectedNewStartingIndex = collection.Count;
ExpectedOldItems = null;
ExpectedOldStartingIndex = -1;
int expectedCount = collection.Count + 1;
if (insertIndex.HasValue)
{
collection.Insert(insertIndex.Value, itemToAdd);
Assert.Equal(itemToAdd, collection[insertIndex.Value]);
}
else
{
collection.Add(itemToAdd);
Assert.Equal(itemToAdd, collection[collection.Count - 1]);
}
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just added an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Clears the given Collection.
/// </summary>
public void ClearTest(ObservableCollection<string> collection)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Reset;
ExpectedNewItems = null;
ExpectedNewStartingIndex = -1;
ExpectedOldItems = null;
ExpectedOldStartingIndex = -1;
collection.Clear();
Assert.Equal(0, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just cleared the collection");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Given a collection, will move an item from the oldIndex to the newIndex.
/// </summary>
public void MoveItemTest(ObservableCollection<string> collection, int oldIndex, int newIndex)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) };
collection.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[oldIndex];
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Move;
ExpectedNewItems = new string[] { itemAtOldIndex };
ExpectedNewStartingIndex = newIndex;
ExpectedOldItems = new string[] { itemAtOldIndex };
ExpectedOldStartingIndex = oldIndex;
int expectedCount = collection.Count;
collection.Move(oldIndex, newIndex);
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(itemAtOldIndex, collection[newIndex]);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just moved an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Will set that new item at the specified index in the given collection.
/// </summary>
public void ReplaceItemTest(ObservableCollection<string> collection, int index, string newItem)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) };
collection.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[index];
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Replace;
ExpectedNewItems = new string[] { newItem };
ExpectedNewStartingIndex = index;
ExpectedOldItems = new string[] { itemAtOldIndex };
ExpectedOldStartingIndex = index;
int expectedCount = collection.Count;
collection[index] = newItem;
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(newItem, collection[index]);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just replaced an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Given a collection, index and item to remove, will try to remove that item
/// from the index. If the item has duplicates, will verify that only the first
/// instance was removed.
/// </summary>
public void RemoveItemTest(ObservableCollection<string> collection, int itemIndex, string itemToRemove, bool isSuccessfulRemove, bool hasDuplicates)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
if (isSuccessfulRemove)
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Remove;
ExpectedNewItems = null;
ExpectedNewStartingIndex = -1;
ExpectedOldItems = new string[] { itemToRemove };
ExpectedOldStartingIndex = itemIndex;
int expectedCount = isSuccessfulRemove ? collection.Count - 1 : collection.Count;
bool removedItem = collection.Remove(itemToRemove);
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
if (isSuccessfulRemove)
{
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since there were items removed.");
Assert.True(removedItem, "Should have been successful in removing the item.");
}
else
{
foreach (var item in _expectedPropertyChanged)
Assert.False(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since there were no items removed.");
Assert.False(removedItem, "Should not have been successful in removing the item.");
}
if (hasDuplicates)
return;
Assert.DoesNotContain(itemToRemove, collection);
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Verifies that the item is removed from a given index in the collection.
/// </summary>
public void RemoveItemAtTest(ObservableCollection<string> collection, int itemIndex)
{
INotifyPropertyChanged collectionPropertyChanged = collection;
collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
collection.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[itemIndex];
ExpectedCollectionChangedFired++;
ExpectedAction = NotifyCollectionChangedAction.Remove;
ExpectedNewItems = null;
ExpectedNewStartingIndex = -1;
ExpectedOldItems = new string[] { itemAtOldIndex };
ExpectedOldStartingIndex = itemIndex;
int expectedCount = collection.Count - 1;
collection.RemoveAt(itemIndex);
Assert.Equal(expectedCount, collection.Count);
Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just removed an item");
collection.CollectionChanged -= Collection_CollectionChanged;
collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Verifies that the eventargs fired matches the expected results.
/// </summary>
private void VerifyEventArgs(NotifyCollectionChangedEventArgs e)
{
Assert.Equal(ExpectedNewStartingIndex, e.NewStartingIndex);
Assert.Equal(ExpectedOldStartingIndex, e.OldStartingIndex);
if (ExpectedNewItems != null)
{
foreach (var newItem in e.NewItems)
Assert.True(ExpectedNewItems.Contains(newItem), "newItem was not in the ExpectedNewItems. newItem: " + newItem);
foreach (var expectedItem in ExpectedNewItems)
Assert.True(e.NewItems.Contains(expectedItem), "expectedItem was not in e.NewItems. expectedItem: " + expectedItem);
}
else
{
Assert.Null(e.NewItems);
}
if (ExpectedOldItems != null)
{
foreach (var oldItem in e.OldItems)
Assert.True(ExpectedOldItems.Contains(oldItem), "oldItem was not in the ExpectedOldItems. oldItem: " + oldItem);
foreach (var expectedItem in ExpectedOldItems)
Assert.True(e.OldItems.Contains(expectedItem), "expectedItem was not in e.OldItems. expectedItem: " + expectedItem);
}
else
{
Assert.Null(e.OldItems);
}
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
NumCollectionChangedFired++;
Assert.Equal(ExpectedAction, e.Action);
switch (ExpectedAction)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Move:
case NotifyCollectionChangedAction.Reset:
case NotifyCollectionChangedAction.Replace:
VerifyEventArgs(e);
break;
default:
throw new NotSupportedException("Does not support this action yet.");
}
}
private void Collection_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
foreach (var item in _expectedPropertyChanged)
{
if (item.Name == e.PropertyName)
item.IsFound = true;
}
}
/// <summary>
/// Helper class to keep track of what propertychanges we expect and whether they were found or not.
/// </summary>
private class PropertyNameExpected
{
internal PropertyNameExpected(string name)
{
Name = name;
}
internal string Name { get; private set; }
internal bool IsFound { get; set; }
}
#endregion
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaClass()]
public partial class ViewConfiguration : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ViewConfiguration(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::android.view.ViewConfiguration get(android.content.Context arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m0.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m0 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "get", "(Landroid/content/Context;)Landroid/view/ViewConfiguration;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewConfiguration;
}
public static int ScrollBarSize
{
get
{
return getScrollBarSize();
}
}
private static global::MonoJavaBridge.MethodId _m1;
public static int getScrollBarSize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m1.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m1 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getScrollBarSize", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m1);
}
public new int ScaledScrollBarSize
{
get
{
return getScaledScrollBarSize();
}
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual int getScaledScrollBarSize()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledScrollBarSize", "()I", ref global::android.view.ViewConfiguration._m2);
}
public static int ScrollBarFadeDuration
{
get
{
return getScrollBarFadeDuration();
}
}
private static global::MonoJavaBridge.MethodId _m3;
public static int getScrollBarFadeDuration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m3.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m3 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getScrollBarFadeDuration", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m3);
}
public static int ScrollDefaultDelay
{
get
{
return getScrollDefaultDelay();
}
}
private static global::MonoJavaBridge.MethodId _m4;
public static int getScrollDefaultDelay()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m4.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m4 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getScrollDefaultDelay", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m4);
}
public static int FadingEdgeLength
{
get
{
return getFadingEdgeLength();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public static int getFadingEdgeLength()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m5.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m5 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getFadingEdgeLength", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m5);
}
public new int ScaledFadingEdgeLength
{
get
{
return getScaledFadingEdgeLength();
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual int getScaledFadingEdgeLength()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledFadingEdgeLength", "()I", ref global::android.view.ViewConfiguration._m6);
}
public static int PressedStateDuration
{
get
{
return getPressedStateDuration();
}
}
private static global::MonoJavaBridge.MethodId _m7;
public static int getPressedStateDuration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m7.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m7 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getPressedStateDuration", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m7);
}
public static int LongPressTimeout
{
get
{
return getLongPressTimeout();
}
}
private static global::MonoJavaBridge.MethodId _m8;
public static int getLongPressTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m8.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m8 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getLongPressTimeout", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m8);
}
public static int TapTimeout
{
get
{
return getTapTimeout();
}
}
private static global::MonoJavaBridge.MethodId _m9;
public static int getTapTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m9.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m9 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getTapTimeout", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m9);
}
public static int JumpTapTimeout
{
get
{
return getJumpTapTimeout();
}
}
private static global::MonoJavaBridge.MethodId _m10;
public static int getJumpTapTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m10.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m10 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getJumpTapTimeout", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m10);
}
public static int DoubleTapTimeout
{
get
{
return getDoubleTapTimeout();
}
}
private static global::MonoJavaBridge.MethodId _m11;
public static int getDoubleTapTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m11.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m11 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getDoubleTapTimeout", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m11);
}
public static int EdgeSlop
{
get
{
return getEdgeSlop();
}
}
private static global::MonoJavaBridge.MethodId _m12;
public static int getEdgeSlop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m12.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m12 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getEdgeSlop", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m12);
}
public new int ScaledEdgeSlop
{
get
{
return getScaledEdgeSlop();
}
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual int getScaledEdgeSlop()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledEdgeSlop", "()I", ref global::android.view.ViewConfiguration._m13);
}
public static int TouchSlop
{
get
{
return getTouchSlop();
}
}
private static global::MonoJavaBridge.MethodId _m14;
public static int getTouchSlop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m14.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m14 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getTouchSlop", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m14);
}
public new int ScaledTouchSlop
{
get
{
return getScaledTouchSlop();
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual int getScaledTouchSlop()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledTouchSlop", "()I", ref global::android.view.ViewConfiguration._m15);
}
public new int ScaledPagingTouchSlop
{
get
{
return getScaledPagingTouchSlop();
}
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual int getScaledPagingTouchSlop()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledPagingTouchSlop", "()I", ref global::android.view.ViewConfiguration._m16);
}
public new int ScaledDoubleTapSlop
{
get
{
return getScaledDoubleTapSlop();
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual int getScaledDoubleTapSlop()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledDoubleTapSlop", "()I", ref global::android.view.ViewConfiguration._m17);
}
public static int WindowTouchSlop
{
get
{
return getWindowTouchSlop();
}
}
private static global::MonoJavaBridge.MethodId _m18;
public static int getWindowTouchSlop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m18.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m18 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getWindowTouchSlop", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m18);
}
public new int ScaledWindowTouchSlop
{
get
{
return getScaledWindowTouchSlop();
}
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual int getScaledWindowTouchSlop()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledWindowTouchSlop", "()I", ref global::android.view.ViewConfiguration._m19);
}
public static int MinimumFlingVelocity
{
get
{
return getMinimumFlingVelocity();
}
}
private static global::MonoJavaBridge.MethodId _m20;
public static int getMinimumFlingVelocity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m20.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m20 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getMinimumFlingVelocity", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m20);
}
public new int ScaledMinimumFlingVelocity
{
get
{
return getScaledMinimumFlingVelocity();
}
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual int getScaledMinimumFlingVelocity()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledMinimumFlingVelocity", "()I", ref global::android.view.ViewConfiguration._m21);
}
public static int MaximumFlingVelocity
{
get
{
return getMaximumFlingVelocity();
}
}
private static global::MonoJavaBridge.MethodId _m22;
public static int getMaximumFlingVelocity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m22.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m22 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getMaximumFlingVelocity", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m22);
}
public new int ScaledMaximumFlingVelocity
{
get
{
return getScaledMaximumFlingVelocity();
}
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual int getScaledMaximumFlingVelocity()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledMaximumFlingVelocity", "()I", ref global::android.view.ViewConfiguration._m23);
}
public static int MaximumDrawingCacheSize
{
get
{
return getMaximumDrawingCacheSize();
}
}
private static global::MonoJavaBridge.MethodId _m24;
public static int getMaximumDrawingCacheSize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m24.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m24 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getMaximumDrawingCacheSize", "()I");
return @__env.CallStaticIntMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m24);
}
public new int ScaledMaximumDrawingCacheSize
{
get
{
return getScaledMaximumDrawingCacheSize();
}
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual int getScaledMaximumDrawingCacheSize()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.ViewConfiguration.staticClass, "getScaledMaximumDrawingCacheSize", "()I", ref global::android.view.ViewConfiguration._m25);
}
public static long ZoomControlsTimeout
{
get
{
return getZoomControlsTimeout();
}
}
private static global::MonoJavaBridge.MethodId _m26;
public static long getZoomControlsTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m26.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m26 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getZoomControlsTimeout", "()J");
return @__env.CallStaticLongMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m26);
}
public static long GlobalActionKeyTimeout
{
get
{
return getGlobalActionKeyTimeout();
}
}
private static global::MonoJavaBridge.MethodId _m27;
public static long getGlobalActionKeyTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m27.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m27 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getGlobalActionKeyTimeout", "()J");
return @__env.CallStaticLongMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m27);
}
public static float ScrollFriction
{
get
{
return getScrollFriction();
}
}
private static global::MonoJavaBridge.MethodId _m28;
public static float getScrollFriction()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m28.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m28 = @__env.GetStaticMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "getScrollFriction", "()F");
return @__env.CallStaticFloatMethod(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
public ViewConfiguration() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.ViewConfiguration._m29.native == global::System.IntPtr.Zero)
global::android.view.ViewConfiguration._m29 = @__env.GetMethodIDNoThrow(global::android.view.ViewConfiguration.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ViewConfiguration.staticClass, global::android.view.ViewConfiguration._m29);
Init(@__env, handle);
}
static ViewConfiguration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewConfiguration.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewConfiguration"));
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.